Backend interview bank

Questions interviewers actually ask, each answered at the length you would say it aloud, with the topic to reread if you were not sure.

95 questions Junior Senior
All levels Junior Mid Senior
Reveal one by one Show all answers
Report an error

HTTP and APIs

31 questions
01 What must an HTTP operation contract define besides its URL and JSON schema? Junior common reveal ▾ hide ▴

It must define the complete observable exchange. That includes the method, target resource, accepted parameters and media types, authentication and authorization rules, success and error statuses, response headers, and representation shapes. It must also cover behavior over time: retry safety, concurrency preconditions, stable pagination, and relevant retention windows. OpenAPI can encode much of the message shape, but not a rule such as “the caller owns this order” or an atomic idempotency guarantee. Those promises need prose plus scenario or policy tests at the real HTTP boundary.

Was this clear?
02 How do safe, idempotent, and retryable HTTP operations differ? Mid common reveal ▾ hide ▴

Safe describes requested intent: the client is not asking to change server state. Idempotent describes effect: repeating the same request has the same intended server effect as sending it once. GET is safe and idempotent; PUT and DELETE are idempotent but not safe. Retryable is a wider application decision that also depends on the failure point and remaining deadline. A POST can be safely retried after an unknown outcome only when the caller reuses one operation key and the server atomically deduplicates the same request fingerprint and returns its stored result.

Was this clear?
03 How does an ETag prevent a lost update, and what implementation detail matters most? Senior common reveal ▾ hide ▴

The server returns a strong ETag for the current representation, and the client sends that value in If-Match when updating or deleting it. The server performs the mutation only if the current tag still matches; a stale tag normally yields 412 Precondition Failed. The crucial detail is atomicity. Reading a version, comparing it in application code, and later issuing an unconditional update leaves another race window. The comparison and write must be one conditional database operation or transaction. After success, return the new ETag so the next edit has a fresh validator.

Was this clear?
04 How would you decide whether an API change is backward compatible? Senior occasional reveal ▾ hide ▴

I judge compatibility from what supported consumers can observe, in both message directions. Narrowing accepted request input or removing a response field is usually risky; adding a response field can still break strict decoders or closed enum handling. Schema diffs therefore identify candidates, not final truth. I combine the diff with provider conformance tests, consumer scenarios, and usage evidence, then check semantic changes such as defaults, ordering, authorization, and error codes. A breaking change gets an explicit version boundary, migration window, deprecation signal, owner, and tested retirement plan rather than an unannounced release.

Was this clear?
05 What happens when a GraphQL resolver returns null for a Non-Null field? Senior occasional reveal ▾ hide ▴

GraphQL records an error and replaces the nearest nullable ancestor with null. The failure bubbles through every Non-Null parent on the path; if no nullable boundary exists before the operation root, the entire data result becomes null. This is why Non-Null is an availability promise, not merely documentation. For example, marking every field in a product subtree Non-Null can turn one unavailable optional enrichment into loss of the whole product. I place nullable boundaries where partial data remains useful, keep errors observable, and test the exact data-and-errors shape for resolver failures.

read more GraphQL
Was this clear?
06 How do you evolve a Protocol Buffers message without breaking existing gRPC clients? Mid common reveal ▾ hide ▴

Preserve the wire meaning of every published field number. Add new fields with new numbers, tolerate their default values, and reserve numbers and names when fields are removed so they cannot be reused accidentally. Do not change a field to an incompatible wire type or reinterpret its business meaning merely because old readers ignore unknown fields. Compatibility also extends beyond the descriptor: new enum values, validation rules, deadlines, and status mappings can break clients. I keep an older generated client or descriptor in tests and exercise old-client/new-server and new-client/old-server exchanges before deployment.

read more gRPC
Was this clear?
37 What makes an API-first contract an engineering control point rather than documentation written in advance? Mid common reveal ▾ hide ▴

In the OpenAPI 3.2.0 and Node 24 workflow, the reviewed contract is versioned before clients and handlers depend on it. CI parses the description, compares it with the last published contract, and verifies real HTTP statuses, headers, media types, and bodies. Mocks and generated clients must come from the same revision. The trade-off is additional review and tooling, while the pitfall is assuming schema conformance proves authorization or idempotency; those behavioral promises still need scenario and domain tests.

Was this clear?
38 How should an API version selector interact with defaults and HTTP caches? Mid common reveal ▾ hide ▴

On the Node 24 boundary, resolve one documented selector—such as a path or media-type header—before dispatching to a version adapter. An omitted selector must either fail or map to a compatibility version whose meaning stays frozen; silently moving the default to the newest contract breaks old clients. Header-selected representations also need the selecting field in Vary and in the deployed cache key. The trade-off is cache fragmentation, but omitting it can serve a v1 representation to a v2 request.

Was this clear?
39 What evidence should gate the retirement of an API version? Senior common reveal ▾ hide ▴

For a Node 24 service, deprecation announces intent; retirement removes the contract and needs stronger evidence. Record the resolved version and a privacy-safe client identity, inventory supported consumers, publish a tested migration map, and verify that each owner moved before the announced date. Exercise the post-retirement response and a rollback path too. Low traffic alone is insufficient because unattended jobs may be intermittent. Supporting parallel adapters costs maintenance, but premature deletion creates a breaking outage that telemetry after the cutoff cannot prevent.

Was this clear?
43 What does an Elysia route schema provide beyond TypeScript inference? Mid common reveal ▾ hide ▴

In Elysia 1.4.30 on Bun 1.3.10 with TypeScript 6, route schemas validate untrusted path, query, header, body, and response data at runtime while also supplying handler and client types. Static types disappear at the wire, so an annotation or cast alone accepts malformed JSON. Declare per-status response schemas and test actual requests through app.handle() or Eden Treaty. The trade-off is stricter schema maintenance; permissive or missing response schemas can let implementation drift even though editor inference still looks correct.

read more Elysia
Was this clear?
44 Why do registration order and lifecycle scope matter in Elysia? Senior common reveal ▾ hide ▴

Elysia 1.4.30 composes hooks and plugins in registration order and within explicit scopes, so middleware added after a route may not wrap that route. Local, scoped, and global hooks also reach different descendants. Register cross-cutting policy before protected routes, give plugins stable names where deduplication matters, and test both success and thrown-error paths. The pitfall is reading the file topically instead of tracing the composed lifecycle: an authentication hook can appear nearby yet never run for an earlier or differently scoped route.

read more Elysia
Was this clear?
45 How do FastAPI dependency caching and yield cleanup affect request-scoped resources? Senior common reveal ▾ hide ▴

FastAPI 0.141.1 builds a dependency graph for each request. By default, repeated references to the same dependency reuse one resolved value, which is useful for identity or a database session; use_cache=False requests another evaluation. A dependency that yields a resource runs cleanup when its dependency scope ends, so commit, streaming, and background-work timing must be deliberate. The pitfall is returning a lazy stream backed by a resource already closed during cleanup. Test acquisition, exception, cancellation, and response-consumption paths over HTTP.

read more FastAPI
Was this clear?
46 What does a FastAPI response model protect, and what can it not prove? Mid occasional reveal ▾ hide ▴

In FastAPI 0.141.1 with Python 3.14, the declared response model documents the OpenAPI shape and filters or validates returned data before serialization. It helps prevent an ORM object from accidentally exposing internal fields and makes status-specific contracts testable. It cannot prove resource authorization, transaction atomicity, or that every runtime error uses the documented representation. Overly broad models weaken the boundary, while overly narrow ones can drop intended data. Send requests through the ASGI interface and compare statuses, headers, bodies, and generated OpenAPI.

read more FastAPI
Was this clear?
47 What must a backend verify after a client completes a presigned upload? Senior common reveal ▾ hide ▴

In the Node 24 design, a presigned URL authorizes a bounded storage operation; it does not prove that the expected safe file arrived. Create a server-owned upload session with an object key, size limit, expiry, and expected checksum. On completion, inspect storage metadata, independently verify byte count and digest, run the content-validation pipeline in quarantine, and atomically mark metadata published only after success. Direct upload saves application bandwidth, but the pitfall is trusting a client “complete” callback or storage Content-Type as publication evidence.

read more File uploads
Was this clear?
52 How should a first backend separate transport, domain, and persistence responsibilities? Junior common reveal ▾ hide ▴

In the Node 24 baseline, the transport layer parses HTTP input, establishes identity, and maps deliberate results to statuses and headers. A domain function enforces business rules using typed commands, while a repository owns durable reads, writes, and transaction details. This separation lets rules run without a socket and keeps database shapes out of the public contract. The trade-off is a few adapters for a small service. The pitfall is a route that validates, mutates global memory, performs SQL, and invents error JSON all at once.

Was this clear?
53 Why does a failed backend response not prove that a write did not happen? Mid common reveal ▾ hide ▴

With Node 24, the database commit and delivery of an HTTP response are separate events. The service may commit an order, then lose the connection before the client receives success; a blind retry can create a duplicate. Define the commit point, make retryable operations use a stable idempotency key, and atomically store the operation result with the business effect. The trade-off is retention and conflict policy for keys. Keeping state only in process memory is another pitfall because restarts and multiple workers destroy that deduplication boundary.

Was this clear?
55 How does request-scoped batching prevent GraphQL N+1 reads without weakening authorization? Mid common reveal ▾ hide ▴

In the Node 24 execution model, sibling field resolvers can request related records independently, turning one list into N additional reads. A loader queues keys during the same execution turn, fetches them in one batch, and returns results in exactly the requested key order. Create it per request so cached data, identity, and tenant scope never leak between users. Authorization still belongs at the business-data boundary, not in field visibility alone. The pitfall is a process-global loader whose cache serves another principal’s object or grows without bound.

read more GraphQL
Was this clear?
56 How would you bound the cost of a GraphQL operation before executing it? Senior common reveal ▾ hide ▴

On the Node 24 server, parse and validate the operation, require finite pagination arguments, and calculate a budget from selected fields, nesting, and list cardinality before invoking resolvers. Persisted operations can reduce the accepted surface, but they do not make an expensive approved query cheap. Apply separate timeouts and downstream limits during execution, then record the normalized operation rather than raw sensitive variables. A simple depth limit is easy to operate but misses wide or multiplicative selections; a cost model is more accurate but requires maintenance as resolvers change.

read more GraphQL
Was this clear?
57 Why can a gRPC deadline leave a write with an unknown outcome? Senior common reveal ▾ hide ▴

With Go 1.27 and gRPC-Go 1.83.2, the client deadline bounds how long it waits and cancellation propagates through context.Context, but it cannot retract a commit that already happened. The server may persist a write just before the client receives DeadlineExceeded; retrying blindly can duplicate the effect. Propagate the deadline downstream, stop optional work promptly, and use a stable operation key for retryable writes. The trade-off is deduplication state, while the pitfall is treating a transport status as proof of the domain outcome.

read more gRPC
Was this clear?
58 What ownership and backpressure rules matter in a gRPC stream? Mid occasional reveal ▾ hide ▴

In gRPC-Go 1.83.2, stream sends and receives are ordered protocol operations tied to one call context; application code must not assume unlimited buffering or share a message that is still being mutated. Use bounded producer queues, stop producers when the context is cancelled, and give one component clear ownership of closing and result handling. Reuse long-lived client connections rather than dialing per message. The trade-off is limiting throughput bursts, but an unbounded queue merely moves backpressure into memory and can outlive a disconnected client.

read more gRPC
Was this clear?
59 How does registration order affect Hono middleware and routes? Mid common reveal ▾ hide ▴

Hono 4.13.5 builds an ordered route and middleware chain, so a middleware registered after a matching route does not retroactively protect that route. Mount authentication, request limits, and error policy before the route groups they should wrap, and test the final composed app with app.request(). A broad wildcard can also affect routes that follow it, making order part of the public behavior. The trade-off is less freedom to rearrange files; the pitfall is reviewing each handler in isolation while the deployed chain skips required policy.

read more Hono
Was this clear?
60 What can a Hono typed client guarantee, and where is runtime validation still required? Mid common reveal ▾ hide ▴

With Hono 4.13.5 and TypeScript 6, exported route types can make a cooperating client check procedure paths and TypeScript input or output shapes at build time. They do not validate bytes from an untyped caller, prevent a stale independently deployed client, or prove authorization. Validate request data at the server boundary and return deliberate status-specific responses; validate external responses when trust requires it. The trade-off is duplicated runtime schemas, but relying on inference alone lets casts, JSON, and version skew bypass every compile-time promise.

read more Hono
Was this clear?
62 Why should an HTTPX client be reused, and why must streaming responses be closed? Mid common reveal ▾ hide ▴

HTTPX 0.28.1 keeps connection pools, cookies, and shared configuration on Client or AsyncClient, so constructing one per request discards connection reuse and repeatedly pays setup cost. A streaming response owns a checked-out connection until its body is consumed or the response closes. Use context managers or a finally path, and scope the client to the service or application lifetime. The pitfall is returning an iterator while closing its client first, or abandoning responses until pool capacity is exhausted under load.

read more HTTPX
Was this clear?
63 How should HTTPX timeouts distinguish network phases and pool capacity? Senior common reveal ▾ hide ▴

HTTPX 0.28.1 separates connect, read, write, and pool timeouts. That makes a saturated local pool distinguishable from a slow connection or a peer that stops producing body bytes. Configure every phase from one end-to-end deadline and leave budget for parsing and retries; a read timeout is inactivity between chunks, not necessarily a total response duration. The pitfall is setting a generous single value and then layering retries, which multiplies latency. Record the failing phase so capacity problems are not misdiagnosed as remote network failures.

read more HTTPX
Was this clear?
67 Why is Ktor serialization not a complete input-validation boundary? Mid occasional reveal ▾ hide ▴

With Ktor 3.5.1 and Kotlin 2.4.10, content negotiation can decode JSON into @Serializable types and reject structural mismatches. It does not establish that an amount is positive, an identifier belongs to the authenticated tenant, or a state transition is allowed. Map transport data into a domain command, validate field and cross-field rules, then authorize the selected object before mutation. The trade-off is separate transport and domain models. Reusing one data class everywhere is shorter, but it exposes server-owned fields and confuses parsing success with business validity.

Was this clear?
71 How do Session and response lifetime affect connection reuse in Requests? Mid common reveal ▾ hide ▴

On Python 3.14, a Requests Session keeps connection pools and shared cookies or headers, so reuse it for a coherent client lifetime instead of constructing one per call. A streamed response holds its connection until the body is consumed or close() runs; use a with block and close on every error path. Shared mutable session state also needs an ownership policy under concurrency. The pitfall is reading only part of a download and abandoning the response, which eventually exhausts pool capacity and looks like a remote timeout.

read more Requests
Was this clear?
72 Why is a Requests timeout tuple not a complete end-to-end deadline? Senior common reveal ▾ hide ▴

On Python 3.14, timeout=(connect, read) bounds connection establishment and periods without incoming response data; it does not necessarily cap DNS, every redirect, retries, body processing, or the total wall-clock operation. Derive phase limits and retry count from one caller deadline, and stop when the remaining budget cannot support another attempt. The trade-off is more deadline plumbing. Omitting a timeout can wait indefinitely, while choosing a large value at each nested layer multiplies latency and hides which phase actually stalled.

read more Requests
Was this clear?
74 What must a REST API define for a safe partial-update contract? Senior occasional reveal ▾ hide ▴

In the Node 24 API, choose and advertise a patch media type whose semantics are explicit. JSON Merge Patch distinguishes an omitted member from a member set to null, while JSON Patch describes ordered operations; neither should be guessed from an arbitrary JSON object. Validate editable fields, authorize the target, and combine the patch with If-Match when concurrent edits matter. Return deliberate conflict and validation representations. The trade-off is client complexity; a vague PATCH handler often overwrites server-owned fields or loses updates while appearing conveniently flexible.

Was this clear?
86 Why is a tRPC router type not a language-neutral wire contract? Mid common reveal ▾ hide ▴

In the Node 24 tRPC model, the client imports the server router’s TypeScript type, so procedure paths and static input or output types flow through a shared build graph without code generation. Those types are erased at runtime and are not a standalone schema that Swift, Python, or an independently released consumer can implement. Keep runtime input validators and intentional output shapes. The trade-off is excellent monorepo ergonomics coupled to TypeScript releases; choose OpenAPI, GraphQL, or Protobuf when consumers need an independently versioned, language-neutral contract.

read more tRPC
Was this clear?
88 How should a URLSession client separate transport, HTTP, and decoding failures? Mid common reveal ▾ hide ▴

In Swift 6.3.3, URLSession.data(for:) can return bytes and a response for any HTTP status; a 404 is not a thrown transport error. First handle cancellation and URLError, then require an HTTPURLResponse, classify the documented status, and only decode the representation expected for that status. A 204 must not be forced through a success-body decoder, and an HTML gateway error is not the API’s JSON error model. The trade-off is more explicit result cases, but collapsing every failure into “decoding failed” destroys retry and user-message decisions.

read more URLSession
Was this clear?
89 How should cancellation and retries share one URLSession request budget? Senior common reveal ▾ hide ▴

With Swift 6.3.3 async URLSession APIs, cancellation should propagate from the owning task to the network task, but it cannot prove that a remote write did not commit. Retry only safe or idempotency-keyed operations, cap attempts, honor Retry-After, add jitter, and stop when the original deadline lacks budget for another try. Preserve CancellationError as cancellation rather than wrapping it as a generic network failure. The pitfall is independent retries in URLSession, repository, and UI layers: three attempts at each layer can multiply into twenty-seven requests.

read more URLSession
Was this clear?

Auth

10 questions
07 Why does successful authentication not prove that a request is authorized? Junior common reveal ▾ hide ▴

Authentication establishes a principal; authorization decides whether that principal may perform this action on this resource. A valid session for user A does not permit reading user B’s invoice. The handler or policy layer must compare the verified identity, requested action, tenant, and target object, using server-controlled data rather than caller-supplied ownership fields. I test missing credentials separately from valid credentials lacking permission, commonly producing 401 and 403 or a deliberate non-disclosing 404. Route-level role checks are not enough when access depends on the specific object identifier.

read more tRPC
Was this clear?
08 Why is a valid JWT signature insufficient for authentication? Mid common reveal ▾ hide ▴

A valid signature proves only that the bytes were protected by the key selected for verification and were not modified. The service must also pin an allowed algorithm and trusted issuer key set, then validate issuer, audience, token purpose, time claims, required claim types, and application state. A correctly signed token for another API or an ID token presented as an access token must still fail. After validation, I return a narrow normalized principal rather than the raw payload, so downstream code cannot accidentally treat an arbitrary private claim as permission.

Was this clear?
09 What trust-boundary difference separates HS256 from an asymmetric JWT signature? Mid common reveal ▾ hide ▴

HS256 uses one shared secret, so every service that can verify tokens can also mint them. Its verification boundary is therefore also an issuance boundary. With an asymmetric scheme, the issuer keeps the private signing key while services receive public verification keys, so verification does not grant signing power. That separation is useful, but not automatic safety: the verifier must choose the algorithm from trusted configuration, constrain kid to the issuer’s approved key set, cache rotation safely, and protect key material. The choice follows the system’s trust topology and operational key policy.

Was this clear?
10 How does refresh-token rotation detect replay, and what should happen after detection? Senior occasional reveal ▾ hide ▴

Each successful refresh transaction consumes the presented token and issues exactly one successor while retaining their token-family relationship. If an already consumed token appears again, either the legitimate client or a thief is replaying a copied credential, and the server cannot know which party now holds the valid successor. It should revoke the active family, record the security event, and require fresh authorization. The consume-and-issue step must be atomic so two concurrent uses cannot both succeed. Rotation provides detection and session control; short access-token lifetime alone does not provide immediate revocation.

Was this clear?
11 What attack does PKCE prevent in the OAuth authorization-code flow? Mid common reveal ▾ hide ▴

PKCE binds an authorization request to the client instance that started it. The client creates a high-entropy code_verifier, sends a derived code_challenge with the authorization request, and later presents the verifier when redeeming the code. An attacker who intercepts only the authorization code cannot exchange it without that verifier. PKCE does not authenticate the end user, replace exact redirect_uri checking, or remove the need for state to bind the browser response and resist CSRF. The authorization server must associate the challenge with the code and allow each code to be redeemed only once.

read more
Was this clear?
12 Why are a file extension and Content-Type insufficient upload validation? Mid occasional reveal ▾ hide ▴

Both are caller-controlled claims, so neither proves what the bytes contain or whether the content is safe. I first enforce request and streaming byte limits, generate a server-side storage key, and write into quarantine rather than a public path. Then I compare allowed extension, declared media type, detected signature, and format-specific parsing; high-risk content may also need malware scanning or transformation. Publication becomes a separate state transition after all checks pass. Downloads use a deliberate Content-Type and Content-Disposition, and user filenames remain metadata, never filesystem paths or executable public names.

read more File uploads
Was this clear?
48 How should an application safely serve a previously uploaded file? Mid common reveal ▾ hide ▴

For the Node 24 pipeline, store bytes under a server-generated opaque key and keep the original filename only as metadata. At retrieval, authorize the requested object, choose a trusted Content-Type, and set a sanitized Content-Disposition; active or uncertain content should download rather than execute in the application’s origin. Keep quarantine objects unreachable and make deletion cover both metadata and bytes. The trade-off is reduced inline preview convenience. A common pitfall is mapping a user filename directly to a public path, enabling collisions, traversal, or script execution.

read more File uploads
Was this clear?
69 How should Laravel route model binding and authorization work together in a nested route? Mid common reveal ▾ hide ▴

Laravel 13.30.1 can bind route parameters to Eloquent models, and scoped binding can constrain a child through its parent relationship. That prevents /teams/A/projects/B from resolving an unrelated project, but model resolution still is not permission. Apply a policy or explicit authorization check using the authenticated principal and requested action before returning or mutating the object. The trade-off is deliberate 403 versus non-disclosing 404 behavior. A pitfall is accepting a bound model as authorized merely because its identifier and parent path were valid.

read more Laravel
Was this clear?
73 What checks are required before retrying a request to a user-supplied URL? Senior occasional reveal ▾ hide ▴

With Requests on Python 3.14, first constrain the URL scheme, hostname, port, resolved addresses, and every redirect so the client cannot reach loopback, private, link-local, or metadata services. Then retry only transient failures for an operation whose effect is safe to replay, using a bounded count, backoff, jitter, and Retry-After within the remaining deadline. Revalidate each redirect because the destination can change. The trade-off is rejecting some flexible integrations; blindly mounting retries on every method turns SSRF probes and uncertain POST outcomes into repeated attacks or duplicate writes.

read more Requests
Was this clear?
87 What must a tRPC server consider when several procedures share one batched request? Senior occasional reveal ▾ hide ▴

On Node 24, a batched tRPC transport can execute several procedure calls under one HTTP request and context creation. Derive identity once from verified credentials, but authorize every procedure and selected object independently; one successful call must not grant another. Bound batch size and total work, isolate per-call errors in the documented response shape, and avoid request-scoped mutable state that creates ordering dependence. Batching reduces transport overhead, but it can amplify expensive work and complicate transaction semantics, so never imply that the whole batch is atomic unless the server explicitly implements that contract.

read more tRPC
Was this clear?

Databases

10 questions
13 What problem does normalization solve, and when is denormalization justified? Junior common reveal ▾ hide ▴

Normalization makes each fact have a clear owner, reducing duplicate data and the insert, update, and delete anomalies that follow from it. For example, department name belongs in a department table rather than being copied into every employee row. Denormalization is justified only for a measured access pattern whose join, aggregation, or availability cost matters. The duplicate then needs an explicit maintenance mechanism, such as a transaction, change stream, or rebuildable projection, plus a consistency expectation. I keep constraints on the authoritative model and verify that the derived copy can be repaired after partial failure.

read more
Was this clear?
14 How do you size a database connection pool across several service instances? Mid common reveal ▾ hide ▴

I start from the database’s total sustainable connection and query capacity, then reserve headroom and divide the remaining budget across every application instance, worker, migration job, and deployment overlap. Per-instance pool size multiplied by maximum simultaneous instances must stay within that budget. I load-test the actual transaction duration and watch acquisition wait, active connections, query latency, and database saturation. A larger pool is not a universal fix: slow queries, leaked connections, or transactions held during remote calls can make it worse. Pools also need bounded acquisition time and guaranteed return through structured cleanup.

read more
Was this clear?
15 How do you choose column order for a composite B-tree index? Mid common reveal ▾ hide ▴

I design the index from concrete query predicates and ordering, not from a rule that the most selective column always comes first. Equality predicates usually form the leading prefix, followed by columns needed for sorting and then range filtering, subject to the database’s actual planner behavior. An index on (tenant_id, status, created_at) naturally supports queries beginning with tenant_id, but not every query on status alone. I confirm with EXPLAIN and production-like data, then account for write amplification, storage, and whether included columns make a frequent query covering. Unused overlapping indexes should be removed deliberately.

read more
Was this clear?
16 What is the difference between EXPLAIN and EXPLAIN ANALYZE in PostgreSQL? Mid common reveal ▾ hide ▴

EXPLAIN shows the optimizer’s estimated plan and costs without running the statement. EXPLAIN ANALYZE executes it and adds actual row counts and timing, while BUFFERS can expose cache and I/O behavior. The gap between estimated and actual rows often points to stale statistics, correlated predicates, or skew and can explain a poor join choice. The boundary is operational safety: ANALYZE really performs writes and can run an expensive query. I use a transaction that can be rolled back for suitable mutations, production-like data, and representative parameters, then compare estimates, actual loops, buffers, and total latency.

read more
Was this clear?
17 When should a MongoDB schema embed data rather than reference it? Mid occasional reveal ▾ hide ▴

Embed when the child is bounded, owned by the parent, and normally read or updated with it. This gives one document read and can make related changes atomic at the document boundary. Reference when the related data has an independent lifecycle, is shared by many parents, grows without a practical bound, or is queried on its own. The decision follows access patterns and consistency needs, not whether the relationship sounds relational. A product snapshot inside an order may be intentional historical data, while a live customer profile should usually be referenced. I also enforce document-size and array-growth limits.

read more
Was this clear?
18 What makes a good database shard key, and why is the choice hard to reverse? Senior occasional reveal ▾ hide ▴

A good shard key has high cardinality, distributes sustained load evenly, appears in common routing predicates, and rarely changes. It should also preserve useful locality without creating a hot shard; a monotonically increasing timestamp can concentrate current writes, while pure hashing can scatter range queries. The key becomes part of placement, indexes, APIs, and operational tooling, so changing it means moving live data while writes continue. Before sharding, I test representative traffic, quantify scatter-gather queries and tenant skew, define cross-shard transaction policy, and design resumable rebalancing with correctness checks and rollback limits.

read more
Was this clear?
40 How would you diagnose and fix an N+1 query in a Django view? Mid common reveal ▾ hide ▴

In Django 6.0.8, a QuerySet is lazy, so iterating results and then touching an uncached relation can issue one extra query per row, often from a template. Capture query counts around the complete view with representative data, then use select_related() for single-valued joins or prefetch_related() for many-valued relations. Assert a bounded query count so later template edits cannot regress it. The pitfall is prefetching every relation: unused prefetches add queries and memory, so optimize the access path actually rendered.

read more Django
Was this clear?
42 Why should a Django application enforce an invariant in both validation and the database? Mid common reveal ▾ hide ▴

Django 6.0.8 forms or serializers provide friendly parsing and errors for one request path, but scripts, admin actions, bulk writes, and concurrent requests can bypass that path. Put durable rules in foreign keys, UniqueConstraint, CheckConstraint, and transactions, while keeping boundary validation for usable feedback. A uniqueness check followed by save() still races, so catch the database error that can win. The trade-off is mapping lower-level failures cleanly; relying only on full_clean() or application checks leaves other writers able to corrupt the invariant.

read more Django
Was this clear?
70 How would you protect and test a multi-write invariant in Laravel? Mid common reveal ▾ hide ▴

In Laravel 13.30.1, put related writes inside one database transaction and encode durable uniqueness or relational rules with database constraints. Request validation supplies useful client errors but cannot stop another concurrent transaction or a queue worker from violating an application-only check. Catch expected constraint conflicts and map them deliberately, while allowing programming failures to reach centralized handling. Test the complete request slice with the real database behavior, including rollback and a competing write. The trade-off is slower integration tests; mocking Eloquent cannot reproduce isolation or constraint races.

read more Laravel
Was this clear?
76 Why is a Rails model validation insufficient for a concurrent data invariant? Senior common reveal ▾ hide ▴

In Rails 8.1.3.1, validations run application queries before persistence and provide useful object errors, but another transaction can pass the same check before either commits. Enforce durable uniqueness and relationships with database indexes, constraints, and a transaction, then catch the expected database conflict and map it deliberately. Avoid callbacks that trigger unrelated external effects inside the transaction. The trade-off is database-specific failure handling; relying only on validates_uniqueness_of creates a race, while relying only on a constraint gives users a poor error without boundary validation.

read more Ruby on Rails
Was this clear?

Caching and queues

6 questions
19 How does cache-aside work, and where can stale data appear? Junior common reveal ▾ hide ▴

On a read, the application checks the cache, loads the source of truth after a miss, and stores the result with a bounded TTL. On a write, it commits the database change and then invalidates the affected cache keys. Staleness can appear between those steps, when invalidation is lost, when another reader repopulates an old value during the race, or until TTL expires. The database remains authoritative. I define acceptable stale time, make invalidation observable and retryable, include tenant and query dimensions in cache keys, and use versioned keys or change-driven invalidation when the risk requires it.

read more
Was this clear?
20 How do you prevent a cache stampede when a hot key expires? Mid common reveal ▾ hide ▴

I ensure that one expiration does not turn every waiter into a database request. Common controls are request coalescing or single-flight per key, a short distributed lease for regeneration, stale-while-revalidate, proactive refresh, and randomized TTLs so related keys do not expire together. Each has a boundary: a lost lease must expire, stale data needs a stated freshness limit, and the regeneration path needs its own timeout and capacity guard. I also cache a bounded negative result when repeated misses are legitimate. Metrics should distinguish cache misses, coalesced waiters, regeneration latency, stale serves, and source load.

read more
Was this clear?
21 What is the difference between key expiration and eviction in Redis? Mid occasional reveal ▾ hide ▴

Expiration is a per-key lifetime chosen by the application; after the TTL, the key should no longer be treated as present. Eviction is a server response to maxmemory pressure, governed by the configured policy, and it may remove a still-valid key or reject writes under noeviction. Therefore a cache hit is never a durability guarantee, and an application must tolerate an early miss. I separate disposable cache data from durable state, choose the policy from key importance and access patterns, monitor memory and evictions, and test behavior when a write is rejected. Persistence settings do not turn eviction into application-level correctness.

read more
Was this clear?
22 How do you make an at-least-once message consumer safe? Senior common reveal ▾ hide ▴

I assume the same message can arrive more than once, including after the side effect committed but before its acknowledgment reached the broker. The message carries a stable event or operation identifier. The consumer records that identifier and the business change in one atomic boundary where possible; a duplicate then returns the prior outcome without repeating the effect. It acknowledges only after durable success. Transient failures are retried with bounded backoff, while permanent failures move to a dead-letter path with reason and replay tooling. Ordering, retry count, and poison-message policy are explicit rather than inferred from the queue product.

read more
Was this clear?
23 When would you choose Core NATS instead of JetStream? Mid rare reveal ▾ hide ▴

I choose Core NATS when low-latency live delivery matters and losing a message while no subscriber is available is acceptable. Core publish-subscribe and queue groups do not provide the durable consumer state needed for later replay. I choose JetStream when messages must be stored, acknowledged, redelivered, replayed, or consumed under an explicit retention policy. JetStream still does not remove application work: at-least-once delivery requires idempotent effects, acknowledgment timing must follow durable success, and consumers need lag and pending limits. The decision follows the loss and recovery contract, not throughput claims alone.

read more
Was this clear?
24 Why must Temporal workflow code be deterministic while activity code need not be? Senior occasional reveal ▾ hide ▴

Temporal reconstructs workflow state by replaying recorded history through the workflow code. For the same history, that code must emit the same sequence of commands; direct wall-clock reads, random values, network I/O, or incompatible code changes can make replay diverge. Temporal supplies replay-safe time, randomness, timers, and versioning mechanisms for orchestration decisions. Activities are the boundary for database calls and other side effects, so they may be nondeterministic and are recorded as results in history. Because an activity can be retried after an unknown outcome, its external effect still needs idempotency and explicit timeouts.

read more
Was this clear?

Testing

8 questions
25 How do you choose between unit, integration, and end-to-end backend tests? Junior common reveal ▾ hide ▴

I choose the smallest boundary that can observe the failure I care about. Pure domain rules fit fast unit tests. Serialization, routing, database constraints, and message adapters need integration tests with those real components. A few critical workflows need end-to-end or deployed smoke tests because TLS, proxies, packaging, and service composition exist only there. The test pyramid is a cost heuristic, not a required percentage. For each risk I state what the test proves and what remains outside it, avoid mocking the behavior under test, and keep failures diagnosable with controlled data, clocks, and dependencies.

read more
Was this clear?
26 What does an API contract test prove, and what does it leave unproven? Senior occasional reveal ▾ hide ▴

A provider contract test proves that an observable request and response conform to a published interface; a consumer contract proves that a provider still supports a concrete consumer interaction. Both can catch serialization, status, header, and schema drift at the boundary. Neither proves that two internal writes committed atomically, that every authorization decision is correct, or that an omitted consumer scenario is safe. I pair them with domain invariant and policy tests, retain old contracts for compatibility checks, and report failures by evidence type. Calling every layer a contract test hides ownership and creates false confidence.

Was this clear?
27 Why is directly calling a FastAPI path function not enough to test an endpoint? Mid common reveal ▾ hide ▴

A direct call exercises ordinary Python but bypasses route matching, parameter-source parsing, dependency resolution, exception conversion, response-model filtering, and serialization. It can therefore pass while the public endpoint is broken. At least one layer should send an HTTP request through an ASGI test client and assert status, relevant headers, and the public body. I cover malformed input, missing authentication, forbidden object access, conflicts, and cleanup after dependency or serialization failure. If lifespan initializes a pool, the client must run as a context manager so startup and shutdown execute too.

read more FastAPI
Was this clear?
28 What is the practical difference between an MVC slice, SpringBootTest, and a random-port test? Mid common reveal ▾ hide ▴

An MVC slice loads a filtered web layer and is useful for mapping, binding, validation, and controller behavior, but it excludes most production wiring. SpringBootTest loads the full application context; with MockMvc it still uses a mocked servlet request path and does not open a server by default. A random-port test starts the embedded server and uses real sockets, covering more HTTP-server behavior at higher cost. None proves external ingress, TLS, or packaging. I use each only for risks inside its boundary and retain at least one test that starts the same primary configuration and profiles as deployment.

read more Spring Boot
Was this clear?
29 What does a database branch improve in CI, and what risks remain? Mid rare reveal ▾ hide ▴

A branch gives a test or preview environment an isolated database state without every suite sharing one mutable schema and dataset. It is useful for migration rehearsal, concurrent pull requests, and reproducible fixtures. It does not automatically make the data safe or the test deterministic. A production-derived branch must be sanitized before untrusted preview code can access it; branch creation point, schema version, seeds, credentials, expiry, and cleanup must be controlled. I still test migration locks and realistic data volume separately, because copy-on-write isolation does not reproduce every production load or operational failure.

read more
Was this clear?
30 What should an in-process Elysia test cover, and why keep real-network tests? Mid rare reveal ▾ hide ▴

Calling app.handle with a Web Request or using an in-process Treaty client should cover routing, runtime validation, lifecycle hooks, short-circuit behavior, response schemas, and error mapping without opening a port. The application module must export the fully composed app without calling listen so import has no deployment side effect. This test still cannot observe DNS, sockets, TLS, reverse-proxy rewriting, base URLs, or which service version a public endpoint actually runs. I keep a smaller real-network suite for those concerns and test the candidate deployment when type compatibility could drift from deployed topology.

read more Elysia
Was this clear?
54 Which tests should a small backend add before it becomes a production service? Junior occasional reveal ▾ hide ▴

For the Node 24 service, use pure tests for domain invariants, repository tests against the real database behavior, and HTTP tests that exercise routing, parsing, authentication, serialization, and error mapping together. Add a small deployed-path check for proxy headers, limits, shutdown, and other infrastructure behavior. Each layer observes a different boundary; mocking every dependency in one route test proves only wiring assumptions. The trade-off is slower integration coverage, so keep fixtures isolated and targeted rather than replacing fast domain tests with an all-purpose end-to-end suite.

Was this clear?
64 When should you replace HTTPX transport in a test, and what does that test not prove? Mid occasional reveal ▾ hide ▴

In HTTPX 0.28.1, a custom or mock transport can inspect built requests and return deterministic responses without opening a socket; ASGITransport can exercise an in-process ASGI app. This is ideal for status mapping, decoding, retry decisions, and malformed bodies. It does not prove DNS, TLS, proxy behavior, HTTP/2 negotiation, real timeouts, or connection pooling. Keep a small real-network integration suite for those boundaries. The trade-off is slower infrastructure tests, while the pitfall is letting a friendly mock accept requests a real server or intermediary would reject.

read more HTTPX
Was this clear?

Deployment

30 questions
31 When would you choose Layer 4 instead of Layer 7 load balancing? Junior common reveal ▾ hide ▴

Layer 4 routes TCP or UDP connections using transport addresses and ports, so it suits non-HTTP protocols, TLS pass-through, or a simple high-throughput connection boundary. Layer 7 understands an application protocol such as HTTP and can route by host, path, header, or cookie, terminate TLS, and apply HTTP-aware policy. That flexibility costs parsing and makes the proxy part of application semantics. I choose from required routing and observability, not a blanket performance claim. In both cases I define active and passive health signals, drain connections during removal, and test behavior when an endpoint becomes slow rather than fully dead.

read more
Was this clear?
32 How should a backend trust client-address and scheme headers from Nginx? Mid common reveal ▾ hide ▴

It should trust forwarded headers only from known proxy hops that overwrite or sanitize them. Public clients can send X-Forwarded-For, X-Forwarded-Proto, or identity-looking headers themselves, so accepting those values from any peer enables spoofing. Nginx should append or replace fields according to a documented hop model, and the application should configure the exact trusted proxy ranges and parse only the expected number of hops. Direct access to the backend must be blocked or treated as untrusted. I test both the normal proxy path and a forged-header request that bypasses or reaches the first trusted hop.

read more
Was this clear?
33 How do Envoy circuit breaking and outlier detection protect different boundaries? Senior rare reveal ▾ hide ▴

Circuit breaking limits aggregate pressure on an upstream cluster, such as concurrent connections, pending requests, active requests, or retries. When a limit is reached, Envoy sheds work instead of allowing queues and resource use to grow without bound. Outlier detection evaluates individual endpoints and can temporarily eject one that repeatedly fails relative to policy. They complement health checks but do not prove business correctness. Limits need per-priority capacity budgets, bounded retries, and overload metrics; ejection needs enough traffic evidence, a maximum ejection percentage, and recovery behavior so a noisy signal cannot remove every healthy-capable endpoint.

read more
Was this clear?
34 Why must a serverless event handler be idempotent? Mid common reveal ▾ hide ▴

Event sources may redeliver after a timeout, worker crash, partial batch failure, or lost acknowledgment, so one logical event can invoke the handler more than once. The handler uses the source event ID or a domain operation ID as a deduplication key and atomically records durable progress with each side effect where possible. It reports only failed batch items when the platform supports that contract, rather than replaying successful records unnecessarily. Initialization outside the handler may reuse clients in a warm environment, but that memory is an optimization, not durable state. Retry limits, dead-letter handling, and observability remain explicit.

read more
Was this clear?
35 Which backend work belongs in an edge function, and what should stay regional? Mid occasional reveal ▾ hide ▴

Edge functions suit short request-bound work that benefits from proximity, such as routing, redirects, header normalization, lightweight authentication checks, and cache decisions. Stateful transactions, long CPU work, large dependencies, unrestricted Node APIs, and repeated calls to a distant primary database usually belong in a regional service. Moving only compute to the edge does not reduce latency if every request still crosses regions for data. I verify each platform’s runtime, CPU, memory, request-size, and subrequest limits, keep secrets and logs within policy, and design a clear fallback when an edge dependency or region is unavailable.

read more
Was this clear?
36 What capability difference matters most between WSGI and ASGI? Senior common reveal ▾ hide ▴

WSGI is a synchronous HTTP call interface: the server supplies an environ and start_response, then pulls bytes from an iterable. ASGI is an asynchronous event interface with a scope plus receive and send, supporting HTTP streaming, disconnect events, WebSockets, and lifespan. Declaring async does not make blocking database or file calls nonblocking; every dependency and middleware boundary must cooperate. A WSGI-to-ASGI adapter can run synchronous work in a thread pool, but it cannot add native WebSocket semantics and can exhaust that pool. I choose by required capability and test cancellation, backpressure, cleanup, and per-worker resource capacity.

read more WSGI and ASGI
Was this clear?
41 Why can an async Django view still block, and where should transaction-heavy work run? Senior occasional reveal ▾ hide ▴

Under Django 6.0.8 on Python 3.14, async def changes the view call boundary but does not make synchronous middleware, file access, clients, or ORM calls nonblocking. Use supported async ORM methods for genuinely asynchronous operations and the documented sync adapter for sync-only dependencies. Django 6.0 does not support transactions in async mode, so transaction-heavy units should remain synchronous and be called through the proper boundary. The trade-off is context-switch and thread capacity; load-test the deployed ASGI stack rather than counting async functions.

read more Django
Was this clear?
49 Why is an application factory useful in Flask, and what setup must finish inside it? Mid common reveal ▾ hide ▴

In Flask 3.1.3 on Python 3.14, a factory creates a configured application instance, initializes extensions, and registers blueprints, middleware, and error handlers before a server handles requests. This supports separate test configurations without relying on a mutable module singleton. Setup after the first request is unsafe because workers can observe different route maps or policies. The trade-off is more explicit dependency wiring. Database migrations and one-time data jobs should remain deployment steps, not factory side effects that repeat for every worker or test instance.

read more Flask
Was this clear?
50 Why should Flask request-context objects not escape into background work? Mid common reveal ▾ hide ▴

Flask 3.1.3 exposes request, session, and g through context-local proxies that resolve only while the owning request context is active. A background thread or queued job that reads them later may fail or, worse, assume the wrong lifetime. Copy only the validated scalar data and identifiers the job needs, then pass those values explicitly; non-request code can open an application context when it genuinely needs current_app. The trade-off is more handoff code, but copying the whole request also leaks credentials and couples durable work to transient state.

read more Flask
Was this clear?
51 When does an async Flask view help, and when is Flask the wrong execution model? Senior occasional reveal ▾ hide ▴

In Flask 3.1.3, an async view can await supported I/O concurrently within one WSGI request when the async extra is installed, but each request still occupies a worker and spawned tasks are cancelled when that view’s event loop ends. It does not provide native WebSocket or long-lived ASGI semantics, and synchronous dependencies still block. Use a task queue for durable background work or an ASGI framework for long-lived connections. The pitfall is measuring coroutine syntax instead of worker capacity, cancellation, and dependency behavior.

read more Flask
Was this clear?
61 How would you keep a Hono application portable across JavaScript runtimes? Senior occasional reveal ▾ hide ▴

Hono 4.13.5 centers handlers on Web-standard Request, Response, and fetch semantics, but Node 24 bindings, filesystem APIs, environment access, and server startup remain adapter-specific. Keep those capabilities behind typed interfaces, pass bindings through context, and place the deployment adapter outside route and domain code. Test the core with app.request(), then run a smaller suite on the real adapter. Portability costs an abstraction layer; importing a runtime-only global deep inside a handler silently turns a portable type graph into one-platform code.

read more Hono
Was this clear?
65 Why does suspend not make a blocking Kotlin backend call nonblocking? Senior common reveal ▾ hide ▴

In Kotlin 2.4.10 with Ktor 3.5.1, suspend lets a coroutine pause only when the called operation cooperates. A blocking JDBC driver, file API, or legacy HTTP client still occupies its thread and can starve Ktor’s execution capacity. Prefer nonblocking libraries, or isolate unavoidable blocking work on a bounded dispatcher sized from downstream capacity. Preserve the request deadline across that hop. The pitfall is using an unbounded pool, which hides blocking temporarily while creating uncontrolled queues, connections, and shutdown behavior.

Was this clear?
66 How should structured concurrency shape side effects in a Kotlin request? Senior common reveal ▾ hide ▴

Kotlin 2.4.10 ties child coroutines to an owning scope, so request cancellation and failures can propagate and completion can be awaited before returning. Use the Ktor request scope for required work and a durable job handoff for effects that must survive the response; do not launch ownerless GlobalScope work. Cancellation is cooperative and does not roll back an already committed database write, so define the commit point and idempotency policy. The trade-off is explicit lifecycle design, but detached work otherwise loses errors and orderly shutdown.

Was this clear?
68 Why do Laravel service-container binding lifetimes matter in long-running workers? Senior occasional reveal ▾ hide ▴

In Laravel 13.30.1 on PHP 8.3.33, singleton bindings live for the container lifetime, which can exceed one request in long-running HTTP or queue workers. Storing a request, authenticated user, tenant, or mutable accumulator in such a service can leak state into later work. Use request-scoped bindings or pass request data explicitly, and reset framework-supported state between jobs. Long-lived clients may be reusable when they contain no request data. The trade-off is lifecycle bookkeeping; code that was harmless under fresh-process PHP can become a cross-request correctness or privacy bug.

read more Laravel
Was this clear?
75 How do Rails conventions affect autoloading and application boundaries? Mid common reveal ▾ hide ▴

Rails 8.1.3.1 on Ruby 4.0.6 uses naming and directory conventions so constants, routes, controllers, models, jobs, and tests can be connected without repeated configuration. That productivity depends on treating filenames and constant paths as a contract; mismatches can load differently in development and eager-loaded production. Keep controllers as HTTP adapters and give domain or query objects clear names rather than hiding work in callbacks. The trade-off is less arbitrary structure, while bypassing conventions creates custom boot logic and environment-specific failures that the framework can no longer diagnose well.

read more Ruby on Rails
Was this clear?
77 How would you deploy a breaking database shape change safely in Rails? Senior occasional reveal ▾ hide ▴

With Rails 8.1.3.1, use an expand-and-contract migration across releases: add the new nullable column or table first, deploy code that can read old and new shapes and writes the transition state, backfill in bounded resumable batches, then enforce constraints and remove the old shape only after every process is compatible. Test rollback and long-running jobs too. The trade-off is temporary duplication. Renaming or dropping a column in one deploy can break old web workers, queued jobs, or console tasks still running the previous code.

read more Ruby on Rails
Was this clear?
78 Why must a Rust async backend isolate blocking work? Senior common reveal ▾ hide ▴

In Rust 1.98, an async future makes progress only when polled and must yield cooperatively. A blocking database driver, filesystem call, or CPU-heavy loop on a Tokio worker prevents unrelated futures on that worker from running. Prefer asynchronous dependencies; otherwise move bounded blocking work to spawn_blocking or a dedicated capacity-limited service and propagate deadlines. The trade-off is scheduling and handoff overhead. The pitfall is treating async fn as proof of nonblocking behavior, then fixing starvation with an unbounded task queue that shifts overload into memory.

Was this clear?
79 Why does dropping a Rust request future not roll back its side effects? Senior common reveal ▾ hide ▴

With Rust 1.98 async execution, timeout or disconnect may drop the request future, running destructors for owned values, but an already committed transaction or accepted remote call remains real. Some blocking work can continue even after its awaiting future is cancelled. Put transactions behind explicit owners, define the commit point, and use idempotency keys for retryable writes. Cleanup should be safe if cancellation occurs at any await. The trade-off is more state modeling; assuming RAII reverses external effects confuses memory cleanup with distributed transaction semantics.

Was this clear?
80 How should a Rust backend connect shared state, backpressure, and graceful shutdown? Mid occasional reveal ▾ hide ▴

In Rust 1.98, put immutable configuration and thread-safe clients in explicit application state, then size pools, semaphores, and bounded queues from downstream capacity. When shutdown begins, stop admission, signal owned tasks, drain only within a deadline, and close resources in dependency order. Axum extractors make ownership visible, but Arc proves shared ownership, not that inner mutation or business ordering is safe. The trade-off is shedding excess work with 429 or 503 responses; an unbounded channel postpones rejection until memory and shutdown time are exhausted.

Was this clear?
81 Why should a Scala backend run effects at one owned boundary? Senior common reveal ▾ hide ▴

In Scala 3.9.0 with Cats Effect 3.7.1, IO describes an effect; constructing it does not execute the work. The application runtime should run the top-level effect, while routes and services compose values and acquire clients, pools, and servers through Resource. This gives release actions an owner on success, failure, and cancellation. The trade-off is explicit effect types in APIs. Calling unsafe runners inside business code or creating ownerless Futures fragments lifecycle control and can leak resources or hide failures during shutdown.

Was this clear?
82 How should an http4s service handle blocking JDBC or filesystem work? Senior common reveal ▾ hide ▴

With Cats Effect 3.7.1 and http4s 0.23.36, wrapping a blocking call in ordinary IO does not make it nonblocking. Mark it with the blocking boundary so the runtime can protect compute threads, and separately bound concurrency according to database or filesystem capacity. Propagate cancellation and deadlines, remembering that an underlying blocking call may not stop immediately. The trade-off is extra context switches. An unbounded blocking region prevents compute starvation only superficially because it can still exhaust connections, threads, queues, and graceful-shutdown time.

Was this clear?
83 How should cancellation interact with a commit boundary in Cats Effect? Senior occasional reveal ▾ hide ▴

In Cats Effect 3.7.1, cancellation is cooperative and finalizers release owned resources, but cancellation cannot undo an external effect that already committed. Keep the cancelable preparation phase separate from the smallest necessary uncancelable commit region, then restore cancellation around later work. If the caller may retry after an unknown outcome, use a stable operation key and queryable result. The trade-off is a brief period that cannot be interrupted; making an entire request uncancelable instead wastes capacity and delays shutdown, while making the commit interruptible can leave ambiguous partial state.

Was this clear?
84 How does Spring Boot auto-configuration decide when to back off? Mid common reveal ▾ hide ▴

Spring Boot 4.1.1 evaluates auto-configuration conditions against the classpath, environment, application type, and beans already defined. A typical configuration supplies a default bean only when the required classes exist and the application has not provided its own bean. This back-off lets explicit application policy win. Diagnose surprises with the condition evaluation report rather than adding random exclusions. The trade-off is startup behavior that depends on configuration state; broad component scanning or an accidental dependency can activate beans, while defining one replacement can disable a useful default chain.

read more Spring Boot
Was this clear?
85 How should a Spring Boot service validate configuration without exposing secrets operationally? Senior occasional reveal ▾ hide ▴

In Spring Boot 4.1.1, bind related settings into typed @ConfigurationProperties, add validation constraints, and fail startup when required values are missing or malformed. Keep credentials in an external secret source and avoid logging the bound object. Actuator health and configuration endpoints need explicit exposure, authorization, and sanitization; being operational metadata does not make them public. The trade-off is stricter deployment coordination. Scattered @Value strings defer errors and obscure ownership, while exposing every Actuator endpoint can reveal environment values, bean names, or infrastructure details.

read more Spring Boot
Was this clear?
90 What state must survive when URLSession performs a background transfer? Senior occasional reveal ▾ hide ▴

In Swift 6.3.3, a background session hands file-based transfers to a system process, so the app may terminate and later reconnect through a stable, unique configuration identifier. Persist the task description, business identifier, destination, and state transition; in-memory closures and progress observers are not restoration state. Move a completed download from its temporary URL promptly and finish background events only after durable handling. The trade-off is a more complex state machine. Generating a new session identifier at every launch loses ownership of existing transfers and their callbacks.

read more URLSession
Was this clear?
91 How should an ASGI application handle streaming and client disconnects? Senior common reveal ▾ hide ▴

Under Python 3.14 ASGI semantics, send http.response.start once, follow it with ordered body events, and set more_body true only when another chunk will follow. A disconnect is racy: send() may raise before a later receive() reports http.disconnect, so cleanup must tolerate either order and run once. Bound request accumulation by looping over more_body rather than calling receive() once. The trade-off is explicit state-machine code; buffering everything is simpler but defeats backpressure and can turn an untrusted stream into unbounded memory use.

read more WSGI and ASGI
Was this clear?
92 What belongs in ASGI lifespan, and what cannot a WSGI adapter provide? Mid occasional reveal ▾ hide ▴

In Python 3.14 deployments, ASGI lifespan owns event-loop-local pools and clients: create them during startup, expose references through lifespan state, and close them during shutdown. A multiworker server runs one cycle per event loop, so total connection capacity multiplies by worker count. A WSGI-to-ASGI adapter can execute synchronous HTTP calls in a thread pool, but it cannot add native WebSockets, async request streaming, or immediate cancellation of blocking work. The trade-off is a staged migration; confusing adaptation with capability upgrades can exhaust threads and mis-scope resources.

read more WSGI and ASGI
Was this clear?
93 What is the minimal WSGI application and response contract? Mid common reveal ▾ hide ▴

Under Python 3.14 and PEP 3333, the server calls application(environ, start_response). The application supplies a status string and response-header list through start_response, then returns an iterable of bytes; text must be encoded before its byte length is calculated. Hop-by-hop headers remain the server’s responsibility. A generator may delay execution until iteration, but headers must arrive before the first body chunk. The pitfall is returning str or guessing Content-Length from characters; run boundary tests through wsgiref.validate to catch protocol violations.

read more WSGI
Was this clear?
94 What must WSGI middleware preserve when wrapping a streaming response? Senior common reveal ▾ hide ▴

In Python 3.14 WSGI, transparent middleware must preserve chunk order, repeated headers, the optional exc_info argument to start_response, and the downstream iterable’s close() lifecycle. Returning the original iterable is safest when the body is unchanged; a transforming wrapper owns forwarding cleanup in normal, exception, and early-disconnect paths. Calling list(result) just to log status buffers the stream and changes resource timing. The trade-off is more careful wrapper code, while losing close() can leak generator-owned files or transactions that tests with short lists never expose.

read more WSGI
Was this clear?
95 How should a WSGI application handle request bodies and server concurrency? Mid occasional reveal ▾ hide ▴

Under Python 3.14 WSGI, wsgi.input is a binary stream, not a parsed body. Validate missing, invalid, and excessive CONTENT_LENGTH, enforce an endpoint byte limit, then read only the permitted amount before decoding. Separately, wsgi.multithread and wsgi.multiprocess describe how the server may call the application; synchronous does not mean single-threaded. The trade-off is explicit limits and process-aware state. An unbounded read() can block or exhaust memory, while mutable globals can race between threads or diverge across worker processes.

read more WSGI
Was this clear?