Backend-engineering interview questions
Status: Complete for the backend-engineering core (Wave 3). Last reviewed 2026-08-28.
This canonical bank grows with the backend-engineering bundles. Example answers model credible spoken responses, not grading rubrics or uniquely correct scripts.
Data structures, complexity, and bottlenecks
Section titled “Data structures, complexity, and bottlenecks”BACKEND-FUNDAMENTALS-01 — Explain why Big O is not a stopwatch
Section titled “BACKEND-FUNDAMENTALS-01 — Explain why Big O is not a stopwatch”Why can an O(n) solution be slower than an O(n²) solution for realistic inputs, and what does complexity analysis still tell you?
BACKEND-FUNDAMENTALS-02 — Replace repeated scans without changing semantics
Section titled “BACKEND-FUNDAMENTALS-02 — Replace repeated scans without changing semantics”A service scans a product list for every incoming line item. Redesign it, state the time and space costs, and identify correctness assumptions introduced by the change.
BACKEND-FUNDAMENTALS-03 — Choose a structure from the workload
Section titled “BACKEND-FUNDAMENTALS-03 — Choose a structure from the workload”Choose among a sequence, set, map, sorted structure, queue, and priority queue for several backend workloads. Which operation and guarantee drive each choice?
BACKEND-FUNDAMENTALS-04 — Diagnose an apparently linear endpoint
Section titled “BACKEND-FUNDAMENTALS-04 — Diagnose an apparently linear endpoint”An endpoint has one loop over 100 records and no nested loop, yet its p95 is several seconds. How would you reason about its complexity and diagnose it?
BACKEND-FUNDAMENTALS-05 — Reason about time, space, and boundaries
Section titled “BACKEND-FUNDAMENTALS-05 — Reason about time, space, and boundaries”When should repeated lookup be indexed in PHP, delegated to the database, or left as a linear scan?
BACKEND-FUNDAMENTALS-06 — Prove the real bottleneck
Section titled “BACKEND-FUNDAMENTALS-06 — Prove the real bottleneck”A proposed optimization replaces a clear O(n²) routine with an O(n) implementation. What evidence would you require before shipping it, and how would you verify the result?
Concurrency, processes, and asynchronous I/O
Section titled “Concurrency, processes, and asynchronous I/O”BACKEND-CONCURRENCY-01 — Find concurrency in a single-threaded service
Section titled “BACKEND-CONCURRENCY-01 — Find concurrency in a single-threaded service”Why can a single-threaded PHP request participate in race conditions, and where must concurrency control live?
BACKEND-CONCURRENCY-02 — Contrast processes, threads, event loops, and fibers
Section titled “BACKEND-CONCURRENCY-02 — Contrast processes, threads, event loops, and fibers”Contrast these execution models, including isolation, scheduling, I/O, and CPU-bound work.
BACKEND-CONCURRENCY-03 — Diagnose a read-modify-write race
Section titled “BACKEND-CONCURRENCY-03 — Diagnose a read-modify-write race”Two requests read a balance, validate a withdrawal, and write the result. Explain the failure and choose a safe mechanism.
BACKEND-CONCURRENCY-04 — Bound an asynchronous fan-out
Section titled “BACKEND-CONCURRENCY-04 — Bound an asynchronous fan-out”An endpoint must call a downstream API for thousands of items. How would you overlap waits without causing overload?
BACKEND-CONCURRENCY-05 — Propagate cancellation and deadlines
Section titled “BACKEND-CONCURRENCY-05 — Propagate cancellation and deadlines”A client disconnects while a request has database and HTTP operations in flight. What should cancellation mean across those boundaries?
BACKEND-CONCURRENCY-06 — Design graceful worker shutdown
Section titled “BACKEND-CONCURRENCY-06 — Design graceful worker shutdown”Design shutdown for a long-running queue worker receiving a termination signal during an external side effect.
HTTP, networking, and web boundaries
Section titled “HTTP, networking, and web boundaries”BACKEND-HTTP-01 — Trace an HTTPS request
Section titled “BACKEND-HTTP-01 — Trace an HTTPS request”Trace an HTTPS request from a URL through DNS, connection establishment, TLS, proxies, the application, and response delivery.
BACKEND-HTTP-02 — Diagnose a DNS migration
Section titled “BACKEND-HTTP-02 — Diagnose a DNS migration”A DNS record was changed, but some clients still reach the old deployment. Explain plausible causes and a safe migration.
BACKEND-HTTP-03 — Design a safe HTTP cache policy
Section titled “BACKEND-HTTP-03 — Design a safe HTTP cache policy”Design browser and CDN caching for a localized endpoint with authenticated and public variants.
BACKEND-HTTP-04 — Separate CORS, CSRF, and authentication
Section titled “BACKEND-HTTP-04 — Separate CORS, CSRF, and authentication”Why can a correct CORS policy coexist with a CSRF vulnerability, and what does each control protect?
BACKEND-HTTP-05 — Model recurring local time
Section titled “BACKEND-HTTP-05 — Model recurring local time”How would you store a one-off instant versus “run at 09:00 Europe/Madrid every weekday”?
BACKEND-HTTP-06 — Diagnose a representation boundary
Section titled “BACKEND-HTTP-06 — Diagnose a representation boundary”An API corrupts emoji, loses precision in identifiers, and occasionally shifts calendar dates. How would you separate and fix the failures?
API semantics and compatibility
Section titled “API semantics and compatibility”BACKEND-API-01 — Design an evolvable error contract
Section titled “BACKEND-API-01 — Design an evolvable error contract”Design an error format that supports several independently deployed clients without leaking internals.
BACKEND-API-02 — Choose safe pagination
Section titled “BACKEND-API-02 — Choose safe pagination”Compare offset and cursor/keyset pagination for a frequently updated tenant-scoped feed.
BACKEND-API-03 — Make a command idempotent
Section titled “BACKEND-API-03 — Make a command idempotent”Design idempotency for a payment-like POST that can time out after the provider succeeds.
BACKEND-API-04 — Evolve a live API contract
Section titled “BACKEND-API-04 — Evolve a live API contract”Classify apparently additive changes that can still break clients and describe a safe removal process.
BACKEND-API-05 — Process signed webhooks
Section titled “BACKEND-API-05 — Process signed webhooks”Design webhook receipt, authentication, replay protection, processing, and recovery.
BACKEND-API-06 — Prevent lost updates
Section titled “BACKEND-API-06 — Prevent lost updates”Two clients edit the same resource from stale representations. Design an HTTP-aware optimistic concurrency contract.
Testing and software quality
Section titled “Testing and software quality”BACKEND-TESTING-01 — Choose a credible test boundary
Section titled “BACKEND-TESTING-01 — Choose a credible test boundary”Choose test boundaries for a pricing rule, a database constraint, an HTTP policy, and a critical checkout journey.
BACKEND-TESTING-02 — Use doubles without fictional confidence
Section titled “BACKEND-TESTING-02 — Use doubles without fictional confidence”When should a payment dependency be stubbed, faked, mocked, contract-tested, or exercised for real?
BACKEND-TESTING-03 — Test a retrying distributed job
Section titled “BACKEND-TESTING-03 — Test a retrying distributed job”How would you test a job that can fail after an external side effect and then be redelivered?
BACKEND-TESTING-04 — Diagnose suite-only flakiness
Section titled “BACKEND-TESTING-04 — Diagnose suite-only flakiness”A test passes alone but fails intermittently in the parallel suite. Give a diagnosis sequence.
BACKEND-TESTING-05 — Combine analysis, coverage, and mutation
Section titled “BACKEND-TESTING-05 — Combine analysis, coverage, and mutation”What distinct evidence do static analysis, coverage, and mutation testing provide, and what do they miss?
BACKEND-TESTING-06 — Design a useful CI gate
Section titled “BACKEND-TESTING-06 — Design a useful CI gate”Design CI that is strict enough to protect delivery but fast and reliable enough to remain usable.
Application and operational security
Section titled “Application and operational security”BACKEND-SECURITY-01 — Threat-model a tenant export
Section titled “BACKEND-SECURITY-01 — Threat-model a tenant export”Threat-model an authenticated bulk export in a multi-tenant application, including background execution and download.
BACKEND-SECURITY-02 — Separate injection controls
Section titled “BACKEND-SECURITY-02 — Separate injection controls”Explain why validation, parameterization, contextual encoding, and authorization are distinct controls.
BACKEND-SECURITY-03 — Defend an outbound fetcher from SSRF
Section titled “BACKEND-SECURITY-03 — Defend an outbound fetcher from SSRF”Design a service that fetches user-supplied URLs without exposing internal networks or cloud credentials.
BACKEND-SECURITY-04 — Design secure uploads
Section titled “BACKEND-SECURITY-04 — Design secure uploads”Design upload, processing, storage, and download for user documents.
BACKEND-SECURITY-05 — Respond to an application-key leak
Section titled “BACKEND-SECURITY-05 — Respond to an application-key leak”An application encryption/signing key appeared in a public build log. What do you do and what may be affected?
BACKEND-SECURITY-06 — Secure authentication and recovery
Section titled “BACKEND-SECURITY-06 — Secure authentication and recovery”Design password authentication, sessions, reset, MFA, and account recovery without making recovery the weakest path.
Performance, capacity, and scalability
Section titled “Performance, capacity, and scalability”BACKEND-PERFORMANCE-01 — Diagnose rising p99
Section titled “BACKEND-PERFORMANCE-01 — Diagnose rising p99”An endpoint’s p99 rises sharply while p50 and average CPU remain stable. Give an evidence-led diagnosis.
BACKEND-PERFORMANCE-02 — Find a service’s saturation point
Section titled “BACKEND-PERFORMANCE-02 — Find a service’s saturation point”How would you determine useful concurrency and the overload knee for a service backed by a database and provider API?
BACKEND-PERFORMANCE-03 — Size PHP workers
Section titled “BACKEND-PERFORMANCE-03 — Size PHP workers”Choose FPM or queue-worker concurrency without simply increasing workers until latency improves.
BACKEND-PERFORMANCE-04 — Choose an optimization
Section titled “BACKEND-PERFORMANCE-04 — Choose an optimization”Choose among query optimization, caching, batching, asynchronous work, replicas, and denormalization for a slow read path.
BACKEND-PERFORMANCE-05 — Design a credible load test
Section titled “BACKEND-PERFORMANCE-05 — Design a credible load test”Design a load test that can predict production behavior rather than produce an attractive requests-per-second number.
BACKEND-PERFORMANCE-06 — Decide how to scale
Section titled “BACKEND-PERFORMANCE-06 — Decide how to scale”When should a service scale vertically, horizontally, with replicas, or through partitioning?
Example answers
Section titled “Example answers”BACKEND-FUNDAMENTALS-01 — Example answer
Solid response: Complexity describes how work grows with a named input; it omits constants and usually does not describe I/O, allocation, or elapsed time. An O(n) loop making sequential network calls can be much slower than an O(n²) comparison over a small bounded in-memory set. A map-based O(n) solution also has construction and memory costs that may not pay back for one small lookup.
It still tells me which design is likely to become unsafe as cardinality grows and helps expose repeated work. I state the input, expected or worst case, and space cost rather than quoting a class alone.
Senior extension: I turn the analysis into a hypothesis: at what input size and workload mix should the alternative win, and which resource becomes limiting? Then I measure representative latency distributions, CPU, allocation, query/remote-call counts, and saturation. Big O guides risk and experiment design; production evidence decides priority.
BACKEND-FUNDAMENTALS-02 — Example answer
Solid response: The nested scans cost O(nm) comparisons for n line items and m products. I can build a product-by-SKU map in O(m) expected time and O(m) extra space, then perform n expected O(1) lookups, giving O(n + m) expected time.
Before changing it, I define duplicate behavior. A simple assignment silently keeps the last product for a duplicate SKU, so I may need to reject duplicates. I also normalize key representation deliberately and preserve missing-product and original-order behavior.
Senior extension: If the catalogue is large or already in a database, materializing all products in PHP may waste memory. I would compare a set-based indexed query, chunked lookup, or database join. I would measure query count, rows transferred, peak memory, CPU, and latency using realistic cardinalities. The best local algorithm can still be the wrong system boundary.
BACKEND-FUNDAMENTALS-03 — Example answer
Solid response: I use a sequence for ordered iteration and duplicates, a set for uniqueness or membership, and a map for repeated lookup by a unique key. I use a sorted structure when range queries or ordered traversal are required. A FIFO queue models arrival order; a priority queue models selecting the most urgent item, not fairness by itself.
The decision starts with operations and guarantees: lookup frequency, insertion/removal pattern, ordering, duplicate policy, and bounds. I also include memory and construction cost.
Senior extension: I separate logical contract from implementation. A PHP array can imitate several structures but does not automatically enforce their invariants, and a database index may own durable lookup better than process memory. For a production queue I also need persistence, delivery, concurrency, and backpressure guarantees; an in-memory FIFO name answers only removal order.
BACKEND-FUNDAMENTALS-04 — Example answer
Solid response: One source-level loop is not necessarily cheap. Each iteration might lazy-load an ORM relation, execute a query, serialize a large graph, or call a downstream service. That is O(n) in iteration count but also n round trips, and latency may be sequential. I would trace a slow request, count and time database and remote calls, inspect query plans and rows examined, and profile CPU or allocation only if those spans are material.
I would compare p50, p95, and p99 and segment by record count and cache outcome.
Senior extension: I include queue wait, connection-pool saturation, database locks, retries, and response transfer so waiting is not mislabelled as PHP computation. Then I form a focused change—eager loading, batching, a set-based query, parallel bounded I/O, or less serialization—and verify the same workload before and after without changing correctness.
BACKEND-FUNDAMENTALS-05 — Example answer
Solid response: I leave a linear scan when the collection is small, there is one lookup, or the predicate cannot be keyed. I build a PHP map when the data is already local, lookups repeat, key semantics are clear, and O(n) extra memory fits the process budget. I delegate to the database when filtering or joining near indexed durable data avoids transferring and retaining a large collection.
The database option needs an appropriate query and verified plan; “let the database do it” is not automatically efficient.
Senior extension: I include lifecycle and consistency. A per-request map is rebuilt; a worker-level cache can become stale or unbounded; a database index increases write and storage cost. I compare rows examined and returned, round trips, peak memory, update frequency, and required freshness, then record the cardinality or latency threshold that would make us revisit the choice.
BACKEND-FUNDAMENTALS-06 — Example answer
Solid response: First I require a measured symptom and budget, not only unattractive notation. I confirm the routine is a meaningful share of representative request or job time and capture input sizes, latency distribution, CPU, peak memory, and relevant I/O counts. I check that the rewrite preserves duplicate, order, missing-value, and error behavior.
Then I benchmark or load-test both versions with realistic distributions, including large and adversarial cases, and compare end-to-end production-like behavior.
Senior extension: I watch for cost migration: the O(n) version may allocate a large map, increase garbage collection, or duplicate data already indexed elsewhere. I canary the change and observe the user-facing objective plus saturation and failure signals. If the old routine is below measurement noise or input is tightly bounded, I keep the clearer code and document the assumption rather than spend complexity budget without a result.
BACKEND-CONCURRENCY-01 — Example answer
Solid response: Single-threaded describes one execution context, not the whole system. Other FPM workers, queue consumers, schedulers, hosts, retries, and external actors overlap through the same database, cache, files, broker, or API. A read-check-write sequence can therefore race even though each request executes statements sequentially.
Concurrency control must live at the shared-state boundary: for example a conditional SQL update, unique constraint, row lock, or optimistic version check. An in-process mutex cannot coordinate independent PHP processes.
Senior extension: I first name the invariant and reconstruct possible interleavings. Then I choose the narrowest mechanism with matching failure semantics and test it against the production database. I distinguish durable correctness from duplicate suppression or performance locks; a cache lease is not a substitute for a database constraint when expiry or failover can admit another holder.
BACKEND-CONCURRENCY-02 — Example answer
Solid response: Processes isolate address spaces and communicate explicitly. Threads share process memory and need synchronization. An event loop multiplexes readiness and timers on an execution thread, which is efficient for many I/O waits but vulnerable to blocking callbacks. Fibers preserve a suspendable PHP stack; they are cooperatively resumed and do not schedule themselves or turn blocking I/O into non-blocking I/O.
CPU-bound work still occupies an execution thread unless moved or parallelized.
Senior extension: I choose from workload and failure boundaries. Processes give fault and memory isolation; threads can share data cheaply but increase synchronization risk; event-driven tasks reduce per-wait overhead but need bounded concurrency and loop-lag observability. The library/runtime determines cancellation, fairness, and I/O support, so “uses fibers” is not enough to predict production behavior.
BACKEND-CONCURRENCY-03 — Example answer
Solid response: Both requests can read the same old balance, both approve, and both write the same new balance. One update is lost and the validation did not protect the invariant. Wrapping the unchanged sequence in a transaction may still allow the race depending on isolation and statements.
I would prefer an atomic conditional update such as decrementing only where balance is sufficient and checking affected rows, or lock/version the row within a short transaction.
Senior extension: If withdrawals also create ledger entries or external effects, I commit the ledger and balance atomically, use a unique operation ID, and call external systems through an idempotent/outbox workflow. I test a controlled interleaving against the real database and define retry behavior for conflicts and deadlocks. The balance may be derived from an append-only ledger rather than mutated state when auditability drives the model.
BACKEND-CONCURRENCY-04 — Example answer
Solid response: I would not start thousands of calls at once. I use a bounded worker set or semaphore, per-call timeouts, an overall deadline, and a queue with explicit capacity. The limit reflects downstream quotas, connection pools, memory, and the endpoint’s latency budget. Results are streamed or accumulated with a bound.
Failures are classified; retries use capped exponential delay and jitter, and cancellation stops launching new calls.
Senior extension: I ask whether the API supports batching or whether durable offline work is the correct product contract. I measure in-flight calls, queue age, downstream latency/errors, memory, and throughput while increasing concurrency. Backpressure must reach the producer—moving unlimited work to a broker only relocates overload. Partial-result and ordering semantics are explicit rather than accidental.
BACKEND-CONCURRENCY-05 — Example answer
Solid response: A disconnect means the response is no longer wanted; it does not prove child operations stopped. I propagate a request deadline and cancellation signal, stop launching work, cancel supported HTTP/database operations, and close resources. Each operation has a timeout no longer than the remaining budget.
Cancellation is cooperative, so unsupported or already committed effects may finish. I do not claim rollback across an external call.
Senior extension: I shield only short consistency-critical cleanup, make durable effects idempotent, and record outcomes for reconciliation if the caller cannot observe them. Logs distinguish cancellation, timeout, and internal failure. Detached work that must survive the request becomes a durable job with its own identity and authorization context, rather than silently continuing in a request process.
BACKEND-CONCURRENCY-06 — Example answer
Solid response: The signal handler should set shutdown intent, not perform complex cleanup. The worker stops reserving new jobs and gives the in-flight job a bounded grace period. It acknowledges only after durable local state and required side effects are in a retry-safe state; otherwise the broker may redeliver.
Timeouts and an idempotency key protect the external call, and shutdown metrics show draining and forced exits.
Senior extension: I align orchestrator grace time, worker timeout, visibility timeout, and maximum expected job duration. If the external provider succeeded but acknowledgement or local recording failed, the retry queries by operation key or reconciles rather than repeating blindly. Deploys drain old payload versions intentionally, and hard-kill behavior is tested because graceful shutdown is a bounded protocol, not a guarantee.
BACKEND-HTTP-01 — Example answer
Solid response: The client parses the URL and resolves the hostname through DNS caches and resolvers. It opens a transport connection, performs TLS negotiation and certificate/hostname validation for HTTPS, then sends an HTTP message. A CDN, load balancer, ingress, or reverse proxy may terminate TLS, cache, retry, buffer, or route before the application handles the effective request and returns a response through those hops.
HTTP/2 or HTTP/3 changes connection/stream behavior, not method semantics.
Senior extension: I name the evidence at each boundary: resolver answers and TTL, connect/TLS timings, negotiated protocol, proxy access and cache status, forwarded-header trust, application trace, and client receipt. I compare hop deadlines and retry policies because a proxy can time out and retry while the origin continues, producing duplicate work and misleading 504s.
BACKEND-HTTP-02 — Example answer
Solid response: DNS is cached by authoritative and recursive resolvers, operating systems, applications, and sometimes intermediaries. Negative answers also cache, and an existing keep-alive connection can continue reaching the old address without another lookup. Different record types, regions, and IPv4/IPv6 paths may disagree.
I lower TTL ahead of the change, make both deployments compatible, change records, observe traffic, and keep the old target healthy beyond the expected cache/connection window.
Senior extension: TTL is not a hard global propagation guarantee. I query authoritative and representative recursive resolvers, inspect client-resolved addresses and connection reuse, and verify load-balancer health/routing. Database, queue, cookie, and payload compatibility must support simultaneous old/new traffic. Drain only after telemetry proves the old target is no longer receiving meaningful requests.
BACKEND-HTTP-03 — Example answer
Solid response: I first classify representations. Public localized content can be shared if the cache key includes the actual selecting dimensions, commonly language or an explicit locale path, and Vary reflects request-field selection. Authenticated personalized content is private or no-store unless a reviewed shared-cache design varies safely by identity/tenant, which is usually undesirable.
I define freshness, validators, purge/invalidation, and stale-on-error behavior.
Senior extension: no-cache means revalidate, not do not store; no-store is the storage restriction. I test browser, CDN, and origin behavior with distinct users/locales and inspect Age/cache-status/ETag. Authorization, cookies, compression, experiments, and currency can all create variants. A missing key dimension is a data leak, not merely stale content.
BACKEND-HTTP-04 — Example answer
Solid response: Authentication establishes identity. CSRF abuses credentials a browser attaches automatically, such as a session cookie, to cause a state-changing request. CORS controls whether browser script from another origin may read or make certain cross-origin requests; it is not server authorization and does not stop non-browser clients or all form-like requests.
So an allowlist CORS policy can be correct while a cookie-authenticated mutation lacks CSRF protection.
Senior extension: I use framework CSRF tokens, appropriate SameSite cookies, and origin checks where suitable, plus authorization on every action. XSS is a separate and often stronger problem because script running in the trusted origin can act as the user. I test actual browser credential and preflight behavior rather than assuming headers imply protection.
BACKEND-HTTP-05 — Example answer
Solid response: A one-off event is an instant; I store it unambiguously, commonly as UTC, and serialize with an explicit offset. A recurring 09:00 rule is local calendar intent. I store the local time, recurrence rule, and IANA zone such as Europe/Madrid, then calculate each next instant using the current zone rules.
Converting once to UTC would shift local execution across daylight-saving changes.
Senior extension: I define behavior for skipped or repeated local times, rule updates, date-only values, precision, and inclusive ranges. I use a monotonic clock for elapsed deadlines, not wall time. For distributed ordering, timestamps are diagnostic evidence rather than a total causal sequence, so business ordering needs versions or sequence identifiers.
BACKEND-HTTP-06 — Example answer
Solid response: These are separate contracts. I preserve raw bytes and media type to find incorrect UTF-8 decoding or byte truncation; Unicode code points and grapheme clusters differ. Large numeric identifiers may exceed a consumer’s exact integer range, so I serialize opaque IDs as strings. A date-only value should stay a date, while an instant needs an offset/zone-aware representation.
I add round-trip tests at each producer/consumer boundary.
Senior extension: I inspect URL/form decoding and double-decoding, JSON libraries, database column encoding, normalization assumptions, and logs that may corrupt evidence. Money gets a decimal or currency-aware minor-unit model, not binary float. Contract schemas document string IDs and temporal types, with fixtures for emoji sequences, combining marks, maximum IDs, DST transitions, and negative offsets.
BACKEND-API-01 — Example answer
Solid response: I use HTTP status for the broad category and a JSON problem document with a stable machine type/code, safe human title/detail, correlation ID, and structured field violations. Clients branch on the stable code, not English. I distinguish malformed input, authentication, authorization/not-visible, conflict, throttling, and transient dependency failures and document retryability.
Stack traces, SQL, internal hosts, secrets, and raw vendor bodies stay in protected logs.
Senior extension: RFC 9457 is a useful base with application extension fields. I version code semantics carefully, keep unknown fields ignorable, and test generated/strict clients. Batch operations define atomicity or per-item outcomes. Correlation IDs connect client errors to traces without exposing high-cardinality sensitive context.
BACKEND-API-02 — Example answer
Solid response: Offset is simple and supports page numbers, but large offsets may be expensive and concurrent inserts/deletes shift rows, causing duplicates or omissions. I prefer keyset pagination for a feed using a deterministic indexed order such as (tenant_id, created_at, id) and continue after the last tuple.
The cursor is opaque and bound to tenant, filters, direction, and sort.
Senior extension: Keyset traversal is not automatically a snapshot; updates to sort keys can still move rows. I define live versus snapshot semantics, cursor expiry, page-size caps, reverse traversal, and whether totals are exact enough to justify their cost. I sign cursors if tampering matters and never use a non-unique timestamp without a tie-breaker.
BACKEND-API-03 — Example answer
Solid response: The client supplies a unique key for one logical operation. The server scopes it to caller/operation, fingerprints the request, and atomically persists key, operation state, and eventual response. Concurrent repeats converge, while reuse with different input is rejected. The same provider operation key is used downstream.
After timeout, retry returns or resolves the original outcome rather than issuing another charge.
Senior extension: I define retention, in-progress responses, which failures are replayed, and reconciliation for unknown provider outcomes. A cache-only check-then-set is insufficient for durable money state. Idempotency handles repeated commands; optimistic versions handle conflicting different commands. Logs and metrics carry operation and attempt IDs without exposing the key as authorization.
BACKEND-API-04 — Example answer
Solid response: Adding an optional response field can break strict decoders, signatures, snapshots, or generated clients. A new enum case breaks exhaustive switches. Changing defaults, nullability, ordering, numeric precision, accepted input, or an “optional” field’s meaning can also break consumers.
I prefer additive changes, tolerant response readers, and expand/migrate/contract rollout with observed client usage.
Senior extension: Deprecation includes an alternative, owner, notice, telemetry, and sunset date; a /v2 path alone does not migrate anyone. I run schema and consumer compatibility tests and test old/new producers and consumers during rolling deploys. When semantics truly diverge, I version explicitly rather than making the same representation context-dependent.
BACKEND-API-05 — Example answer
Solid response: I enforce HTTPS and body limits, preserve the exact raw body, and verify the provider signature and signed timestamp before parsing or mutation. Secret rotation allows an overlap. I persist the provider event ID under a unique constraint and acknowledge after durable receipt, then process idempotently in a worker.
Duplicates and out-of-order delivery are expected; arrival order is not truth.
Senior extension: If entity order matters, I use provider versions or refetch current state. Processing state and effects commit together or are recoverable, and failed items enter owned retry/dead-letter workflows. Reconciliation can list provider events or compare state. IP allowlists are defense in depth, signature comparison is timing-safe where relevant, and logs retain audit metadata without signed secrets or personal payloads.
BACKEND-API-06 — Example answer
Solid response: The GET returns an ETag or explicit version. The client sends If-Match with its update, and the server applies the change only if that validator still matches. A stale writer receives 412 Precondition Failed, reloads, and lets the user or domain policy merge rather than silently overwriting.
The compare and update must be atomic at the storage boundary.
Senior extension: I distinguish full replacement from patch semantics and define whether a representation ETag is strong enough for concurrency. An application version column can back the validator. Automatic retry is unsafe when user intent conflicts; commutative operations may instead use atomic increments or domain commands. Idempotency keys do not solve two different stale edits.
BACKEND-TESTING-01 — Example answer
Solid response: I unit-test the pricing policy with boundary/table/property cases. I test constraints, transactions, and queries against the production database engine. I drive HTTP middleware/authorization/serialization through the application boundary. I keep a small end-to-end checkout test for wiring and the critical user journey.
Each test states what is real and asserts an observable contract or invariant.
Senior extension: The cheapest credible boundary depends on risk, not a fixed pyramid quota. I add controlled concurrency and migration tests where engine behavior matters and avoid duplicating framework code in mocks. Production canaries and monitoring cover topology/load uncertainty. Failures should point to one boundary quickly enough that the suite remains useful.
BACKEND-TESTING-02 — Example answer
Solid response: I wrap the provider SDK in an interface I own. Policy tests stub deterministic responses; a fake can model multi-step states if its semantics are intentionally maintained. A mock is appropriate when emitting one correctly identified call is the outcome. Contract tests verify my adapter’s request/response mapping, while provider sandbox/smoke tests cover authentication and real protocol wiring.
No one layer proves all behavior.
Senior extension: I avoid mocking SDK internals or using an in-memory fake as proof of timeouts, idempotency, quotas, or webhook signatures. Fixtures are versioned from safe provider examples, and failure/unknown outcomes are modeled. Live tests are rate-limited and isolated, with reconciliation/cleanup. The boundary reduces vendor churn rather than inventing a fictional provider.
BACKEND-TESTING-03 — Example answer
Solid response: I inject failures at each boundary: before/after local commit, after provider success before outcome recording, and before acknowledgement. The provider fake/sandbox understands a stable idempotency key. I redeliver the same message and assert one logical external effect, convergent local state, and correct acknowledgement/retry behavior.
Unknown outcomes remain pending for reconciliation rather than guessed failed.
Senior extension: I exercise serialization and a real broker/database path for risky semantics, control concurrent consumers with barriers, and test visibility timeout. Permanent versus transient errors and dead-letter ownership are asserted. A reconciliation test repairs a provider/local mismatch idempotently. Attempt and operation IDs make failure artifacts diagnosable.
BACKEND-TESTING-04 — Example answer
Solid response: I preserve the seed/order/worker and inspect failure artifacts before rerunning. Then I look for shared database rows, static/global state, clock/timezone, files/ports, queue names, environment mutation, non-awaited async work, and transaction cleanup. I reproduce with the same parallelization and random order, then reduce to the interacting tests.
Sleeping or retrying is not a fix.
Senior extension: I isolate per-worker databases/resources, inject clocks and IDs, wait on observable completion, and remove order dependence. Quarantine is temporary with owner and deadline. I track flaky probability and suite health because intermittent green is still failing evidence; framework/process state leakage may also reveal a production worker-lifetime defect.
BACKEND-TESTING-05 — Example answer
Solid response: Static analysis explores type/control-flow possibilities under its model without running code. Coverage shows which code executed, not whether assertions would detect defects. Mutation testing changes behavior and checks whether tests fail, revealing weak assertions or unreachable/equivalent code.
Together they are complementary, but none proves database isolation, deployment configuration, external contracts, or complete requirements.
Senior extension: I ratchet a static baseline, inspect unexecuted high-risk branches, and mutation-test important deterministic units/changed code. I review survivors rather than chase percentages. Native types, runtime boundary validation, property tests, integration tests, code review, and production evidence cover different uncertainty. Tool configuration/stubs are themselves part of the trusted model.
BACKEND-TESTING-06 — Example answer
Solid response: Presubmit runs deterministic formatting/lint, static analysis, unit tests, and focused real-database integration in parallel. Heavier browser, matrix, mutation, dependency/image, and deploy checks run by affected risk or after merge, with a periodic full run. Required checks are pinned, owned, and publish useful reports.
I track queue time, duration, flake/failure rate, and repair time.
Senior extension: Cache keys include lockfiles/runtime/config, forked code cannot reach secrets, and artifacts redact sensitive data. Test selection is validated by full runs so omissions are visible. Emergency bypass is authorized/audited with compensating checks. A gate that teams rerun blindly or routinely bypass is not strict; it is noisy theater.
BACKEND-SECURITY-01 — Example answer
Solid response: Assets are tenant data, identities, export files, and availability. I authorize export creation against the tenant and capability, resolve rows through tenant scope, constrain filters/size/rate, and store a job with actor/tenant IDs. The worker resolves fresh scope rather than trusting serialized models. Output uses generated names in private storage and a short-lived authorized/signed download.
Every create/download is audited and sensitive content is not logged.
Senior extension: I consider IDOR, filter injection, role revocation during execution, cross-tenant connection state, CSV formula injection, object-store ACL/cache leaks, predictable URLs, and resource exhaustion. Policy defines whether completion uses original or current authorization. Retention/deletion and encryption follow data classification, and anomaly alerts cover unusual bulk volume.
BACKEND-SECURITY-02 — Example answer
Solid response: Validation says input has an acceptable shape/domain; it does not grant access. Parameterization keeps SQL values out of the query grammar, but dynamic identifiers/raw fragments need allowlisting. Authorization decides whether the actor may perform the action. Contextual output encoding prevents data becoming executable in a specific HTML/JS/URL context.
A numeric project ID can be valid and parameterized yet still expose another tenant’s record.
Senior extension: I map each untrusted value through its full lifecycle and use structured APIs for every interpreter. Sanitization is for intentionally allowed rich content, not a universal substitute for encoding. Database constraints own durable invariants, CSP is defense in depth, and tests include alternate object IDs and output contexts rather than only malformed input.
BACKEND-SECURITY-03 — Example answer
Solid response: Prefer an allowlist of required schemes and destinations. Parse once, reject credentials/unsupported ports, resolve DNS, and block loopback, private, link-local, metadata, multicast, and other forbidden ranges for IPv4/IPv6. The connection layer enforces egress policy and destination, revalidates redirects, and applies strict connect/read/total timeout and response-size limits.
The response is treated as untrusted content.
Senior extension: DNS can rebind between check and connect, so network firewall/proxy controls are essential and resolution should be bound/rechecked. Redirect chains, alternate numeric IP forms, proxies, and parser discrepancies are tested. The fetcher runs least-privileged without ambient cloud credentials, isolates heavy parsing, and logs safe destination/outcome metadata for abuse detection.
BACKEND-SECURITY-04 — Example answer
Solid response: I authenticate/authorize, cap count and bytes, generate an object ID/name, and inspect signature/content rather than trust filename or MIME. Store outside executable/public paths with private ACL. Scan or transform according to risk in an isolated worker with CPU/memory/time limits. Downloads reauthorize and use safe content type/disposition; original names are encoded metadata only.
I reject archive expansion and path traversal.
Senior extension: I model parser vulnerabilities, decompression bombs, polyglots, SVG/HTML active content, symlinks, object-store callback trust, and quarantine transitions. Signed URLs are short-lived and scoped; CDN cache keys cannot cross tenants. Malware verdict updates and deletion/retention are auditable, and failed processing cannot publish partially trusted content.
BACKEND-SECURITY-05 — Example answer
Solid response: Treat it as compromised immediately: preserve evidence, remove public exposure without destroying the timeline, identify key purpose/scope and all environments/artifacts, rotate/revoke with controlled rollout, and invalidate dependent sessions/tokens/signatures as required. Search logs/repos/images and restrict attacker persistence.
Encryption keys may expose stored ciphertext; signing keys may allow forged cookies, URLs, or payloads.
Senior extension: Rotation may need dual-read/new-write, key IDs, re-encryption, or mass session revocation. I assess when exposure began and correlate anomalous key use, notify security/legal/customers according to impact, and rebuild compromised artifacts/credentials. Root cause covers CI secret scoping/redaction, least privilege, automated detection, and a rehearsed future rotation path.
BACKEND-SECURITY-06 — Example answer
Solid response: Store passwords with the platform’s current adaptive hash and rehash policy, allow long passwords, check compromised/common choices, and rate-limit by several risk signals without easy account lockout DoS. Sessions use unpredictable IDs, secure HttpOnly/SameSite cookies, rotation after login/privilege change, expiry and revocation. Reset tokens are random, short-lived, single-use, and stored safely.
MFA and recovery changes require reauthentication and audit.
Senior extension: Recovery is threat-modelled as authentication: protect email/helpdesk/SIM paths, use recovery codes and step-up for sensitive actions, notify on changes, and delay/highlight risky resets. Prevent enumeration with consistent responses while retaining internal signals. Credential stuffing, session theft, OAuth linking, device loss, and support override playbooks are monitored and tested.
BACKEND-PERFORMANCE-01 — Example answer
Solid response: Stable p50 with worse p99 suggests a subset: large tenants/payloads, cache misses, lock/pool waits, dependency retries, GC/allocation, or hot partitions. I compare slow and normal traces, segment by input/cache/dependency/outcome, and separate queue wait from execution. I inspect connection pools, lock waits, query plans/rows, downstream latency, memory, and event/worker queues.
Average CPU does not exclude localized saturation.
Senior extension: I correlate deploy/data/traffic changes and preserve client-side timeouts/errors so slow abandoned work is visible. A controlled reproduction uses the affected distribution, then a focused fix is canaried against p50/p95/p99, throughput, errors, saturation, and business results. I avoid optimizing a common fast span that is absent from the tail.
BACKEND-PERFORMANCE-02 — Example answer
Solid response: I define the request mix and latency/error objective, then load with realistic arrivals and data while increasing concurrency. I measure arrival/completion throughput, queue/pool wait, DB connections/locks/CPU, provider quota/latency, application CPU/memory, and tails. The useful limit is before throughput flattens and queueing/errors rise sharply, with headroom.
Concurrency is capped by the smallest critical pool/dependency, not just PHP capacity.
Senior extension: I test bursts, cold cache, dependency degradation, retry behavior, and failover. Open-arrival testing exposes overload that closed-loop clients can hide. Backpressure and shedding are validated at the knee. Little’s Law is a sanity check, while observed distributions and saturation decide production limits and autoscaling signals.
BACKEND-PERFORMANCE-03 — Example answer
Solid response: For FPM I measure per-worker RSS distribution and CPU/service time under representative requests. Total workers must fit memory with OS/agents headroom and avoid swapping, while database connections and downstream capacity support the concurrency. Queue workers also include per-job memory/duration, broker visibility, and provider limits.
I raise concurrency in load tests until throughput stops improving or latency/saturation worsens.
Senior extension: More workers may only move the queue to the database. I monitor FPM/queue wait, active/idle workers, DB pool wait, CPU throttling, RSS, and job age. Separate pools can isolate slow workloads. Container CPU/memory limits, autoscaling warmup, graceful shutdown, and long-lived state leaks are included in capacity/failover tests.
BACKEND-PERFORMANCE-04 — Example answer
Solid response: I trace the path first. If rows scanned/sorts dominate, fix query/index/data access. If repeated independent calls dominate, remove or batch them. Cache when reads repeat and freshness/invalidation/failure contracts are acceptable. Move optional slow work async when the product permits delayed completion. Replicas help eligible read capacity with staleness; denormalization is for a measured read shape with owned synchronization.
I change the largest relevant term.
Senior extension: I compare correctness and cost migration: cache stampede/staleness, replica read-your-write, denormalization write/reconciliation, queue backlog, index write amplification. I set a before/after workload and observe tails, memory, writes, dependencies, and failures. The simplest change meeting the budget wins, with a documented assumption/revisit threshold.
BACKEND-PERFORMANCE-05 — Example answer
Solid response: I model production endpoint/job mix, independent arrival pattern, concurrency, data cardinality/skew, payloads, authentication, cache state, dependency latency/errors, and topology. The generator is validated not to saturate. I measure client latency including timeouts/errors plus server queueing, spans, CPU, memory, pools, database, cache, and downstream quotas.
I test steady state and expected peaks, not just a short warm-cache run.
Senior extension: Scenarios include burst, cold start/cache loss, deploy/restart, degraded dependency, failover, and recovery/drain. Test data and external calls are authorized and isolated. I report distributions and sent/completed rates with environment/version, reproduce runs, and use canary production evidence to revise the model rather than claim the lab is exact.
BACKEND-PERFORMANCE-06 — Example answer
Solid response: Vertical scale is simplest when one node is constrained and larger resources are economical. Horizontal scale helps stateless/partitionable application work only if shared databases, caches, quotas, and state can support it. Read replicas offload eligible reads with lag/read-your-write trade-offs. Partitioning helps data/write boundaries or isolation after those are proven bottlenecks, but adds routing and cross-partition operations.
The constrained resource and growth model drive the choice.
Senior extension: I include failure redundancy, rebalancing, hot tenants, deploy/state lifetime, consistency, recovery, operational skill, and cost. A queue absorbs bursts but does not add service capacity. I validate scale-out efficiency and failover under load, retain headroom, and avoid sharding before query/model/capacity fixes have been exhausted with evidence.