Legacy Modernization and Architecture Evolution Questions
Evolving an existing system rather than designing greenfield. Covers the modernization patterns (strangler fig, anti-corruption layers, facades and protocol adapters), choosing between rehosting, replatforming, incremental refactoring and a full rewrite, data migration and coexistence (dual-running, change-data-capture versus bulk cutover, reconciliation and drift), cutover readiness and decommissioning, recovering undocumented behavior from legacy code and stored procedures, instrumenting a migration so you can tell in real time whether it is working, and the organizational and risk management of long migrations across many teams. The scope is the migration itself: not quantifying or prioritizing technical debt, not code-level refactoring craft, not how to decompose a system into microservices, and not cloud migration or deployment and rollback mechanics as topics in their own right.
A legacy system speaks a protocol your new services do not (SOAP, a proprietary mainframe queue, or similar), and you need new consumers to work against it without waiting for the legacy side to change. Design the adapter layer that sits between them and describe how you would keep it from becoming a second system to maintain forever.
Sample Answer
Direct answer
Put a dedicated adapter service (not a shared library scattered across callers) between the legacy protocol and your new consumers, responsible for protocol translation, authentication bridging, and error-shape normalization, and treat it as a temporary, shrinking piece of infrastructure with an explicit plan to retire it, not a permanent integration point. The design decisions that matter most are where it lives (sidecar versus a shared gateway), how it handles the legacy system's throughput and latency ceiling, and how you keep it from quietly becoming a second system nobody wants to touch.
Structured elaboration
The core responsibilities of the adapter:
- Protocol translation: converting between the legacy wire format (SOAP, a proprietary queue protocol, fixed-width records) and whatever your new services speak (REST, gRPC, JSON).
- Schema and semantic mapping: legacy field names, units, and enums translated to the new domain model, the same discipline as an anti-corruption layer, because this adapter usually needs to be one.
- Authentication bridging: legacy systems often use older auth mechanisms (SAML, an older XML-based single sign-on standard; mutual certificates; static API keys); the adapter is where that gets exchanged for whatever your new services use, most commonly OAuth 2.0 tokens, with mTLS (mutual TLS) reserved for machine-to-machine cases rather than being an equally likely default.
- Backpressure and resilience: legacy systems frequently cannot handle the request volume a modern service mesh can generate. The adapter needs connection pooling, request batching, and its own rate limiting so it does not accidentally take down the legacy system it is protecting new consumers from.
On placement: a sidecar (deployed alongside each consuming service) minimizes added network hops and keeps the blast radius of a failure small, at the cost of deploying and versioning the adapter logic N times. A shared gateway centralizes the translation logic in one place, which is easier to evolve and monitor, at the cost of being a single point of failure and a potential throughput bottleneck if the legacy system's guaranteed-once processing requirements mean requests cannot simply be load balanced across replicas without care. For a small number of consumers with strict latency budgets, a sidecar is usually right; for many heterogeneous consumers, a shared gateway with careful capacity planning is usually right.
To avoid the adapter becoming permanent: track what fraction of the legacy system's capabilities still route through it, treat new special cases added to the adapter as a signal that a capability just got more entangled rather than less, and set an actual target date to revisit whether the adapter can start shrinking.
Worked example
A legacy mainframe payments system exposes a proprietary message-queue protocol with strict guaranteed-once processing semantics: the mainframe cannot handle duplicate submissions, and it cannot tell a modern REST client "I got that, don't worry." The adapter needs to:
- Accept REST requests from new services and assign each one an idempotency key before submitting to the mainframe queue, so a retried REST call does not become a duplicate mainframe transaction.
- Maintain a connection pool to the mainframe queue sized to its actual capacity, not the capacity of whatever load-balanced modern service is calling it, and queue or reject excess requests with a clear error rather than letting them silently pile up.
- Translate the mainframe's fixed-format response codes into REST status codes and structured error bodies the new services can actually branch on.
- Emit metrics on translation errors and latency added, since "how much is this adapter costing us" is exactly the number that later justifies (or delays) retiring it.
For the case where a third-party vendor keeps owning part of the flow (say, payment processing) for a bounded transition period, the same adapter pattern applies but with an explicit compatibility window: the adapter needs graceful-degradation fallback flows if the vendor's system is slow or down, SLA monitoring against the vendor's contracted latency, and a version-compatibility check so a vendor-side change does not silently break translation.
Trade-offs and pitfalls
The biggest pitfall is under-provisioning the adapter for the legacy system's real limits: a modern service tier can generate far more concurrent load than a mainframe queue was ever designed for, and the adapter's job is partly to be a deliberate throttle, not just a translator. The second is scope creep: once an adapter exists, it is tempting to route every new integration through it "since it's already there," which is exactly how a temporary migration aid becomes a permanent, poorly-owned piece of critical infrastructure that outlives the legacy system it was built to retire.
During a cutover period, you have two log files (one from the legacy system, one from its replacement) recording the requests each one processed, and you need to find every mismatch between them. The files are too large to hold in memory. Write a program that reconciles them.
Sample Answer
Direct answer
With only 4GB of RAM for up to 10 million records, you cannot hold both files in memory, so the approach is to partition both logs by a hash of the request ID into a fixed number of on-disk buckets, then compare each pair of buckets in memory one at a time. This bounds peak memory to roughly total_records / num_buckets regardless of how large the files get, and it avoids needing a full sort since equality comparison, not ordering, is all the reconciliation actually needs.
Structured elaboration
The two realistic strategies are external sort (sort both files by request_id using disk-backed merge sort, then compare in a single streaming pass) and hash-partitioning (split both files into N buckets by hash(request_id) % N, then compare bucket by bucket). Hash-partitioning is the better fit here: it's O(records) rather than O(n log n), it's simpler to implement correctly, and it naturally gives you a knob (the number of buckets) to directly control peak memory, since you can choose N so that records_per_bucket * bytes_per_record comfortably fits inside the RAM budget.
The algorithm:
- Partition pass: stream through each log file once, and for each record, compute
hash(request_id) % Nand append the line to the corresponding bucket file on disk. This pass never holds more than one line in memory at a time. - Compare pass: for each bucket index, load that bucket's legacy-side records into an in-memory dictionary keyed by request_id (this is the only point where records are held in memory, and it's bounded to one bucket's worth), then stream through that bucket's new-side records, looking each one up in the dictionary. This finds requests present in the new log but missing from the legacy log directly, and finds requests present in both but with differing responses. A final pass over the dictionary after streaming the new-side file finds requests present in the legacy log but missing from the new log.
- Aggregate results across all N buckets.
Peak memory is controlled entirely by N: doubling N roughly halves the number of records held in memory at once, at the cost of more file handles and a bit more I/O overhead from the partitioning pass. For 10 million records at, say, 150 bytes each in memory as a Python dict entry, a modest N (dozens, not thousands) comfortably fits a 4GB budget with room to spare for the rest of the process.
Worked example
import json, hashlib, os, tempfile, shutil
def bucket_index(request_id: str, n_buckets: int) -> int:
h = hashlib.blake2b(request_id.encode(), digest_size=8).digest()
return int.from_bytes(h, 'big') % n_buckets
def partition_file(path, n_buckets, out_dir, side):
writers = [open(os.path.join(out_dir, f'{side}_{i}.jsonl'), 'w') for i in range(n_buckets)]
try:
with open(path) as f:
for line in f:
line = line.strip()
if not line:
continue
rec = json.loads(line)
writers[bucket_index(rec['request_id'], n_buckets)].write(line + '\n')
finally:
for w in writers:
w.close()
def reconcile(legacy_path, new_path, n_buckets=8):
tmp = tempfile.mkdtemp(prefix='reconcile_')
try:
partition_file(legacy_path, n_buckets, tmp, 'legacy')
partition_file(new_path, n_buckets, tmp, 'new')
only_legacy, only_new, mismatched = [], [], []
for i in range(n_buckets):
legacy_map = {}
with open(os.path.join(tmp, f'legacy_{i}.jsonl')) as f:
for line in f:
rec = json.loads(line)
legacy_map[rec['request_id']] = rec
seen_new_ids = set()
with open(os.path.join(tmp, f'new_{i}.jsonl')) as f:
for line in f:
rec = json.loads(line)
rid = rec['request_id']
seen_new_ids.add(rid)
if rid not in legacy_map:
only_new.append(rid)
elif legacy_map[rid].get('response') != rec.get('response'):
mismatched.append((rid, legacy_map[rid], rec))
for rid in legacy_map:
if rid not in seen_new_ids:
only_legacy.append(rid)
return {'only_legacy': sorted(only_legacy), 'only_new': sorted(only_new),
'mismatched': sorted(mismatched, key=lambda x: x[0])}
finally:
shutil.rmtree(tmp, ignore_errors=True)
Executed against a synthetic fixture of 1,008 records (1,000 present in both logs with the same response, 5 present only in the legacy log, 3 present only in the new log, and 7 of the 1,000 common records deliberately given mismatched responses), with n_buckets=8: the function correctly identified all 5 legacy-only IDs, all 3 new-only IDs, and all 7 mismatched IDs with their differing response values, with the largest single bucket holding 138 records in memory at once, well within budget, and the same code scales to 10 million records simply by increasing n_buckets proportionally.
Trade-offs and pitfalls
The design assumes request IDs hash roughly uniformly across buckets, which is true for a well-distributed ID space (UUIDs, sequential IDs with a good hash function) but would break down and create an oversized "hot" bucket if IDs were, say, sequential integers hashed with a poor function that clusters them. The other real trap is choosing too few buckets and blowing the memory budget on one side of the comparison, which is why the implementation should assert or log the actual peak bucket size in production, rather than trusting the choice of N was right without measuring it.
A widely used internal tool has reached end of life and your team has to sunset it while everyone else still depends on it. How do you get people to actually move off it?
Sample Answer
Direct answer
Sunsetting a widely-used internal tool that's reached end of life without your own team's continued support means treating the other teams still depending on it as stakeholders you need to actively move, not just notify, which requires a real communication plan, a realistic timeline with margin, genuine incentives to migrate, and honest budgeting for both the sunset work and the disruption it causes the teams still relying on the tool.
Structured elaboration
- Communicate the decision and the why, early and repeatedly. Teams still depending on the tool need to hear the decision, the reasoning (why it's reached end of life, why continuing to support it isn't viable), and the timeline as early as possible, since the amount of lead time you give directly determines how smoothly other teams can actually plan their own migration work around it.
- A realistic migration timeline, not an aspirational one. Build in margin for the reality that other teams have their own priorities and won't necessarily treat migrating off your tool as urgent until the deadline is close, and plan communication checkpoints (not just a single announcement and a single deadline) to keep the migration visible on their radar throughout.
- Risk mitigation for the teams still on the old tool. If support is genuinely ending, what happens to a team that hasn't migrated by the deadline? A real risk mitigation plan names this explicitly (a hard cutoff with no further support, a limited best-effort extension for teams with a documented migration plan already underway, or something else), rather than leaving it ambiguous and discovering the answer only when the deadline actually arrives.
- Incentives to encourage migration, since asking teams to prioritize migrating off your tool competes directly against their own roadmap and incentives. Concrete incentives: dedicated migration support from your team for a limited window, a genuinely easier or better replacement that makes migrating a net win rather than a pure cost, or executive sponsorship that makes the deadline a real organizational priority rather than one team's internal decision that other teams can deprioritize.
- Budgeting and resourcing, both for your own team's sunset work and for the teams migrating off it. If teams need real engineering time to migrate, and that competes with their existing roadmap, the plan needs an honest accounting of that cost, ideally with a resourcing conversation happening at the same level (with the relevant managers or leadership) as the original decision to sunset the tool, not left as an unstated assumption.
Worked action framework
Sunsetting a widely-used internal ETL tool that's reached end of life:
- Stakeholder communication plan: an initial announcement six months before the planned sunset date, naming the reason (the tool's underlying dependency is itself end-of-life and a security risk to keep running), followed by monthly check-ins with each dependent team individually, not just broadcast announcements, tracking their specific migration progress.
- Migration timeline with margin: the announced deadline is set with a deliberate two-month buffer beyond the team's own internal target, based on past experience that dependent teams' actual migration pace tends to run behind their own initial estimates.
- Risk mitigation for the deadline: teams with a documented migration plan already in progress but not yet complete by the deadline get a defined, limited extension (30 days) with continued best-effort support; teams with no migration plan in progress by 60 days before the deadline get an explicit escalation to their leadership, making the risk visible before it becomes a crisis at the deadline itself.
- Incentives: the team offers dedicated migration office hours and a pre-built migration script covering the most common usage pattern, directly reducing the cost of migrating for teams that would otherwise have to figure it out from scratch, which meaningfully increases the number of teams that migrate proactively rather than waiting until the deadline forces them.
- Budgeting: the sunset effort itself (building the migration script, running office hours, maintaining the old tool through the transition window) is explicitly resourced as a project with allocated engineering time, rather than something the team is expected to absorb alongside its normal roadmap unfunded.
Trade-offs and pitfalls
The trade-off is the real cost of investing in migration tooling, incentives, and sustained communication against the alternative of a hard deadline with minimal support, which is cheaper for your own team in the short term but reliably produces a much worse outcome (teams caught unprepared, an escalation crisis right at the deadline, or a deadline that has to slip anyway because too many teams aren't ready). The pitfall to avoid is treating the initial announcement as sufficient communication; without sustained, individual check-ins, dependent teams reliably deprioritize a migration that isn't urgent yet, right up until it suddenly is, at which point there's no longer enough runway left to do it well.
You inherit a system with almost no documentation, dependencies nobody wrote down, and the one engineer who understood it just left. What do you actually do in the first weeks, and how do you avoid either freezing all feature work or making the risk worse?
Sample Answer
Direct answer
The first weeks are about reducing risk cheaply, not about rewriting anything: map what the system actually does and who depends on it, put a safety net under it (monitoring and tests) before touching the code, and only then start making small, reversible changes. The goal by day 90 is not "the system is modernized," it is "the system is no longer a black box, and the org has evidence about what's safe to touch," while feature work continues in parallel rather than freezing entirely.
Structured elaboration
A workable structure:
- Days 1 to 30, discovery. Build a dependency map using a combination of static analysis (what does the code call), dynamic tracing and log correlation (what actually happens in production, which is often different from what the code suggests), and conversations with anyone who has touched the system, since undocumented tribal knowledge is itself a source you have to capture before it walks out the door. This is also when you look for lightweight, low-production-impact ways to instrument the system if it has no observability at all.
- Days 30 to 60, safety net. Add monitoring and alerting so you would actually notice if something broke, and add characterization tests, tests that pin down the system's current behavior (correct or not) so a later change that alters that behavior gets caught immediately, rather than tests that assert what the behavior should be, which requires understanding the system better than you do yet.
- Days 60 to 90, first small changes. Make a handful of low-risk, reversible improvements, fixing the most painful operational issue, extracting the most clearly separable piece, and use these as a way to validate that your dependency map and safety net actually work, before committing to anything bigger.
Throughout, the discovery approach itself matters: static analysis alone misses runtime-only dependencies (a job triggered by a cron entry nobody documented, a hidden call made only under a rare condition), so combining it with dynamic tracing, network traffic capture, and log correlation catches what static analysis alone would miss, at low production impact since these are observational techniques, not changes to the system itself.
To avoid freezing feature work: communicate explicitly that discovery and safety-net work is happening in parallel with, not instead of, feature delivery, and pick the first few changes specifically because they are small enough not to threaten the delivery timeline while still proving the approach works.
Worked example
An engineer inherits a legacy payment-reconciliation service: no documentation, three flaky integration tests, and the one person who understood it left six months ago.
- Week 1 to 2: they run static analysis to find every internal call path, and separately turn on request logging (a low-impact, purely observational change) to see what actually gets called in production. The two do not fully agree: static analysis misses a nightly batch job triggered by an external cron system nobody had documented, which the logs reveal because it shows up as unexplained traffic at 2am.
- Week 3 to 6: they build monitoring on the reconciliation service's key outputs (does the daily reconciliation total match expectations) so a regression would actually be visible, and write characterization tests around the three most business-critical code paths, capturing current behavior rather than guessing at intended behavior.
- Week 7 to 12: with the safety net in place, they fix the most painful operational issue (a memory leak that forces a weekly manual restart) as the first real change, verify the characterization tests and monitoring both catch the change as expected (a sanity check that the safety net itself works), and report back to stakeholders with an actual map of the system's dependencies and risk areas, rather than a vague "it's better now."
Trade-offs and pitfalls
The tempting shortcut is to skip straight to fixing the most obviously bad code, but without a dependency map and a safety net first, you cannot tell whether a "fix" broke something you didn't know depended on the old behavior, which is exactly how well-intentioned early changes to an undocumented system make things worse rather than better. The other trap is treating discovery as a one-time exercise rather than an ongoing habit; legacy systems that have been running for years often have dependencies that only surface under conditions (end of quarter, a specific customer's data shape) you will not see in the first 90 days no matter how thorough you are.
Compare rehosting, replatforming, incremental refactoring, and a full rewrite as ways to modernize an existing system. When does each one actually win, and what does 'winning' mean differently for each?
Sample Answer
Direct answer
Rehosting moves a system as-is onto new infrastructure and wins on speed when the goal is escaping unsupported hardware or a data center exit deadline. Replatforming makes small, targeted changes (a managed database instead of a self-hosted one) and wins when you want some operational benefit without touching application logic. Incremental refactoring decomposes and modernizes the system piece by piece and wins when the system needs to keep evolving and the team can invest in an ongoing effort. A full rewrite replaces the system outright and wins only when the existing system's structure is so far from what's needed that incremental change would cost more than starting over, and the business can tolerate the risk of an all-or-nothing delivery.
Structured elaboration
The real differentiator between these isn't just cost or time, it's what risk each one is willing to accept:
- Rehosting (lift-and-shift): lowest technical risk (nothing about the application changes), fastest to execute, but it changes nothing about the underlying problems (scaling limits, unmaintainable code, licensing costs tied to the old platform). It's a stopgap, not a fix, and it's the right first move when there's a hard deadline (end-of-life hardware, a data center closing) that leaves no time for anything deeper.
- Replatforming: moderate risk, moderate benefit. You get real operational wins (managed backups, autoscaling) without the risk of touching business logic, but you're still carrying whatever architectural debt the application has.
- Incremental refactoring: this is the strangler-fig territory, higher effort spread over a longer timeline, but continuously shippable and reversible at almost any point. It's the right choice when the system needs to keep serving traffic and evolving, and the org can sustain the discipline of an ongoing migration rather than a one-time project.
- Full rewrite: highest risk, because you're betting the whole effort on an estimate for a system whose exact current behavior nobody has fully mapped, the same problem that makes writing "characterization tests first" so important for any legacy work. It sometimes wins on relative cost and time if the existing system is small enough, or so entangled that incremental extraction genuinely doesn't have a viable seam.
Pairing the approach with a rollout strategy that matches its risk profile: rehosting and replatforming can usually go through a single cutover with a tested rollback plan, since the application behavior itself hasn't changed. Incremental refactoring needs the parallel-run and gradual-traffic-shift discipline strangler-fig migrations use. A full rewrite needs the most conservative rollout of all: extensive parallel-run validation against the old system before the new one is trusted with any real traffic, since there is no incremental fallback if a whole rewritten system turns out to be subtly wrong.
Worked example
A 15-year-old monolith running on infrastructure the vendor is discontinuing support for in six months:
- Rehost first: the deadline leaves no time for anything else, so the team moves it to modern infrastructure unchanged, buying time.
- Then decide the target: with the deadline pressure gone, they evaluate the system properly. It has clear, separable modules (billing, notifications, reporting), so incremental refactoring via strangler fig is viable, and they start extracting the highest-pain module (notifications, which changes often and causes frequent incidents) first, using canary rollout (releasing the change to a small slice of traffic first, so a problem shows up as an early warning instead of a full outage) and parallel-run validation to de-risk each extraction.
- They explicitly rule out a full rewrite: the modules are separable enough that strangling costs less in both time and risk than a rewrite would, given the amount of undocumented behavior a rewrite would have to somehow rediscover from scratch.
Trade-offs and pitfalls
The mistake that costs the most is picking based on which approach sounds most technically satisfying rather than which one matches the actual constraint (a hard deadline favors rehosting regardless of its long-term limitations; a system that genuinely cannot be decomposed favors a rewrite regardless of the risk). The second most common mistake is pairing a high-risk approach (a full rewrite) with a rollout strategy suited to a low-risk one (a single cutover), which is how a rewrite that was individually well-executed still causes an incident, because nobody validated it against real production behavior before trusting it fully.
Unlock Full Question Bank
Get access to all 22 Legacy Modernization and Architecture Evolution interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.