Last Minute Notes

Backend Interview Playbook

Backend interview preparation: what each level is graded on, a 60-question bank with pointers, a worked REST API design exercise, coding round tasks mapped to runnable examples, a production debugging flowchart, cheat sheets, common mistakes, and study plans.

📘 Backend Interview Playbook

The other pages teach the material. This page is for rehearsal: what interviewers look for, a bank of questions with what a strong answer covers, a full API design walk-through, coding tasks you can practice with the runnable examples, and a way to debug production problems out loud.

Table of Contents

  1. What Interviewers Look For
  2. Question Bank
  3. Worked Exercise: Design a Booking API
  4. Coding Round Tasks
  5. Debugging Production Out Loud
  6. Cheat Sheets
  7. Common Mistakes
  8. Study Plans

1. What Interviewers Look For

LevelExpected
JuniorHTTP and REST basics, status codes, CRUD with validation, SQL basics, error handling, can read and write clean code and tests
MidSound API and schema design, authentication flows and common vulnerabilities, N+1 and caching, async jobs and idempotency, debugging with logs and plans, framework internals (event loop, DI, transactions)
SeniorTrade-offs and failure modes: consistency, retries, backpressure, security architecture, observability, deployment safety, performance analysis, mentoring through design
StaffCross-service design, migration and rollout strategy, reliability and cost, technical direction, translating business risk into engineering decisions

Signals that raise your rating: you clarify requirements, you name the failure mode of each choice (what if the request is retried, the dependency is slow, two users click at once), you protect data (validation, authorization, least privilege), and you can debug systematically.


2. Question Bank

Sixty questions, with a checklist of what a strong answer includes.

2.1 HTTP, Web and Fundamentals (12)

#QuestionStrong answer includesRead
1What happens when you type a URL and press enter?DNS, TCP or QUIC, TLS, HTTP request, server processing, response, keep-aliveFundamentals
2GET vs POST vs PUT vs PATCH vs DELETESafe and idempotent, body, typical use, retriesFundamentals
3Explain common status codes and 401 vs 403, 400 vs 422Ranges, meaning, client vs server errorFundamentals
4What is idempotency and why does it matter?Retries, examples, idempotency keysAPI Design
5What are cookies and their security attributes?HttpOnly, Secure, SameSite, scope, session idsFundamentals
6What is CORS and how does preflight work?Same-origin policy, headers, credentials, not a server security controlFundamentals
7HTTP/1.1 vs HTTP/2 vs HTTP/3Multiplexing, head-of-line blocking, QUICFundamentals
8How do you structure a backend service?Controller, service, repository, DTOs, middleware, composition rootFundamentals
9What is the twelve-factor app?Config in env, stateless, logs to stdout, disposabilityFundamentals
10Liveness vs readinessRestart vs remove from traffic, shallow livenessDeployment
11How does a server handle many concurrent requests?Thread pool, event loop, virtual threads, I/O bound vs CPU boundFundamentals
12How do you handle errors in an API?Central handler, no leaks, problem details, correlation idAPI Design

2.2 APIs (10)

#QuestionStrong answer includesRead
13Design REST resources for a domainNouns, nesting, ids, status codes, examplesAPI Design
14Offset vs cursor paginationDeep offset cost, stable cursors, signed opaque cursorAPI Design
15How do you version an API and deprecate safely?Additive changes, path or header versions, Sunset headerAPI Design
16Make POST safe to retryIdempotency key with unique constraint and stored responseAPI Design
17Prevent lost updates in RESTETag and If-Match, 412API Design
18REST vs GraphQL vs gRPCFit, caching, typing, streaming, N+1API Design
19Design webhooksSignatures, timestamps, retries, idempotent receivers, replayAPI Design
20Expose a long-running operation202, status resource, polling or webhookAPI Design
21Rate limiting designAlgorithms, 429, Retry-After, per key tiersClassic Designs
22What belongs in an error response?RFC 9457 fields, trace id, no internalsAPI Design

2.3 Authentication and Security (12)

#QuestionStrong answer includesRead
23Authentication vs authorizationDefinitions, 401 vs 403Security
24How do you store passwords?Argon2id or scrypt or bcrypt, salt, pepper, rate limitsSecurity
25Sessions vs JWTRevocation, storage, CSRF, scalingSecurity
26JWT pitfallsalg pinning, claims validation, revocation, storageSecurity
27OAuth authorization code with PKCESteps, why PKCE, redirect URI, stateSecurity
28Refresh token rotationSingle use, reuse detection, revoke familySecurity
29CSRF and defensesSameSite, tokens, Origin, no state change on GETSecurity
30SQL injection and preventionParameterization, allowlists for identifiers, least privilegeSecurity
31IDOR or BOLAObject-level checks in queriesSecurity
32XSS and SSRFEncoding and CSP, allowlists and metadata protectionSecurity
33OWASP Top 10:2025 highlightsAccess control first, supply chain, exceptional conditionsSecurity
34How would you secure a new public API?TLS, authn, authz, validation, rate limits, secrets, loggingSecurity

2.4 Node.js and Java (8)

#QuestionStrong answer includesRead
35How does the Node.js event loop work?Phases, microtasks, libuv pool, blockingNode and Spring
36How do you handle CPU-bound work in Node?Worker threads, queues, separate serviceNode and Spring
37What is middleware?Chain, next, short-circuit, orderingNode and Spring
38Dependency injection in SpringIoC container, constructor injection, testingNode and Spring
39Why did my @Transactional not roll back?Proxy, self-invocation, checked exceptions, visibilityNode and Spring
40JPA N+1 and fixesFetch join, entity graph, batch, DTOsNode and Spring
41Spring MVC vs WebFlux vs virtual threadsBlocking vs reactive, when eachNode and Spring
42Node vs Java for a new serviceWorkload, team, ecosystem, operationsNode and Spring

2.5 Performance, Async, Architecture, Delivery (18)

#QuestionStrong answer includesRead
43Approach a slow endpointMeasure, trace, profile, fix the biggest, re-measurePerformance
44HTTP caching with ETagValidators, 304, Cache-ControlPerformance
45Cache stampedeSingle-flight, jitter, stale-while-revalidatePerformance
46Cache invalidation strategiesTTL, delete on write, events, versioned keysPerformance
47N+1 and DataLoaderBatching per tick, caching per requestPerformance
48Size a connection or thread poolLittle's law, small pools, backpressurePerformance
49Design background job processingQueue, workers, retries, DLQ, idempotencyAsync
50The dual write problem and outboxAtomic event with data, relay, at-least-onceAsync
51Retries: backoff, jitter, budgetsWhy, formula, stormsAsync
52Run a cron job on many instancesLock or leader, idempotent, alert on missing runsAsync
53Queue or KafkaTask distribution vs replayable logAsync
54Hexagonal architecturePorts, adapters, dependency rule, testabilityArchitecture
55Aggregate, entity, value objectDDD tactical patternsArchitecture
56Testing strategy for a servicePyramid, fakes, Testcontainers, contract testsArchitecture
57Mock vs stub vs fakeDefinitions, prefer fakesArchitecture
58Graceful shutdownSIGTERM, drain, close pools, grace periodDeployment
59Zero-downtime deploy with a schema changeRolling or canary, readiness, expand and contractDeployment
60Secrets managementSecret manager, workload identity, rotation, no secrets in imagesDeployment

3. Worked Exercise: Design a Booking API

Prompt: design the HTTP API for a movie ticket booking service (browse shows, hold seats, pay, get tickets). Talk through it in this order.

3.1 Requirements and Resources

Clarify: public or internal API, web and mobile clients, expected traffic, payment provider, seat holds with a timeout, cancellations.

ResourcePurpose
/movies, /showsCatalog, read-heavy, cacheable
/shows/{id}/seatsSeat map with availability
/holdsTemporary reservation of seats (expires)
/bookingsConfirmed purchases
/bookings/{id}/payments, /bookings/{id}/cancellationsActions modeled as sub-resources

3.2 Key Endpoints

GET    /v1/shows?movieId=12&date=2026-06-01&limit=20&cursor=...     list shows, cacheable, cursor pagination
GET    /v1/shows/501/seats                                          200, ETag, short max-age

POST   /v1/holds                                                     Idempotency-Key required
       { "showId": 501, "seatIds": ["A1", "A2"] }
       201 Created, Location: /v1/holds/h_9f2
       { "id": "h_9f2", "seatIds": ["A1","A2"], "expiresAt": "2026-06-01T18:05:00Z" }
       409 Conflict   (a seat is taken)   application/problem+json

POST   /v1/bookings                                                  Idempotency-Key required
       { "holdId": "h_9f2", "paymentMethodId": "pm_123" }
       201 Created, Location: /v1/bookings/b_77   or   402 / 422 payment failed   or   410 Gone   (hold expired)

GET    /v1/bookings/b_77                                             owner only, 404 for others
POST   /v1/bookings/b_77/cancellations                               202 Accepted, refund handled asynchronously

3.3 The Points That Show Depth

TopicWhat to say
Double bookingThe hold is an atomic check-and-set in the database (unique constraint on confirmed seats, conditional update), see Transactions and ticket booking
IdempotencyIdempotency-Key on POST /holds and POST /bookings, so a client retry after a timeout never creates two holds or charges twice
PaymentCall the provider with its own idempotency key, handle the unknown outcome (timeout) by querying status, confirm the booking via webhook or reconciliation, keep a state machine (PENDING, CONFIRMED, FAILED, CANCELLED)
Hold expiryexpiresAt stored and enforced at confirm time, a job releases expired holds, return 410 Gone on a stale hold
AuthorizationJWT or session, a user can only read their own bookings (WHERE id = ? AND user_id = ?), 404 not 403 for others, scopes for admin routes
CachingCatalog endpoints with Cache-Control and CDN, the seat map with a short TTL and ETag, but the hold call is always authoritative
Rate limits and abusePer user and IP limits, a waiting room for hot events, bot protection
ErrorsRFC 9457 problem details with stable type values (seat-unavailable, hold-expired)
Async workTicket generation and emails via queue with the outbox, see Async
ObservabilityCorrelation id on every request, metrics for hold success rate, payment failures, expiry, and booking latency, alerts on SLO burn
Evolution/v1 prefix, additive changes, deprecation headers

Close with what you would do next (webhooks for partners, pagination for bookings, multi-region).


4. Coding Round Tasks

Practice these in 30 to 45 minutes each. The runnable examples in this section are starting points.

TaskWhat it testsReference
Build a CRUD REST API for tasks with validation and correct status codesHTTP, routing, error handlingServer from scratch
Add rate limiting middleware (token bucket)Algorithms, per-key state, 429 and headersRate limiter, LLD version
Implement an LRU cache with TTLData structures, invariantsLRU, cache with single-flight
Implement retry with exponential backoff and jitterAsync control flow, error classificationRetry
Build an in-memory job queue with retries and a dead-letter listConcurrency limits, idempotencyJob queue
Implement cursor pagination with a signed cursorKeyset logic, HMACCursor demo
Implement idempotency keys for a payment endpointStorage, hashing, replayIdempotency demo
Verify a webhook signatureHMAC, constant-time compare, replay windowWebhook demo
Write JWT auth middlewareVerification, claims, errorsJWT demo
Implement TOTP verificationHMAC, time windows, test vectorsTOTP demo
Batch requests in one tick (DataLoader) and limit concurrencyPromises, batchingBatching demo
Implement graceful shutdownSignals, drainingShutdown demo
Design a URL shortener API and code the coreKey generation, redirects, cachingURL shortener
Prevent overselling with an atomic SQL updateConcurrency, SQLTransactions

Tips for coding rounds:

  • Ask about input size, concurrency, error handling and persistence before typing.
  • Get a working vertical slice first, then validate, then handle errors, then tests.
  • Name things well, keep functions small, and inject the clock, ids and I/O so code is testable.
  • State complexity and what would change at ten times the load.
  • Write two or three tests, including a failure case, even if time is short.

5. Debugging Production Out Loud

Interviewers often give a symptom ("the API is slow", "we see intermittent 500s"). Show a structured approach: mitigate first, then find the cause, then prevent recurrence.

Habits to narrate:

  • Use the golden signals (latency, traffic, errors, saturation) and RED per endpoint.
  • Follow one bad request through logs and traces by correlation id.
  • Check what changed first: deploys, config, flags, data, dependencies, traffic, dates (certificate expiry, quotas).
  • Form a hypothesis and test it with a query, a metric or a repro, rather than changing many things.
  • Communicate: status updates, impact, ETA, and a written timeline for the post-incident review.
  • Prevent recurrence: add the missing alert, a test, a timeout, a limit or a runbook, see Reliability and Operations.

Common root causes to mention: N+1 or missing index after a deploy, connection pool exhaustion caused by a slow dependency, retry storms, cache stampede after expiry or restart, unbounded queries or payloads, event-loop blocking, memory leaks, expired certificates or credentials, and misconfigured timeouts.


6. Cheat Sheets

6.1 HTTP

Safe:        GET HEAD OPTIONS        Idempotent: GET HEAD PUT DELETE OPTIONS       Not idempotent: POST (PATCH depends)
2xx  200 OK  201 Created+Location  202 Accepted  204 No Content
3xx  301 302 307 308 redirects     304 Not Modified (conditional GET)
4xx  400 malformed  401 unauthenticated  403 forbidden  404 not found  405 method  409 conflict
     410 gone  412 precondition failed  415 media type  422 invalid data  429 too many requests
5xx  500 bug  502 bad gateway  503 unavailable (Retry-After)  504 gateway timeout
Caching:     Cache-Control max-age / no-cache / no-store / private / public / immutable,  ETag + If-None-Match -> 304
Cookies:     HttpOnly  Secure  SameSite=Lax  __Host- prefix

6.2 Auth and Security

Passwords:   Argon2id | scrypt | bcrypt, unique salt, constant-time compare, rate limit, breached list
Sessions:    random id in HttpOnly Secure SameSite cookie, rotate on login, idle and absolute timeout, CSRF defense
JWT:         pin alg, check exp iss aud, short-lived access + rotating refresh, never sensitive data, no localStorage
OAuth:       Authorization code + PKCE for users, client credentials for services, exact redirect URIs, no implicit or password grant
MFA:         TOTP (RFC 6238), passkeys (WebAuthn) are phishing resistant, avoid SMS for high risk
AuthZ:       deny by default, check every object (BOLA), central policy, tenant isolation
Injection:   parameterize SQL, encode output, validate with allowlists, block SSRF to private ranges, no mass assignment
OWASP 2025:  A01 Broken Access Control, A02 Misconfiguration, A03 Supply Chain, A04 Crypto, A05 Injection, A06 Insecure Design,
             A07 Authentication Failures, A08 Integrity Failures, A09 Logging and Alerting, A10 Exceptional Conditions

6.3 Reliability Patterns

Timeout everything | retry only idempotent calls with backoff + jitter + budget | circuit breaker | bulkhead | load shedding
Idempotency key on POST | dedupe table in consumers | outbox for DB + event | DLQ for poison messages
Graceful shutdown: SIGTERM, fail readiness, stop accepting, drain, close pools, exit
Liveness shallow, readiness reflects ability to serve, startup probe for slow boot
Expand and contract for schema changes | build once deploy many | canary with automated rollback

6.4 Performance

Measure p95 p99 first | trace to the slow hop | N+1 -> join or batch | parallelize independent I/O, bound concurrency
HTTP cache + CDN | app cache with TTL jitter and single-flight | pool sized by the database | compress and paginate
Node: never block the loop, workers for CPU | JVM: heap vs container, GC, virtual threads for blocking I/O

7. Common Mistakes

MistakeBetter
Jumping to code without clarifyingAsk about scale, clients, consistency and failure behavior
Ignoring retries and duplicatesIdempotency keys, dedupe, at-least-once thinking
Authentication without authorizationCheck ownership on every object
Trusting client inputValidate at the boundary, allowlist fields, parameterize queries
Returning 200 for errors, or 500 for bad inputCorrect 4xx and 5xx with a problem body
Leaking internals in errorsGeneric message plus correlation id, details in logs
Blocking the event loop or the thread poolOffload CPU work, use async I/O, bound concurrency
Unbounded everything (queries, payloads, retries, queues)Limits, pagination, timeouts, backoff, bounded queues
Caching without invalidation or key dimensionsTTLs, versioned keys, per-user scoping, stampede protection
Long transactions and remote calls inside themShort transactions, outbox for side effects
No timeouts on outbound callsTimeouts and circuit breakers on every dependency
Secrets in code, images or logsSecret manager, workload identity, redaction
Only happy-path testsFailure, duplicate, concurrent and boundary cases
Debugging by guessingScope, follow a trace, check what changed, one hypothesis at a time

8. Study Plans

8.1 Four Weeks

WeekLearnPractice
1: FoundationsFundamentals, Node and Spring, API DesignBuild the CRUD API from scratch, add validation, errors, pagination and idempotency keys
2: Security and dataAuthentication and Security, the Databases fundamentals, SQL and indexing pagesImplement JWT middleware and password hashing, find and fix an injection and an IDOR, read query plans
3: Reliability and scalePerformance and Caching, Async Processing, TransactionsJob queue with retries and outbox, cache with single-flight, oversell prevention
4: Architecture and deliveryArchitecture and Testing, Deployment, System DesignWrite tests with fakes and Testcontainers, containerize, add graceful shutdown, do two mock interviews (design and debugging)

8.2 Seven-Day Crash Plan

DayFocus
1HTTP, status codes, REST design, idempotency, pagination
2Auth flows: sessions, JWT, OAuth with PKCE, passwords, CSRF and CORS
3Security: OWASP list, injection, IDOR, SSRF, secrets
4Node event loop and Spring transactions and DI, ORM pitfalls
5Caching, N+1, connection pools, async jobs, retries, outbox
6Architecture, testing strategy, deployment, probes, graceful shutdown
7Worked API design exercise, a debugging drill out loud, review the cheat sheets

Next steps beyond this section: System Design for architecture-level questions, and Databases for the data layer.

On this page