Amazon Software Engineer Interview Prep Guide
Everything Amazon actually asks Software Engineer candidates — concept walkthroughs, worked examples, and the real interview questions, drawn from candidate reports. Free to read.
Last updated

Focus most on practical AWS platform engineering: EKS/Kubernetes operations, Terraform state and drift, Jenkins/CI/CD deployment strategies, IAM/security, observability, and production incident troubleshooting, while keeping coding centered on strings, hash maps, caching, and operational scripting rather than advanced DSA. You self-rated System Design and Behavioral 4/5 with many solid concept ratings, so distributed systems basics, top-K streaming, and standard STAR structure are review areas rather than from-scratch study. For Amazon, this plan highlights Leadership Principles through ownership and incident stories, AWS cloud networking and IAM, durable distributed schedulers, cache design, and operational excellence trade-offs. With 1–2 weeks, use this as a roughly 2.5-hour first-pass cheatsheet, then spend remaining time on mock troubleshooting, architecture whiteboarding, and story rehearsal.
Technical Screen — 61 min
Behavioral & Leadership
- Leadership Principles And STAR Stories (Focus) — covered in depth under Onsite below.
Coding & Algorithms
-
Arrays, Strings, Hash Maps, And Frequency Counting (Focus) — covered in depth under Take-home Project below.
-
LRU Cache And O(1) Data Structures (Focus) — covered in depth under Onsite below.
System Design
Focus area — AWS architecture, networking, IAM, security, HA, and disaster recovery are load-bearing requirements and several related ratings are shaky.
What's being tested
Candidates must demonstrate practical cloud networking and CIDR fundamentals plus secure system design judgment: how to partition IP space, enforce least-privilege network controls, and choose management/storage patterns that support scale, availability, and audits. Interviewers look for crisp clarifying questions, correct bitwise/prefix reasoning, and tradeoffs between cost, operational complexity, and security posture—skills a Software Engineer uses when designing services and APIs that run in a cloud VPC.
Core knowledge
-
CIDR and prefix math: number of addresses in a prefix
/pis . A/24= 256 addresses, usable hosts often but cloud providers may reserve additional addresses. -
VPC and subnet semantics: a VPC is an L3 container; subnets map to AZs. Plan subnets per AZ to enable high availability and failure-domain isolation.
-
Security group vs NACL: security groups are stateful (return traffic allowed automatically), NACLs are stateless and evaluate per-packet; both use allow/deny but precedence and order differ.
-
Route table basics: longest-prefix match decides next hop; default routes (0.0.0.0/0) send to IGW/NAT. Multiple route tables let you split traffic control per subnet.
-
IP address management (IPAM): avoid fragmentation by allocating in powers-of-two blocks; reserve hot pools for growth and ephemeral needs (autoscaling, CI runners).
-
NAT design and egress: NAT gateway (managed, scalable, cost-per-hour) vs instance NAT (cheaper at low scale, operational overhead); consider bandwidth and single-point-of-failure.
-
Perimeter and L7 controls: use ALB/NLB, WAF, and ingress controllers for public endpoints; terminate TLS at the edge or via a service mesh depending on threat model.
-
Storage tradeoffs: EBS for single-instance block storage, EFS for POSIX shared mounts, S3 for object storage and high-throughput read-heavy workloads; choose encryption-at-rest and lifecycle policies.
-
Identity & access: use IAM roles for service principals, SAML SSO for human access, and role assumption for cross-account access; avoid long-lived credentials and prefer short-lived tokens.
-
Observability & auditing: enable VPC Flow Logs, centralized logging (
CloudWatch/ELK) and config auditing. Log retention and indexing affect cost—prioritize for critical flows. -
Encryption & networking: apply TLS end-to-end for public and internal traffic if the threat model requires, and consider mTLS for service-to-service authentication in zero-trust designs.
-
IPv6 considerations: IPv6 removes address exhaustion but changes NAT assumptions; plan dual-stack if external client reachability or privacy requirements demand it.
Tip: sketch a small CIDR map on the whiteboard early — it shows you understand constraints and avoids later rework.
Worked example: Design secure multi-tier cloud infrastructure
First 30 seconds: ask clarifying questions — expected scale (RPS, number of hosts), compliance/regulatory constraints, public vs private endpoints, DR / RTO targets, and whether multi-account tenancy is required. Skeleton: (1) Network segmentation: public subnets for load balancers, private app subnets, isolated DB subnets; subnets per AZ for HA. (2) Perimeter & L7 controls: place an ALB/NLB in public subnets, terminate TLS with a certificate manager, add a WAF for OWASP class protections. (3) Access rules and identity: use security groups for instance-level access, NACLs for coarse-layer filtering, IAM roles for services and SAML SSO for users. (4) Management & observability: enable VPC Flow Logs, centralized metrics, and patching via Systems Manager. One tradeoff to flag: NAT gateway cost versus instance NAT — NAT gateway simplifies operations and scales, but at high egress volume instance NAT with autoscaling or using egress proxies may be cheaper. Close by outlining rollout: prototype with IaC (Terraform/CloudFormation), run security tests, and iterate on CIDR sizes and monitoring; note you'd also design automated incident playbooks and periodic access reviews if given more time.
A second angle: Evaluate IP Access Rules
This framing focuses on bitwise and precedence logic. Start by formalizing rule semantics: each rule is (action, direction, CIDR, port/proto), and evaluation must handle overlapping CIDRs and precedence. Algorithmically, use a longest-prefix match (LPM) trie for fast lookup; worst-case lookup is proportional to address bit-length (32 for IPv4). Be explicit about tie-breaking: most systems apply the most-specific (longest) prefix first; if equal prefix-lengths exist, either first-match or explicit priority decides allow/deny. For correctness, test edge cases: /32 exact matches, 0.0.0.0/0 fallback, and combined allow/deny conflicts. Implement unit tests that exercise overlapping prefixes and rule reordering to ensure deterministic behavior.
Common pitfalls
Pitfall: Wrong CIDR sizing — Candidates often pick a tight subnet (
/28etc.) without growth headroom, forcing disruptive re-IP later. Always reserve growth pools and show how you'd expand or use NAT-ing patterns to defer readdressing.
Pitfall: Confusing security groups with NACLs — A common mistake is expecting NACL statefulness; call out stateful security groups for service-level allow rules and NACLs for stateless, coarse network filters.
Pitfall: Overprivileged identities — granting blanket
*IAM permissions or sharing long-lived keys looks efficient but fails audits; prefer role assumption, least privilege, and short-lived credentials, and describe proof of rotation and audit hooks.
Connections
Interviewers may pivot to related topics like service-to-service auth (mTLS, token exchange), load balancing/health checks, kubernetes network policies, or IPAM tooling and automation (Terraform, AWS IPAM). Being able to map your VPC design to containerized deployments and service meshes is valuable.
Further reading
-
AWS VPC User Guide — practical reference for VPC, subnets, security groups, NACLs, and route tables.
-
RFC 4632 - Classless Inter-Domain Routing (CIDR) — authoritative explanation of prefix notation and aggregation.
-
Zero Trust Networks (book) — practical patterns for least-privilege network architecture and service-to-service authentication.
Practice questions
Software Engineering Fundamentals
-
Python/Bash And Linux Operational Scripting (Focus) — covered in depth under Take-home Project below.
-
Kubernetes, EKS, And Container Operations (Focus) — covered in depth under Onsite below.
-
Production Incidents, Observability, And Troubleshooting (Focus) — covered in depth under Onsite below.
-
Object-Oriented Design And Concurrency-Safe LLD (Focus) — covered in depth under Onsite below.
Onsite — 73 min
Behavioral & Leadership
Leadership Principles And STAR Stories
Focus areaFocus area — Despite 4/5 behavioral confidence, you explicitly want ownership, incident management, leadership, conflict, and real project stories for Amazon.

What's being tested
Amazon behavioral interviews test whether you can demonstrate Leadership Principles through concrete engineering judgment, not whether you can recite values. For a Software Engineer, the interviewer is probing how you debug ambiguous systems, make tradeoffs under pressure, own production outcomes, raise quality bars, and work across teams without authority. Strong answers show specific technical context, measurable impact, and personal accountability: what you did, why it mattered, what alternatives you considered, and what you learned. Expect deep follow-ups on details like failure modes, metrics, incident timelines, code-review decisions, and whether your actions would scale beyond one heroic fix.
Core knowledge
-
STAR means Situation, Task, Action, Result. For Amazon, the Action section should be the longest: roughly 10% context, 10% goal, 60% your decisions/actions, 20% measurable results and lessons.
-
Ownership stories should show you acted beyond your narrow ticket. Good SWE examples include fixing a flaky
`CI`pipeline, improving an unowned service’s`p99`latency, writing a runbook after an incident, or taking responsibility for a bad deployment even when another team contributed. -
Dive Deep requires technical specificity. Be ready to explain logs, dashboards, traces, database queries, thread dumps, memory profiles, cache behavior, retries, timeouts, race conditions, and why the first plausible root cause was wrong.
-
Customer Obsession for engineers usually maps to reliability, latency, correctness, accessibility, security, or developer experience. Tie work to concrete outcomes: reduced checkout errors from
`1.2%`to`0.3%`, cut`p95`API latency from`900ms`to`220ms`, or reduced support tickets by`35%`. -
Bias for Action is not “move fast and break things.” Strong answers show bounded risk: feature flags, canary deployments, rollback plans, read-only migrations, dark launches, rate limits, or temporary mitigations while a permanent fix is built.
-
Insist on the Highest Standards should include quality mechanisms, not perfectionism. Mention code reviews, test coverage, load testing, static analysis,
`SLO`alerts, backward-compatible APIs, migration validation, or eliminating an entire class of bugs through tooling. -
Invent and Simplify is especially relevant when you reduce operational complexity. Examples: replacing manual deployments with one-click pipelines, consolidating duplicate services, simplifying an API contract, removing a brittle dependency, or turning tribal knowledge into automation.
-
Have Backbone; Disagree and Commit should show respectful escalation using evidence. For SWE, evidence might include load-test results, error-budget burn, security risk, operational burden, or a prototype comparing two designs. Once a decision is made, show you supported execution.
-
Deliver Results stories need constraints. State the deadline, dependency, ambiguity, or resource limit. Then explain prioritization: what you cut, deferred, automated, delegated, or simplified to ship safely without hiding quality risks.
-
Earn Trust is demonstrated through transparency and follow-through. In engineering stories, this can mean posting an incident update, admitting a regression you caused, documenting tradeoffs, giving credit, asking for review early, or making a decision visible in an
`ADR`. -
Measured impact matters even when the story is behavioral. Use engineering metrics such as
`MTTR`,`MTTD`, deployment frequency, rollback rate,`p95`/`p99`latency, error rate, availability, test flakiness, build time, memory usage, CPU utilization, or defect escape rate. -
Follow-up readiness is critical. Interviewers often ask: “What exactly did you do?”, “What data did you inspect?”, “Who disagreed?”, “What would you do differently?”, “How did you know it worked?”, and “Was this really your contribution?”
Worked example
For “Answer Dive Deep and Ownership in LP interview”, a strong candidate should frame the story in the first 30 seconds as a production or near-production problem with measurable customer or operational impact. For example: “I’ll use a story where our order-status API had intermittent `5xx` spikes after a deployment; I was not the original owner, but I was on call and drove root cause, mitigation, and prevention.” Clarify the scale briefly: request volume, severity, affected customers, and whether there was an `SLA` or `SLO` at risk.
Organize the answer around four pillars: first, detection and triage; second, technical investigation; third, mitigation and communication; fourth, long-term prevention. In the investigation pillar, go beyond “I checked logs” and name the actual reasoning path: comparing deploy timestamps with error spikes, isolating one dependency, finding retry amplification, verifying with traces, and reproducing under load. A good tradeoff to flag is mitigation versus root cause: “I rolled back first to stop customer impact, then used the failed build in staging to preserve evidence and continue debugging.”
The result should include numbers: `5xx` rate dropped from `8%` to baseline, `MTTR` was `37 minutes`, and a follow-up change reduced similar incidents by adding timeout budgets, circuit breakers, and an alert on dependency saturation. Close with learning: “If I had more time, I would have added pre-production load tests for retry storms earlier and documented a dependency-failure checklist for the on-call rotation.” This shows you owned both the immediate fix and the systemic improvement.
A second angle
For “Answer Amazon-style leadership deep dives”, the same storytelling discipline applies, but the interviewer may focus less on one incident and more on decision-making, conflict, or influence. Suppose the story is about disagreeing with a proposed synchronous service call in a checkout path. The framing should emphasize the engineering tradeoff: synchronous simplicity versus availability risk, latency budget, and blast radius. Instead of centering the narrative on logs and root cause, center it on evidence, stakeholder alignment, and commitment after the decision. A strong answer would mention a prototype, `p99` latency estimates, failure-mode analysis, and how you either persuaded the team or committed to the chosen design while adding safeguards.
Common pitfalls
Pitfall: Giving a generic values answer instead of an engineering story.
A weak answer says, “I always take ownership and communicate well.” A stronger answer names the service, the bug, the metric, the decision you made, and the result. Amazon interviewers will keep drilling until they can separate your actual contribution from the team’s general effort.
Pitfall: Over-indexing on heroics and under-indexing on mechanisms.
“I stayed up all night and fixed production” may sound committed, but it can also signal fragile operations. Pair urgency with scalable mechanisms: alerts, runbooks, tests, deployment guards, code ownership, post-incident reviews, and prevention of repeat failures.
Pitfall: Hiding conflict, mistakes, or tradeoffs.
Perfect stories often sound rehearsed and shallow. It is usually better to say, “My first hypothesis was wrong,” “I shipped a mitigation with known limitations,” or “I disagreed with the design because of `p99` latency risk.” Then show how you used data, communicated clearly, and improved the system.
Connections
Interviewers often pivot from behavioral stories into system design, especially around reliability, scalability, and operational excellence. They may also ask for debugging deep dives, code quality tradeoffs, incident management, or cross-team design negotiation. Prepare each story so it can support both a leadership principle discussion and a technical follow-up.
Further reading
-
Amazon Leadership Principles — official source for the principles and the language interviewers use.
-
The Site Reliability Workbook — practical mechanisms for incident response, reliability, alerting, and operational ownership.
-
How Complex Systems Fail — Richard I. Cook — useful mental model for explaining incidents without oversimplifying root cause.
Practice questions
Coding & Algorithms
- Arrays, Strings, Hash Maps, And Frequency Counting (Focus) — covered in depth under Take-home Project below.
LRU Cache And O(1) Data Structures
Focus areaFocus area — You selected key-value stores, caching, eviction, and cache invalidation; Amazon often probes cache semantics and trade-offs.

What's being tested
This tests O(1) mutable data structure design, usually combining a hash map with a doubly linked list to implement cache lookup, recency updates, insertion, and eviction. Interviewers are probing whether you can preserve invariants under get, put, update-existing, capacity overflow, and missing-key cases.
Patterns & templates
-
Hash map + doubly linked list — map
key -> node; list stores recency order;getandputareO(1)average time. -
Sentinel head/tail nodes simplify list mutations —
addToFront(node),remove(node),moveToFront(node),popTail()avoid null-heavy edge cases. -
LRU semantics — successful
get(key)updates recency;put(existingKey, value)updates value and recency; eviction removes least-recently-used node. -
Capacity handling — after inserting a new key, if
size > capacity, evict tail node and delete its key from the map. -
Cache optimization framing — define cache key, cached value, invalidation/TTL, memory bound, expected hit rate, and worst-case behavior before coding.
-
Complexity contract — state
O(1)average time due to hash map,O(capacity)space; note hash collision worst case if interviewer asks. -
Thread-safety extension — single mutex is simple and correct; finer-grained locking improves throughput but complicates recency-list consistency.
Common pitfalls
Pitfall: Using only a hash map gives fast lookup but no
O(1)way to find and remove the least-recently-used item.
Pitfall: Forgetting that
getmust update recency causes subtle failures on eviction-order tests.
Pitfall: Evicting from the list but not deleting from the map leaves stale nodes and incorrect future lookups.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
System Design
Distributed Job Scheduler Systems
Focus areaFocus area — You selected distributed job scheduling and platform reliability; emphasize leases, retries, idempotency, backoff, and worker failure recovery.
What's being tested
Interviewers are probing whether you can design a reliable distributed scheduler that turns future-time requests into actual execution while handling scale, failures, duplicate delivery, and clock/time-zone edge cases. For Amazon-style systems, this matters because many services depend on deferred work: retries, reminders, payments, fulfillment workflows, cleanup, batch fanout, and SLA-driven automation. A strong Software Engineer answer shows you can separate job definition, schedule computation, durable persistence, dispatch, and worker execution, then reason about the failure modes between each boundary. The interviewer is not looking for a single “perfect” architecture; they want crisp tradeoffs around correctness, latency, throughput, and operability.
Core knowledge
-
One-off jobs and recurring jobs should be modeled differently. A one-off job stores
run_at; a recurring job stores a schedule expression such ascron,interval, orrate, plustimezone,next_run_at, and recurrence metadata. Store future occurrences lazily rather than materializing infinite schedules. -
Durable storage is the source of truth. Use
DynamoDB,Postgres,MySQL, or similar to persistjob_id,tenant_id,run_at,payload_ref,status,attempt_count,dedupe_key, and timestamps. A scheduler that only keeps jobs in memory loses work on restart and usually fails the reliability bar. -
Scheduling algorithms depend on scale and latency targets. A single-node min-heap works for small systems, with
O(log n)insert and pop. At larger scale, use time-bucketed partitions, database range scans onrun_at, or a hierarchical timing wheel for high-throughput near-future timers. -
Polling plus claiming is a common durable pattern. Scheduler nodes query due rows where
run_at <= now()andstatus = SCHEDULED, then atomically transition toCLAIMEDusing compare-and-swap,SELECT ... FOR UPDATE SKIP LOCKED, or conditional writes. Claiming prevents many schedulers from dispatching the same job simultaneously. -
Sharding keeps due-job scans bounded. Partition by time bucket and hash, for example
bucket = floor(run_at / 60s)andshard = hash(job_id) % N. This gives roughly and avoids one hot partition for a popular timestamp like midnight. -
Delivery semantics are usually at-least-once, not exactly-once. Network failures make “did the worker execute?” ambiguous. Design for duplicate dispatch using idempotency keys, dedupe tables, conditional state transitions, and business-level safeguards rather than promising exactly-once execution.
-
Idempotency belongs at the job effect boundary. If the job sends an email, charges a card, or updates an order, pass a stable
idempotency_keyto the downstream service. Stripe-style idempotency keys are a useful mental model: repeated requests with the same key should produce one logical effect. -
Retries need bounded policy, not infinite loops. Store
attempt_count,max_attempts,last_error, andnext_retry_at. Use exponential backoff with jitter, e.g.delay = min(base * 2^attempt, max_delay) + random_jitter, to avoid thundering herds after regional or dependency outages. -
Leases handle scheduler and worker crashes. A claimed job should have
lease_until; if a node dies, another node can reclaim it after the lease expires. Use fencing tokens or monotonically increasingclaim_versionto prevent stale workers from committing after their lease is no longer valid. -
Recurring schedules require careful time handling. Store timestamps in UTC, but preserve the user’s
timezonefor computing the next local occurrence. Daylight Saving Time creates nonexistent times, duplicated times, and “last day of month” ambiguity; state your policy explicitly. -
Queues decouple dispatch from execution. The scheduler can enqueue due work into
SQS,Kafka,RabbitMQ, or an internal work queue, while workers consume and execute. Note limits:SQSdelay queues are useful for short delays but max delay is 15 minutes, so long-term scheduling still needs durable storage. -
Observability should include correctness and latency signals. Track
schedule_lag = dispatch_time - run_at, queue depth, due jobs per shard, claim conflicts, retry rate, dead-letter count, worker success rate, andp99dispatch latency. These metrics reveal hot shards, stuck schedulers, and downstream dependency failures.
Worked example
For “Design a scalable job scheduler”, a strong candidate would start by clarifying the scale and semantics: “Are jobs one-off, recurring, or both? What is acceptable scheduling latency, seconds or minutes? Is execution at-least-once acceptable if workers are idempotent? What job volume and payload size should I assume?” Then they might declare assumptions: 100M stored jobs, 100K due per minute at peak, second-to-minute precision, and at-least-once delivery.
The answer should be organized around four pillars: API and data model, durable scheduling store, scheduler/dispatcher architecture, and worker execution with retries and idempotency. For the API, propose CreateJob, CancelJob, GetJob, and maybe CreateRecurringSchedule, with stable job_id and optional client-provided dedupe_key. For storage, describe a table indexed by run_at or time buckets, plus sharding by hash to avoid a single partition scanning all due work.
For dispatch, explain that multiple scheduler nodes poll assigned shards, atomically claim due jobs, enqueue them to a work queue, and mark them dispatched only after successful enqueue. For workers, describe idempotent execution, retry with backoff, and a dead-letter state after max_attempts. One tradeoff to flag explicitly: scanning durable storage every second is simple but expensive at very high scale; time buckets or a timing wheel reduce scans but add complexity in rebalancing and recovery. Close by saying that with more time you would drill into multi-region behavior, recurring-job DST rules, operational dashboards, and backpressure during dependency outages.
A second angle
For “Design delayed job scheduler (LLD)”, the same concepts apply, but the interviewer is likely pushing for lower-level class design and concurrency behavior. Instead of starting with multiple regions and millions of tenants, focus on interfaces like JobStore, DelayQueue, SchedulerLoop, WorkerPool, and RetryPolicy. You should be ready to discuss whether the in-memory structure is a priority queue, delay queue, or timing wheel, and how it reloads from durable storage after restart. The key distinction is that an LLD answer needs concrete state transitions, locking or atomic update behavior, and testable components rather than only boxes on an architecture diagram. You can still mention distributed concerns, but anchor them in methods such as claimDueJobs(now, limit), extendLease(jobId, token), and completeJob(jobId, token).
Common pitfalls
Pitfall: Promising exactly-once execution.
A tempting answer is “the scheduler will ensure each job runs exactly once.” In distributed systems, a scheduler can crash after dispatching but before recording success, or a worker can complete while the acknowledgment is lost. A better answer is: “The scheduler provides at-least-once delivery, and downstream effects are protected with idempotency keys and conditional writes.”
Pitfall: Treating time as simple.
Many candidates say “store a cron expression and run it at the right time” without addressing time zones, DST, leap days, or clock skew. Stronger candidates store execution timestamps in UTC, preserve the user’s intended timezone for recurrence computation, use NTP-synchronized clocks, and state a policy for nonexistent or duplicated local times.
Pitfall: Drawing components without explaining state transitions.
A box diagram with API -> DB -> Queue -> Workers is not enough. The interviewer needs to hear how a job moves from SCHEDULED to CLAIMED to ENQUEUED to RUNNING to SUCCEEDED or FAILED, and what happens if a process dies between any two steps.
Connections
This topic often pivots into distributed queues, leader election, workflow orchestration, rate limiting, and idempotent API design. Be prepared to compare a custom scheduler with managed systems such as SQS, EventBridge Scheduler, Quartz, Airflow, or Temporal, especially around durability, retries, dependencies, and operational complexity.
Further reading
-
Designing Data-Intensive Applications — excellent background on replication, partitions, logs, consistency, and failure handling in distributed systems.
-
The Google File System paper — useful for understanding leases, master coordination, and failure-tolerant distributed design patterns.
-
Amazon Builders’ Library: Timeouts, retries, and backoff with jitter — directly relevant to retry policy, overload control, and avoiding retry storms.
Practice questions
- Terraform IaC, State, Modules, And Drift Management (Focus) — covered in depth under Take-home Project below.
Focus area — You called out Jenkins, CI/CD, GitHub Actions, deployment strategies, gates, health checks, and rollback automation.
What's being tested
Candidates must show practical mastery of CI/CD pipeline design and deployment strategies that enable safe, repeatable releases: you should reason about build artifacts, automated tests, deployment orchestration, traffic shifting, health gating, and rollback mechanics. Interviewers probe for clear tradeoffs between Blue-Green and Canary approaches, how to automate rollback triggers, and what an engineer owns (pipeline code, deployment manifests, health checks) versus what infra teams own (cluster provisioning, load balancers). Expect to justify choices with failure modes, metrics, and recovery SLAs.
Core knowledge
-
CI/CD fundamentals: separate build, test, and deploy stages; produce an immutable artifact (e.g., Docker image tagged by SHA) that moves through environments to ensure repeatability and traceability.
-
Jenkinspipeline patterns: use declarative pipelines, stage-levelpoststeps for cleanup, credentials binding, and store artifacts in a registry (ECR,DockerHub) and metadata in the pipeline (build number, git SHA). -
Blue-Green deployment: maintain two identical environments (
blue,green), switch traffic at router/ELBlevel for near-instant rollback by flipping the virtual IP or load-balancer target set; zero-downtime but requires double capacity. -
Canary deployment: progressively shift traffic (e.g., 1%, 5%, 25%, 100%) to new version; useful when capacity is limited and you want fine-grained risk control; requires automated metrics gating.
-
Automated canary analysis (ACA): compare
baselinevscandidateon metrics likeerror rate,p95latency, business metrics; use statistical thresholds and time windows to avoid false positives (e.g., require sustained deviation for T minutes). -
Rollback types: instant rollback (flip back traffic or redeploy previous image), graceful rollback (drain connections, let sessions expire), and stateful rollback caveats (DB migrations are often irreversible—apply backward-compatible migration patterns).
-
Health checks and readiness probes:
livenessvsreadinessinKubernetes; readiness gating prevents load balancer from sending traffic until service is healthy; build health-check endpoints that are cheap, deterministic, and reflect real user paths. -
Observability signals: track
error rate,latencypercentiles (p50,p95,p99),saturation(CPU, memory), request counts, and key business metrics; compute relative change and signal-to-noise; maintain rolling windows (e.g., compare last 5m vs previous 30m). -
Feature flags: separate code rollout from deployment; use feature flags for controlled exposure and fast rollback by toggling flags rather than redeploying; beware flag debt and stale branches.
-
Idempotency and migration safety: design deploys to be idempotent; for DB schema changes, prefer backward-compatible multi-step migrations (add column → backfill → switch read → remove old code).
-
Testing strategy: unit tests in CI, integration tests in an isolated environment, smoke tests post-deploy (synthetic requests hitting core flows), and end-to-end checks that anchor to business metrics.
-
Cost / capacity tradeoffs: Blue-Green doubles runtime capacity; Canary reduces capacity overhead but increases orchestration complexity. Quantify: double capacity cost = 2x active instance count; canary requires fine-grained routing and metrics automation.
Tip: automate gating rules in the pipeline (e.g., fail if
error rateincreases by >50% for 5 minutes), and expose a manual override for on-call.
Worked example
Design a CI/CD pipeline using Jenkins to support Blue-Green deployments with automated rollback. Frame the problem: ask about target platform (Kubernetes, EC2 behind ELB), traffic-shift mechanism, acceptable downtime, and rollback SLOs. Skeleton answer pillars: 1) build immutable Docker images and push to registry with metadata (git SHA, build ID); 2) automated test stages (unit, integration, contract) then deploy to staging for smoke tests; 3) deploy to green (the new environment) while blue serves traffic, run health checks and smoke tests; 4) switch traffic at ELB/ingress when green passes, monitor key metrics and trigger rollback on predefined conditions. Flag a tradeoff: blue-green gives immediate rollback (flip back) but requires 2x instances; if double capacity is unaffordable, prefer canary. Close with extension: "if I had more time, I'd add automated canary analysis for metric drift, integrate a feature-flag toggle for risky features, and wire the pipeline into on-call runbooks."
A second angle
Implementing a Canary rollout that progressively shifts traffic with automated health gating changes the orchestration details. Instead of two full environments, you run both versions concurrently on the same cluster and use traffic-splitting at the ingress or service mesh (Istio) level. Key constraints: determine canary percentages and cadence (e.g., 1% for 10 minutes → 5% for 15 minutes → 25% for 30 minutes), define statistical tests to compare baseline/canary metrics, and ensure sample sizes are sufficient for signal detection. This framing emphasizes metric sensitivity and automation (ACA), and it forces you to reason about routing, sticky sessions, and test-exposure bias (canary users may not represent all user segments), unlike blue-green which is binary.
Common pitfalls
Pitfall: Underestimating observability needs. Many engineers implement traffic switch logic but fail to define the exact metrics, thresholds, windows, and rollback playbook; this leads to delayed detection or noisy false positives.
Pitfall: Treating DB migrations as reversible. A tempting quick rollback is to redeploy the old binary, but irreversible schema changes will break the old code; always plan backward-compatible migrations and multi-step rollout.
Pitfall: Over-communicating detail or under-scoping responsibilities. As a Software Engineer, own pipeline code, health checks, and artifact immutability; do not assume you'll provision infra or change load-balancer internals without clarifying team boundaries.
Connections
Interviewers may pivot to feature-flag strategies, the design of health-check endpoints and synthetic testing, or how services coordinate schema migrations (backward-compatible migrations and data pipelines). They may also ask about integrating service meshes (Istio) or CD tools (Spinnaker) for advanced traffic control.
Further reading
-
[Continuous Delivery by Jez Humble & David Farley] — canonical book on deployability and deployment patterns.
-
Martin Fowler – Blue-Green Deployment — concise pros/cons and implementation notes.
Practice questions
Focus area — You named Kubernetes, EKS, Docker, Helm, networking, scheduling, and production troubleshooting as core interview priorities.
What's being tested
Interviewers are probing whether you can design, run, and debug cloud-native applications that behave correctly inside Kubernetes on AWS (`EKS`) without relying on a cluster administrator. Expect questions that test your knowledge of container lifecycle, resource accounting and QoS, deployment strategies (zero-downtime, canary), observability/debugging patterns, and how application design interacts with Kubernetes primitives. Amazon cares because service owners must build resilient microservices that degrade gracefully, autoscale predictably, and minimize operational blast radius.
Core knowledge
-
Pod / Container lifecycle: A Pod is the atomic deployable unit; container termination receives
SIGTERMthenSIGKILLafterterminationGracePeriodSeconds. Implement graceful shutdown handlers andpreStophooks to drain connections. -
Probes: readiness / liveness / startup: readiness probe controls Service endpoints (prevents traffic); liveness probe restarts unhealthy containers; startupProbe avoids premature liveness checks during long init. Misconfiguring these causes traffic drops or crash loops.
-
Resources, requests, limits, and QoS: CPU is specified in millicores (100m = 0.1 CPU). Requests drive scheduler placement; limits enforce cgroups. QoS classes: Guaranteed (requests==limits), Burstable, BestEffort. OOM kills happen when memory usage > limit.
-
Deployments, StatefulSets, DaemonSets: Use Deployment for stateless replicas and rolling updates; StatefulSet for stable network IDs/ordered startup and persistent storage; DaemonSet for one pod per node (logging/monitoring).
-
RollingUpdate and canary controls:
RollingUpdateusesmaxSurgeandmaxUnavailable(e.g.,maxSurge:1, maxUnavailable:0for zero-downtime). Canary patterns can be implemented with split Deployments, Ingress weight, or tools like Flagger (progressive delivery). -
Service types and ingress: Service
ClusterIPfor internal DNS,LoadBalancer(creates an AWS ELB/NLB/ALB via controller) for external traffic,NodePortrarely for production.Ingressrequires a controller (`AWS Load Balancer Controller`forALBintegration). -
Persistent storage: Use PersistentVolume / PersistentVolumeClaim for durability; prefer StatefulSet for single-writer volumes. For shared storage, use appropriate RWX-backed solutions; ephemeral data belongs on
emptyDir. -
Config & secrets: Use ConfigMap for non-sensitive config, Secret for credentials (note:
Secretis base64-encoded, not encrypted by default—use KMS/`sealer`or a secrets operator). Mount vs env var tradeoffs: files allow rotation without restart. -
ServiceAccount & IAM: Grant pod AWS permissions with ServiceAccount and IRSA on
`EKS`rather than node IAM roles—least-privilege and auditable. -
Autoscaling basics: HPA uses metrics (CPU, custom via
`metrics-server`/ Prometheus). Desired replicas ≈ ceil((currentMetric / targetMetric) * currentReplicas). Balance HPA with pod startup time and target latency. -
Observability & logging: Emit stdout/stderr (ingested by node agent). Use metrics (
`Prometheus`), structured logs, and tracing (`OpenTelemetry`/`Jaeger`). For`EKS`, forward logs/metrics to`CloudWatch`or a centralized stack via Fluentd/collector. -
Image best-practices: Use immutable tags, minimal base images, scan registries (
`ECR`) for vulnerabilities, and setimagePullPolicyappropriately. Avoidlatestfor production. -
Networking and policies: Service DNS (
<name>.<namespace>.svc.cluster.local) enables discovery. Use NetworkPolicy for pod-level ingress/egress restrictions; expect transient DNS caching and aggressive connection reuse from long-lived clients.
Worked example — "Design a zero-downtime deployment on EKS"
First 30s: clarify assumptions—is the service stateless? Any long-lived TCP connections? Expected RPS and acceptable latency bump? Are DB schema changes involved? Skeleton of the response: (1) Use a Deployment with RollingUpdate and maxSurge:1, maxUnavailable:0 to ensure capacity. (2) Implement robust readiness probes that only return success after warmup, and catch SIGTERM to stop accepting new requests and drain in-flight work. (3) Ensure graceful deregistration from the AWS load balancer (use `AWS Load Balancer Controller` so Kubernetes lifecycle triggers target group deregistration with connection draining). (4) Autoscaling via HPA and pre-warmed capacity to absorb surge. Explicit tradeoff: setting maxUnavailable:0 increases resource usage during deploys (extra pod) but reduces user-visible errors. Close: instrument `p99` latency and error rate, and add an automated canary rollout (or Flagger) for faster rollback if metrics regress—if more time, propose DB migration strategies (expand-contract) and automated health-based rollback.
A second angle — "Investigate intermittent 5xxs and pod restarts"
Frame the problem: get concrete symptoms—are restarts due to crashes (`kubectl get pods` shows restart count) or external 5xxs? Action pillars: (1) check pod events (`kubectl describe pod`) for OOMKilled or probe failures; (2) fetch container logs (`kubectl logs --previous`) and application traces to find exceptions or GC pauses; (3) examine resource metrics (CPU/memory) and node conditions (DiskPressure) via `metrics-server` or Prometheus; (4) verify probes—false liveness kills cause frequent restarts and downstream 5xxs. Tradeoff to call out: increasing memory limits hides leaks but raises cost—better to profile and fix leaking allocations. Finish by proposing mitigations: tune probes, set terminationGracePeriodSeconds, add circuit-breaking and retries at client/ingress, and plan a gradual rollout once root cause fixed.
Common pitfalls
Pitfall: Confusing readiness and liveness probes.
Many candidates treat them interchangeably; the immediate failure mode is removing a pod from rotation vs killing it. Always explain how each affects traffic and restarts.
Pitfall: Proposing cluster-admin fixes for app-level problems.
Suggesting node autoscaling or changing CNI configs is tempting but overkill for application bugs; show you first exhausted app-level fixes (resource tuning, probes, graceful shutdown).
Pitfall: Ignoring shutdown semantics.
A common shallow answer is “handle SIGTERM later.” Better: say how long your terminationGracePeriodSeconds is, what your preStop does, and how the load balancer deregisters the pod to avoid dropped requests.
Connections
Interviewers may pivot to adjacent topics like CI/CD (image promotion, immutable artifacts, deployment pipelines), service meshes and traffic shaping (`Istio`, `AWS App Mesh`), or deeper infra concerns (cluster autoscaling, node groups) — be ready to scope answers to application-level responsibilities.
Further reading
-
Kubernetes Documentation — Concepts — canonical reference for probes, controllers, Services, and storage.
-
AWS EKS Best Practices Guide (containers) — pragmatic EKS patterns for security, networking, and deployment.
Practice questions
Focus area — You asked for real enterprise scenarios involving monitoring, logs, metrics, incident response, operational ownership, and trade-offs.
What's being tested
Interviewers are checking whether you can triage production incidents quickly and correctly using observability signals, and whether you can implement code-level fixes that prevent recurrence. They want to see practical debugging skills: forming hypotheses from metrics/traces/logs, isolating root cause in a distributed flow, making safe short-term mitigations (rollback / feature flag) and proposing durable fixes. Amazon cares because customer-facing correctness, latency, and availability depend on engineers who can fix faults safely under pressure and improve system observability.
Core knowledge
-
Observability fundamentals: the three pillars — structured logs, metrics, and distributed tracing — and how they complement each other when investigating failures. Know when to pivot from one to another.
-
Metric types: counter for event counts, gauge for current values, histogram for latency distributions; compute percentiles from histograms (use
`p50`,`p95`,`p99`), watch sampling bias at low traffic. -
SLO / Error budget: SLO = acceptable success rate (e.g., 99.9%); ; alerts should map to consuming the error budget, not raw noise.
-
Distributed tracing: spans, parent-child relationships, and trace_id propagation; use traces to attribute latency to specific services/DB calls. Know head-based vs tail-based sampling tradeoffs.
-
Correlation ids: instrument requests with a correlation id /
`request_id`and include it in logs, traces, and metrics to cross-link signals for a single request. -
High-cardinality vs aggregation: high-cardinality tags (user_id, order_id) cause storage and query costs; prefer coarse dimensions (region, endpoint) for alerting and dig deeper with trace/log lookup.
-
Logging practices: use structured JSON logs, include context fields (
`user_id`,`trace_id`), avoid logging PII, use appropriate log levels, and rotate/retain logs with cost limits. -
Latency debugging pattern: check service
`p50`/`p95`/`p99`across endpoints, inspect traces for long spans, then drill down (DB queries, external APIs, GC, thread contention). -
Instrumentation tools: be comfortable with
`Prometheus`metrics,`Grafana`dashboards,`Jaeger`/`Zipkin`tracing, and profilers like`pprof`or flamegraphs for CPU/alloc hotspots. -
Quick mitigations: feature flags, canary rollbacks, temporary rate-limiting, or circuit breakers; these are engineer-level actions to reduce customer impact before a full fix.
-
Retries and idempotency: design endpoints to be safe under retries (idempotent or use idempotency keys) and use exponential backoff with jitter to avoid thundering herds.
-
Root-cause vs band-aid: short-term mitigations must be followed by permanent fixes plus improved observability (new metrics/alerts, dashboards) to detect recurrence.
Worked example — "Diagnose a production latency spike in a user-facing service"
First 30 seconds: ask which endpoints are affected, the SLA (`SLO`) and timeframe, whether a deploy occurred, and whether load changed. Sketch the approach: (1) confirm signal (metrics) and scope (which endpoints/users/regions), (2) isolate layer (service, DB, external call, infra), (3) triage with traces/logs, (4) mitigate, then fix. Start by checking `p50`/`p95`/`p99` on the dashboard to see percentile divergence; if `p99` blew up but `p50` unchanged, focus on tail events (long GC pauses, retries, lock contention). Pull a few failing traces (via `trace_id`) and correlate with logs to see slow DB queries or external API latency. A key tradeoff: temporarily raising trace sampling gives more data but increases overhead; prefer targeted increased sampling for the affected endpoints. Mitigation might be to roll back the recent deploy or enable a feature flag for the change causing the spike. Close by proposing durable fixes (optimize hot DB query, add histogram metrics for the problematic call, add an alert on `p99` latency) and say: "If I had more time, I'd add unit/integration tests that reproduce the latency pattern and run a canary to validate the fix."
A second angle — "Intermittent 500s from a backend service"
Same investigation pattern but with different signals: error rate elevation instead of latency. Ask about traffic patterns, retry behavior, and whether the errors are client-side (`4xx`) or server-side (`5xx`). Start with error-rate metrics and error-aggregation logs to find common exception types, then use traces to find the failing span. Consider upstream downstream dependencies (authentication, third-party APIs) and whether a database migration or schema change coincided with the onset. Short-term mitigations include returning a graceful fallback, enabling a circuit breaker for the failing downstream, or rolling back the change. Important design decision here is whether to treat errors as transient (retries) or stateful (require rollback and data fixes). Also plan post-incident: add an alert that tracks both error rate and user-impacted fraction, and add structured error codes to make future triage faster.
Common pitfalls
Pitfall: Jumping to the most visible signal.
A single metric spike is only a symptom; avoid declaring the`DB`or network as root cause before correlating traces and logs. Instead, state hypotheses and test them quickly with focused trace samples.
Pitfall: Over-instrumenting during an incident.
Adding verbose logging everywhere increases load and can worsen the outage; prefer targeted increased sampling or temporary feature-flagged debug endpoints.
Pitfall: Fixing symptoms without observability improvements.
Applying a rollback or hotfix and closing the incident without adding metrics/alerts that would detect recurrence is a depth mistake; include a remediation checklist (code fix, tests, dashboards, alert thresholds).
Connections
Expect pivots to adjacent topics like release engineering (canary strategies, rollout policies) and SRE runbooks (on-call procedures, paging). Be ready to discuss tradeoffs between observability cost and fidelity (storage/retention vs sampling).
Further reading
-
Site Reliability Engineering (Google SRE book) — practical SLO, incident, and postmortem guidance.
-
Observability Engineering (Honeycomb & Charity Majors blog posts) — hands-on articles about tracing, high-cardinality dimensions, and debugging production systems.
Practice questions
Software Engineering Fundamentals
Focus area — You selected OOD, concurrency, resource pooling, and thread safety; focus on production-grade class boundaries and synchronization.
What's being tested
Interviewers are probing whether you can turn an ambiguous product workflow into a clean object-oriented design, then make it safe under concurrent access. For a Software Engineer, this means more than naming classes: you must define responsibilities, state transitions, invariants, APIs, persistence boundaries, and failure behavior. Amazon cares because many production systems look “simple” at the feature level—tasks, carts, orders, reservations—but fail when multiple users, services, retries, or devices act on the same entity at once. A strong answer shows practical judgment: simple in-memory design when appropriate, database-backed consistency when needed, and extensibility without over-engineering.
Core knowledge
-
Domain modeling starts with nouns, verbs, and invariants. For a task system:
Task,User,Project,Comment,Assignee; for a restaurant:Table,Reservation,Order,MenuItem,Bill. The important part is not the nouns themselves, but who owns state and which transitions are legal. -
Single Responsibility Principle means each class should have one reason to change.
Ordercan own order-line state, but pricing rules often belong inPricingServiceorPriceCalculator; payment authorization belongs behind aPaymentProcessorinterface, not insideOrder. -
State machines are essential for workflows. Model states explicitly:
CREATED -> CONFIRMED -> PREPARING -> READY -> COMPLETED, orOPEN -> ASSIGNED -> IN_PROGRESS -> DONE. Define invalid transitions and enforce them centrally, preferably through methods likeorder.markReady()rather than arbitrary field mutation. -
Invariants are the rules that must always hold, even under concurrency. Examples: inventory cannot go below zero, one table cannot have two active reservations for the same time slot, a task cannot be assigned to a deleted user, and an order cannot be paid twice. State these aloud before choosing locks or transactions.
-
API design should expose use cases, not database tables. Prefer operations like
POST /orders/{id}/items,POST /tasks/{id}/assign, orPOST /reservations/{id}/cancelover genericPATCHfor every field when transitions have business rules. Include idempotency for retryable operations such as checkout. -
Composition over inheritance is usually better for extensibility. A pizza order should compose
Crust,Size,Topping, andPricingRule; avoid a class explosion likeLargeThinCrustPepperoniPizza. Use Strategy pattern for pricing, discounts, tax, or payment providers. -
Optimistic concurrency control works well when conflicts are rare. Add a
versioncolumn and update withWHERE id = ? AND version = ?; if zero rows are updated, reload and retry or return a conflict. This is common for task edits, cart updates, and profile-like entities. -
Pessimistic locking is appropriate when conflicts are likely or consequences are severe. In
Postgres,SELECT ... FOR UPDATEcan lock an inventory row during purchase. Keep transactions short; never hold a database lock while calling an external payment provider. -
Idempotency keys protect against duplicate client retries. For checkout, accept an
Idempotency-Keyheader and store the request key with the resultingOrderor payment attempt. If the same key is retried, return the original result instead of charging twice. -
Consistency boundaries should be explicit. A single aggregate, such as
OrderplusOrderItems, can often be updated transactionally. Cross-aggregate workflows—inventory reservation, payment, fulfillment—may need sagas, status fields, compensating actions, and reconciliation jobs rather than one giant transaction. -
Thread safety matters for in-memory components. Shared mutable structures like
Map<TaskId, Task>require synchronization,ConcurrentHashMap, immutable value objects, or actor-style ownership. Remember thatConcurrentHashMapmakes individual map operations safe, not multi-step invariants like “check then insert if capacity remains.” -
Event ordering matters in input systems and workflow systems. Keyboard/mouse events need monotonic sequence numbers, timestamps, and deterministic replay; order systems need append-only history for debugging. A log like
Event(seq, deviceId, type, payload, timestamp)helps reproduce bugs and reason about causality.
Worked example
For Design an OOD restaurant management system, a strong candidate would first clarify scope: “Are we designing for dine-in only, or also delivery? Do we need reservations, table assignment, ordering, kitchen status, billing, and payment? Is this single restaurant or multi-location?” Then they would declare assumptions: single location, multiple staff using terminals concurrently, and core flows covering reservation, seating, order placement, kitchen fulfillment, bill splitting, and payment.
The answer skeleton should have four pillars: domain model, state transitions, service/API layer, and concurrency controls. The domain model might include Restaurant, Table, Reservation, Party, Order, OrderItem, MenuItem, KitchenTicket, Bill, and Payment. State transitions matter: a Reservation moves from REQUESTED to CONFIRMED to SEATED or CANCELLED; an OrderItem moves from PLACED to IN_PREP to SERVED.
The candidate should explicitly separate responsibilities: TableManager assigns tables, OrderService mutates orders, KitchenService manages tickets, BillingService computes totals, and PaymentService integrates with a payment processor. A concrete tradeoff to flag is reservation concurrency: two hosts might try to assign the same table for overlapping times, so table assignment should happen inside a transaction with a uniqueness constraint or lock on the table/time slot. Another useful tradeoff is bill splitting: you can support equal split first, then item-level split later by modeling BillLineItem ownership.
A strong close would be: “If I had more time, I’d add audit logs for staff actions, offline-terminal sync, menu availability windows, and failure handling around partial payment authorization.”
A second angle
For Design a keyboard and mouse input system, the same design skill applies, but the domain is lower-level and more event-driven. Instead of modeling business aggregates like Order and Reservation, you model InputEvent, KeyboardEvent, PointerEvent, FocusTarget, TextComposition, and EventDispatcher. The key invariant is not “do not oversell inventory,” but “deliver events in deterministic order to the correct focused component while preserving composition and pointer semantics.”
Concurrency shows up differently: hardware events, UI thread dispatch, accessibility hooks, and replay logs may operate on different threads. A strong design would use an event queue with sequence numbers, immutable event objects, and a single-threaded dispatch loop or carefully synchronized handoff. The transferable concept is the same: define ownership of mutable state, legal transitions, ordering guarantees, and the boundary where external inputs become internal state changes.
Common pitfalls
Pitfall: Starting with a class diagram before clarifying workflows.
A tempting weak answer is to list classes like Book, User, Cart, Order, or Task immediately. That misses what interviewers care about: behavior under real operations. Start with 3–5 core flows, then derive classes and methods from those flows.
Pitfall: Treating concurrency as “add a lock” without naming the invariant.
Saying “I’ll synchronize the method” is too vague. A better answer is: “The invariant is that inventory cannot go negative; I’ll enforce it with a transaction and conditional update, UPDATE inventory SET quantity = quantity - 1 WHERE sku = ? AND quantity > 0, then check affected rows.”
Pitfall: Overusing inheritance and patterns.
Designs like VegPizza extends Pizza, CheesePizza extends VegPizza, and LargeCheesePizza extends CheesePizza become brittle fast. Prefer small interfaces, composition, and strategies: Pizza has Size, Crust, List<Topping>, and pricing rules that can evolve independently.
Connections
Interviewers often pivot from this topic into system design, especially when an object model becomes a service with persistence, caching, and APIs. They may also pivot into database transactions, distributed consistency, idempotent API design, or design patterns such as Factory, Strategy, Observer, Repository, and State.
Further reading
-
Design Patterns: Elements of Reusable Object-Oriented Software — the classic source for Strategy, Observer, Factory, and State patterns.
-
Martin Fowler, Patterns of Enterprise Application Architecture — practical patterns for service layers, repositories, transactions, and domain models.
-
Stripe API Idempotent Requests — clear real-world explanation of retry-safe API design for payment-like workflows.
Practice questions
Take-home Project — 23 min
Coding & Algorithms
Focus area — Coding is 2/5 and you asked for string parsing, scripting-adjacent problems, key-value thinking, and practical debugging fluency.

What's being tested
Array/string counting questions test whether you can turn brute-force comparisons into linear or near-linear passes using prefix/suffix state, two pointers, hash maps, and frequency vectors. Interviewers are probing correctness under duplicates, zeros, negative values, collisions, and boundary cases—not just happy-path O(n) code.
Patterns & templates
-
Prefix/suffix accumulation — compute left-to-right and right-to-left products/counts in
O(n)time; avoid division and handle zeros explicitly. -
Two-pointer scan on sorted arrays — move
l/rbased on sum comparison; skip duplicate values when returning unique pairs. -
Frequency map counting — use
dict,HashMap, orCounterfor character/item counts; compare vectors inO(k)wherekis alphabet size. -
Fixed alphabet arrays — prefer
int[26]orint[128]for lowercase/ASCII strings; faster and simpler than hash maps when domain is bounded. -
Partition state tracking — maintain left/right distinct-character counts as a split moves; update counts carefully when a frequency reaches zero.
-
Modulo reasoning — maximize distinct remainders by tracking used residues in a set; remember residues range from
0tok - 1. -
Hash map internals — know hashing, buckets, collisions, load factor, resizing, and worst-case
O(n)lookup; mention concurrency concerns when relevant.
Common pitfalls
Pitfall: Using division in product-except-self fails when zeros appear and may violate the stated constraint.
Pitfall: Returning duplicate pairs from a sorted array because you advance pointers but do not skip repeated values.
Pitfall: Treating hash map operations as always
O(1)without acknowledging collisions, resizing cost, and adversarial keys.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
Software Engineering Fundamentals
Focus area — You explicitly prefer scripting, Linux debugging, automation, and production tasks over advanced DSA.
What's being tested
Candidates must show practical mastery of Python and Bash scripting for operational tasks: parsing logs, automating workflows, and gluing system tools. Interviewers probe correctness, robustness (error handling, idempotency), and readable maintainable scripts you would check into a repo.
Patterns & templates
-
Shebang-led executable scripts — use
#!/usr/bin/env python3or#!/bin/bashand include usage/help flags for operability. -
Robust subprocess handling — prefer
subprocess.run(..., check=True)in Python; useset -eand||checks in bash for failures. -
Stream-processing with UNIX tools — combine
grep,awk,sed,cutand pipes for line-oriented transforms; avoid large in-memory buffers. -
Idempotent file ops — write to a temp file then
mvto target, use atomic renames to avoid partial-state races. -
Logging & exit codes — write structured logs, send errors to
stderr, return meaningful nonzero exit codes for orchestration. -
Scheduling & services — prefer
systemdtimers orcronfor simple periodic runs; ensure environment/PATHis explicit and use virtualenvs. -
Process control & signals — handle
SIGINT/SIGTERMin Python (signal), trap in bash to clean up temp files and child processes.
Common pitfalls
Pitfall: Assuming the runtime environment — scripts that rely on implicit
PATHentries or unstatedPYTHONPATHbreak in CI or cron.
Pitfall: Silent failures — swallowing exceptions or ignoring
stderrmakes debugging production incidents much harder than printing one clear error and exiting nonzero.
Pitfall: Memory-scaling mistakes — reading whole large log files into memory instead of streaming (
for line in file:) causes OOM on real-world datasets.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
Focus area — Terraform is a stated focus and your profile includes state, modules, remote locking, environments, and enterprise IaC concerns.
What's being tested
Interviewers probe a candidate’s ability to design, reason about, and operate Infrastructure as Code at application scale: how you structure Terraform code, manage its state, compose reusable modules, and detect/resolve configuration drift safely. They want to see clear tradeoffs (simplicity vs. reuse, remote state vs. local), an understanding of idempotence and resource lifecycle, and concrete patterns you would implement in code or CI to avoid outages. Expect to justify decisions under constraints like multiple environments, team ownership, and automated pipelines.
Core knowledge
-
Terraform lifecycle:
terraform init,terraform plan,terraform apply,terraform destroy— plan shows a diff, apply reconciles to reach the desired state; never skipplanin automation. -
State file semantics: the state is the source of truth for resource IDs, attributes, and dependencies; treat it as authoritative and versioned — losing or corrupting it breaks reconciliation.
-
Remote state backends: using
S3/GCS/Azure BlobplusDynamoDB/GCSlocking prevents concurrent writes; remote backends scale to large teams and enable CI usage. -
State locking & consistency: locking prevents concurrent
applys; explain how you would implement locks in CI to avoid race conditions and partial applies. -
Modules design: prefer small, opinionated modules with clear inputs/outputs and semantic versioning (use
vX.Y.Ztags); reuse via registries or shared repos, avoid over‑generalization. -
Workspaces vs. separate state:
terraform workspaceis fine for small testing; for production, prefer separate state files per environment to reduce blast radius and accidental cross-env changes. -
Drift detection: run
terraform planagainst remote state in CI regularly or on PRs; integrate drift checks and alerting; automated remediation requires human-approved plans for nontrivial changes. -
Importing existing resources: use
terraform importto adopt resources safely; afterwards update configuration to match imported attributes to avoid immediate diffs. -
Resource lifecycle meta-arguments:
lifecycle { create_before_destroy = true },prevent_destroy, andignore_changesare powerful but can mask problems; use sparingly and document rationale. -
Idempotence and immutability: favor immutable patterns (replace resources) for safe upgrades, but account for resources that must be in-place (databases, stateful disks) and plan for migration steps.
-
Secrets & state security: never store secrets in plaintext in state; use encryption at rest (backend provider), restrict IAM roles, and consider partial state scrubbing or external secret sources.
-
Testing and validation: use
terraform validate,terraform fmt, static linters (tflint), and unit/integration tests (e.g., Terratest) in CI to catch module regressions before apply.
Tip: tag resources with ownership and environment metadata to make drift triage and auditing straightforward.
Worked example — "Design Terraform modules and state layout for multi-environment microservices"
First 30s framing: clarify number of environments (dev/stage/prod), deployment cadence per team, whether environments share cloud accounts, and constraints on resource isolation or cross-account access. Skeleton answer pillars: (1) module topology — a small base module per service (networking, compute, IAM) plus environment overlays; (2) state layout — separate remote state per environment and per service to minimize blast radius; (3) CI integration — plan on PRs, apply on merge with approval gates for prod. Call out a tradeoff: many small state files improve safety but add operational complexity for cross-resource references (use remote_state data sources or outputs with careful access controls). Close by noting incremental improvements: "if more time, I'd add automated drift scans, finer-grained module tests with Terratest, and documented migration playbooks for state moves."
A second angle — "Detect and remediate Terraform drift in CI/CD pipeline"
Here the constraints change: the focus is on automation and safety under continuous delivery. You’d propose a pipeline where every PR runs terraform plan against the current remote state and fails if drift is detected unexpectedly. For remediation, prefer an explicit human-reviewed apply for nontrivial changes; for trivial config fixes (tagging, metadata), a safe auto-apply policy can exist with strict IAM/approval controls. Discuss performance: live plan for large state can be slow — mitigate with targeted plans using -target sparingly and scheduled full-plan jobs off-peak. Mention one design decision: choose to alert and block merges when drift originates outside CI (manual console changes), forcing teams to import or reconcile rather than silently overwrite.
Common pitfalls
Pitfall: Treating the state as a backup rather than the authoritative source.
Many engineers export resources manually and then overwrite state with new configs, causing resource duplication or orphaned resources; always import resources into state and reconcile config to imported attributes first.
Pitfall: Overusing
ignore_changesorprevent_destroy.
These meta-arguments can hide real problems and become technical debt; interviewers will prefer small, explicit exceptions with clear justification and tickets than broad, permanent ignores.
Pitfall: Relying on
terraform workspacefor environment isolation at scale.
Workspaces can leak configuration and make accidental cross-env updates easier; for multi-team production systems, separate state files/accounts per environment are safer despite added indirection.
Connections
Interviewers may pivot to adjacent topics like CI/CD pipeline design (how terraform runs in Jenkins/GitHub Actions), configuration drift detection across other IaC tools (e.g., kubectl vs. terraform), or testing strategy (unit tests with terratest and policy-as-code checks). Be ready to map your Terraform choices to app deployment, monitoring, and incident recovery workflows.
Further reading
-
Terraform documentation — State — authoritative reference on backends, locking, and state commands.
-
[Terraform: Up & Running (book) — Yevgeniy Brikman] — practical patterns for modules, testing, and production usage.
-
Gruntwork Terratest — examples for automated integration testing of Terraform modules.
Practice questions