HTHyperTransformer AI

Study cards › Backend Engineering

Backend EngineeringInterview questions and answers

← Topics1 / 100
1 / 100 viewed
Question

What is Node.js?

Answer

Node.js is a JavaScript runtime built on Chrome's V8 engine that runs JS outside the browser, typically on servers. It uses a single-threaded event loop with non-blocking I/O — perfect for handling thousands of concurrent connections doing I/O-bound work like APIs, real-time chat, or proxying.

Question

What is Express.js?

Answer

Express is a minimal, unopinionated Node.js web framework. It provides routing, middleware composition, and helpers around the raw HTTP module — but it stays out of your way about structure. Most Node tutorials use it because it's small enough to learn in an hour and flexible enough for big apps.

Question

What is NestJS?

Answer

NestJS is an opinionated Node.js framework built with TypeScript and inspired by Angular and Spring. It gives you dependency injection, decorators, modules, guards, interceptors, and a CLI — ideal for large teams that want strict structure. Comes with first-class support for REST, GraphQL, microservices, and WebSockets.

Question

What is middleware?

Answer

Middleware is a function with access to (req, res, next) that runs before or after route handlers. Each one can read/modify req or res, then call next() to continue. Express composes them in order — typical examples: body parsing, authentication, logging, rate limiting, and error handling.

Question

How does Node's event loop work?

Answer

Node's event loop cycles through phases: timers (setTimeout), pending callbacks, poll (I/O), check (setImmediate), and close events. Between every phase, microtasks (promises, process.nextTick) drain. Knowing this order helps you predict ordering of callbacks and avoid blocking the loop.

Question

What is libuv?

Answer

libuv is the C library that powers Node's async I/O. It manages the event loop, the thread pool used for file system and DNS operations, and abstractions over OS-level networking. Node's single-threaded feel comes from libuv handing the heavy lifting to OS primitives behind the scenes.

Question

What is the cluster module?

Answer

cluster lets you fork multiple Node.js processes that share a server port, taking advantage of multi-core CPUs in an otherwise single-threaded runtime. The master forks workers; the OS round-robins incoming connections. Most modern setups use PM2 or container orchestration (k8s) instead of raw cluster.

Question

What are worker threads in Node?

Answer

Worker threads are true OS threads designed for CPU-bound work (image processing, parsing, encryption). They run separately from the main event loop and communicate via message passing. Don't confuse them with the cluster module — workers do real parallel computation; cluster runs separate event loops.

Question

How do you handle authentication in Node?

Answer

Two main patterns: stateless JWT (token in Authorization header, validated each request) and session cookies backed by a store like Redis. Use a battle-tested library — Passport, Lucia, or jose for JWT. Never roll your own crypto, and always set HTTP-only Secure cookies for browser clients.

Question

What is rate limiting?

Answer

Rate limiting caps how many requests a client can make in a window — protecting your service from abuse, runaway scripts, and DOS attacks. Common algorithms: token bucket, sliding window. Typical implementation: Redis with INCR + EXPIRE per IP or user key. Most API gateways (Cloudflare, AWS WAF) also offer it.

Question

How do you log effectively in Node?

Answer

Use structured JSON logs (pino, winston) so they're machine-queryable. Include a request ID/trace ID on every log line to correlate. Write to stdout; let your platform (Docker, ECS, k8s) ship logs to a central system (Datadog, ELK, CloudWatch). Never log secrets or PII without scrubbing.

Question

What is a message queue?

Answer

A message queue is a durable buffer that decouples producers (services that create work) from consumers (services that do work). Producers push, consumers pull. Examples: RabbitMQ, AWS SQS, Apache Kafka, BullMQ on Redis. Queues absorb spikes, enable retries, and make systems resilient to consumer downtime.

Question

Why use a queue in backend systems?

Answer

Queues decouple services so they can scale and fail independently, absorb traffic spikes (so a viral signup doesn't crash you), allow retries with backoff, move slow work (emails, ML inference) off the request path, and provide audit trails. They're one of the highest-leverage abstractions in backend design.

Question

What are background workers?

Answer

Workers are background processes that pull jobs from a queue and execute them — used for sending emails, processing images, running scheduled reports, training ML models, or anything that takes longer than a typical HTTP request should. They scale horizontally and independently from your API tier.

Question

What is BullMQ?

Answer

BullMQ is a Redis-backed job queue for Node.js. It supports retries with exponential backoff, scheduled and recurring jobs, rate limiting, priorities, parent-child workflows, and a UI dashboard (Bull Board). Solid default choice when you don't want the operational complexity of Kafka or RabbitMQ.

Question

What is OOP in Java?

Answer

OOP organizes code around objects (data + behavior) instead of free-floating functions. Java's four pillars: Encapsulation (hiding internals), Inheritance (subclass extends base), Polymorphism (same call, different behavior), and Abstraction (programming to interfaces). It's how most enterprise Java codebases are structured.

Question

Overview of Java collections?

Answer

List (ArrayList, LinkedList) for ordered sequences. Set (HashSet, TreeSet) for unique items. Map (HashMap, TreeMap, ConcurrentHashMap) for key-value lookups. Queue (PriorityQueue, ArrayDeque) for FIFO/priority workflows. The right collection for the access pattern is one of the biggest perf levers in Java.

Question

ArrayList vs LinkedList?

Answer

ArrayList is a resizable array — O(1) random access, O(n) inserts in the middle. LinkedList is a doubly linked list — O(n) random access, O(1) insert/remove if you already have the node. ArrayList wins for nearly all real workloads; LinkedList's theoretical advantages rarely matter in practice due to cache effects.

Question

HashMap vs TreeMap?

Answer

HashMap gives O(1) average lookup/insert/delete via a hash table — keys are unordered. TreeMap is a Red-Black tree giving O(log n) ops but keys are sorted, enabling range queries (firstKey, headMap, etc.). Use HashMap unless you need ordering or sorted traversal.

Question

What is multithreading in Java?

Answer

Multithreading runs multiple threads concurrently within a single process. In modern Java, you use ExecutorService and thread pools rather than raw Threads. Concurrent code is hard — race conditions, deadlocks, memory visibility. Lean on concurrent collections (ConcurrentHashMap), atomics, and CompletableFuture instead of locks where possible.

Question

What are Java streams?

Answer

Streams provide a functional pipeline over collections — map, filter, reduce, collect — with lazy evaluation. list.stream().filter(…).map(…).collect(toList()). Streams enable parallel execution (.parallelStream()) and read like the operation you're describing, instead of nested for loops.

Question

What are the JVM basics?

Answer

The JVM loads class files, verifies bytecode for safety, JIT-compiles hot methods to native machine code, manages a generational heap, and runs garbage collection. It's why Java is portable (one bytecode runs everywhere) and why it can reach near-native performance after warmup.

Question

How does Java garbage collection work?

Answer

Generational GC: short-lived objects live in the young gen (Eden + Survivor spaces), survivors move to the old gen. Minor GCs collect young gen often and cheaply; major GCs sweep old gen and are pricier. Modern collectors (G1, ZGC, Shenandoah) minimize pause times by working concurrently.

Question

What is JIT compilation?

Answer

Just-In-Time compilation: the JVM starts interpreting bytecode, identifies hot methods (frequently executed), and compiles them to native machine code on the fly. After warmup, Java can match or beat C/C++ on many workloads thanks to runtime-driven optimizations the static compiler couldn't make.

Question

Java concurrency primitives?

Answer

synchronized blocks (intrinsic locks), volatile (visibility, not atomicity), Lock interfaces (ReentrantLock, ReadWriteLock), atomics (AtomicInteger, AtomicReference), CountDownLatch, Semaphore, CompletableFuture for async pipelines, and concurrent collections like ConcurrentHashMap. Prefer high-level primitives — raw synchronized blocks are easy to get wrong.

Question

What is Spring Boot?

Answer

Spring Boot is an opinionated layer over the Spring framework that auto-configures common setups, embeds a web server (Tomcat/Jetty), and lets you run a production-ready app with a single jar. It dramatically reduces XML and boilerplate — most enterprise Java services start here today.

Question

How do you build a REST API in Spring Boot?

Answer

Annotate a class with @RestController, methods with @GetMapping/@PostMapping/etc., and accept/return POJOs. Spring's MessageConverter (Jackson) auto-serializes to JSON. Add @Valid for request validation, @ExceptionHandler for errors, and you have a fully functional REST endpoint in a few lines.

Question

What is dependency injection in Spring?

Answer

Spring creates objects (beans) and wires their dependencies automatically. You declare what you need via constructor parameters (preferred) or @Autowired fields, and Spring resolves them from its container. This decouples your classes from how their collaborators are built, making testing and refactoring trivial.

Question

What is JPA?

Answer

JPA (Jakarta Persistence API) is Java's standard ORM specification — it defines annotations like @Entity, @Id, @OneToMany and the EntityManager API. You write Java classes that map to tables, and the provider (usually Hibernate) generates SQL. JPA lets you switch providers without changing your code.

Question

What is Hibernate?

Answer

Hibernate is the most popular JPA implementation. It maps Java classes to DB tables, generates SQL, manages sessions and caching, supports lazy loading, and handles dirty checking (auto-detecting changes). Hibernate is powerful but has gotchas — N+1 queries and LazyInitializationException are classic traps to learn.

Question

How do you secure a Spring Boot API?

Answer

Spring Security: configure a SecurityFilterChain with JWT or session auth, protect endpoints with @PreAuthorize/@Secured, enforce HTTPS, and handle CSRF (disable for stateless APIs, enable for browser forms). Add rate limiting at a gateway, and use Spring's built-in CORS handling.

Question

What is a JWT?

Answer

JSON Web Token — a signed, base64-encoded JSON payload carrying claims like user id, roles, and expiry. The signature lets servers verify authenticity without a database lookup, making JWTs stateless and easy to scale. Downside: revocation is harder (use short expiry + refresh tokens).

Question

What is OAuth2?

Answer

OAuth2 is an authorization framework where a user grants a client app limited access to their data on a resource server, mediated by an authorization server. It's why 'Sign in with Google' exists — your app gets a token, never sees the user's Google password. Standardized flows: Authorization Code (with PKCE), Client Credentials, Refresh.

Question

OAuth2 vs OIDC?

Answer

OAuth2 handles authorization (access tokens granting access to resources). OIDC (OpenID Connect) adds an identity layer: an ID token (JWT) that tells you WHO the user is, plus a userinfo endpoint. 'Sign in with Google' is technically OIDC, not pure OAuth2 — the ID token is the key piece.

Question

Microservices vs monolith?

Answer

Monolith: one codebase, one deploy, one DB — simpler ops, easier refactoring, slower to scale teams. Microservices: many services, each independently deployed and scaled — better team autonomy but huge ops complexity (networking, observability, consistency). Start with a monolith; split when team or scale forces it.

Question

How do microservices communicate?

Answer

Sync calls over REST or gRPC when callers need an immediate answer; async over message queues (Kafka, RabbitMQ, SQS) when fire-and-forget or event-driven. Sync is simpler but couples services tightly. Async is more resilient but harder to reason about — pick per use case.

Question

What is FastAPI?

Answer

FastAPI is a modern Python web framework using type hints to power both validation (via Pydantic) AND auto-generated OpenAPI docs. It's async-first (built on Starlette/ASGI), so it's significantly faster than Flask/Django for I/O-bound workloads. The developer experience is exceptional, especially for AI/ML APIs.

Question

What is async programming in Python?

Answer

Python's async/await with the asyncio library lets a single thread handle many I/O-bound tasks concurrently. You write async def functions and await on coroutines (sleep, network calls). It's NOT parallel CPU execution — for CPU work, use multiprocessing or a different language tier.

Question

What is Celery?

Answer

Celery is Python's most popular distributed task queue, typically backed by Redis or RabbitMQ. You define tasks (functions), enqueue them with .delay(args), and worker processes pick them up. Used for emails, ETL, AI inference, scheduled jobs — anything you don't want to block an HTTP request.

Question

FastAPI vs Flask?

Answer

FastAPI is async, has built-in validation via Pydantic, and auto-generates OpenAPI docs. Flask is sync, minimal, with the largest ecosystem and the simpler mental model. New Python APIs almost always choose FastAPI; Flask still wins for tiny scripts or when you need very specific WSGI-based libraries.

Question

What is Pydantic?

Answer

Pydantic is a Python data validation library built around type hints. You declare a class with typed fields and Pydantic gives you runtime parsing, validation, JSON Schema generation, and clear error messages. FastAPI uses it for every request and response model. Pydantic v2 is dramatically faster than v1.

Question

What is LangChain?

Answer

LangChain is a Python (and JS) framework for building LLM-powered apps. It provides primitives like chains (composable prompt → LLM → output), agents (LLM with tools), memory, retrievers (RAG), and integrations with most LLM providers and vector stores. Useful for prototyping; production teams often pick more focused tools instead.

Question

How do you handle errors centrally in Express?

Answer

Define an error-handling middleware (the 4-argument signature: err, req, res, next) at the end of your middleware stack. Forward errors with next(err) from any handler. The error middleware logs, decides status code, and sends a sanitized response — keeping error handling in one place.

Question

What is CORS?

Answer

Cross-Origin Resource Sharing. By default, browsers block JavaScript from reading responses from a different origin. CORS is the server's way of opting in: respond with Access-Control-Allow-Origin and friends, and the browser allows the request. Server-to-server calls are not affected — CORS is a browser-only policy.

Question

What is idempotency in REST?

Answer

An operation is idempotent if running it multiple times gives the same end result. GET/PUT/DELETE are idempotent (by spec); POST usually isn't. Idempotency lets clients safely retry on network errors. For non-idempotent POSTs, accept an Idempotency-Key header and dedupe server-side.

Question

Status code for created resource?

Answer

201 Created. Best practice: also return a Location header pointing to the new resource's URL (e.g. /users/abc123) and include the created entity in the body. For long-running creates, return 202 Accepted with a way to poll status.

Question

Common HTTP status codes?

Answer

200 OK, 201 Created, 204 No Content (success, empty body). 301/302 redirects. 400 Bad Request, 401 Unauthorized (no/invalid auth), 403 Forbidden (authenticated but not allowed), 404 Not Found, 409 Conflict, 422 Unprocessable Entity, 429 Too Many Requests, 500 Server Error, 503 Service Unavailable.

Question

What is a circuit breaker?

Answer

A circuit breaker stops calls to a failing dependency once errors exceed a threshold — instead of piling up timeouts, the breaker 'opens' and immediately fails fast. After a cool-down it lets a probe through (half-open) to test recovery. Protects you from cascading failures across services.

Question

What is the bulkhead pattern?

Answer

Bulkheads isolate resources (thread pools, connection pools) per dependency, so a single slow downstream can't drain all your resources. Think of it like a ship's watertight compartments — one floods, the others stay dry. Crucial for resilient service-to-service architectures.

Question

What is graceful shutdown?

Answer

On SIGTERM, your service should: stop accepting new requests, finish in-flight ones (with a timeout), close DB and queue connections cleanly, then exit. Kubernetes gives you ~30 seconds by default. Without graceful shutdown, deploys cause errored requests and lost work.

Question

How do you handle file uploads?

Answer

Stream multipart data (don't buffer huge files in memory), validate MIME type AND check magic bytes, enforce a size limit, scan for malware if untrusted, and store in object storage (S3) — not on the app server's local disk, which doesn't survive restarts and doesn't scale horizontally.

Question

What is connection pooling?

Answer

Instead of opening a DB connection per request, the app maintains a pool of reusable connections. This avoids TCP/TLS handshake overhead, caps concurrency to protect the DB, and recycles connections after a max age. Every serious DB driver has built-in pooling — tune size based on workload.

Question

What is API versioning?

Answer

API versioning lets clients on old versions keep working while you ship breaking changes. Three approaches: URL path (/v1/users — most popular, easy to debug), Accept header, or query param. Pick one and stick to it. Better long-term play: avoid breaking changes by being additive.

Question

REST vs GraphQL?

Answer

REST: multiple endpoints, fixed response shapes — simple to cache, easy to debug, may over/under-fetch. GraphQL: single endpoint, client picks exactly the fields it wants — solves over-fetching but adds server complexity (resolvers, N+1, query depth limits). Use GraphQL when frontends vary widely in needs.

Question

REST vs gRPC?

Answer

REST: human-readable JSON over HTTP, ubiquitous, easy to test with curl. gRPC: binary Protocol Buffers over HTTP/2, with code-gen for clients in many languages, streaming support, much lower latency. REST for public APIs and external integrations; gRPC for internal service-to-service traffic.

Question

What is event-driven architecture?

Answer

Services publish events to a broker (Kafka, RabbitMQ) and other services subscribe to react. The producer doesn't know or care about consumers. This decouples teams, enables replay and audit, scales well — but the implicit graph of producers/consumers is harder to reason about than direct calls.

Question

What is eventual consistency?

Answer

After a write, different replicas can briefly disagree, but they converge over time (assuming no new writes). Trades strict consistency for availability and scale — essential in geo-distributed systems. UIs must handle the 'I just changed it but I see the old value' moment.

Question

What is a saga?

Answer

A saga is a long-running distributed transaction broken into local steps, each with a compensating action to undo it on failure. e.g. book flight → charge card → reserve hotel; if hotel fails, refund and cancel flight. Sagas avoid distributed locks and 2PC — the price is more app-level logic.

Question

What is two-phase commit (2PC)?

Answer

A coordinator asks all participants 'can you commit?' (prepare phase); if all say yes, it tells them to commit (commit phase). It provides strong consistency across systems but blocks if the coordinator fails mid-flight. Mostly avoided in modern designs in favor of sagas or idempotent operations.

Question

What is a health check endpoint?

Answer

An endpoint (/health, /healthz) returning the service's status. Load balancers and orchestrators (k8s, ECS) hit it to decide whether to route traffic. Two flavors: liveness (am I alive at all?) and readiness (can I serve traffic right now?). Lightweight, never auth-protected.

Question

Liveness vs readiness probes?

Answer

Liveness: is the process alive? Restart if no (good for stuck deadlocks). Readiness: can it serve traffic right NOW? Remove from load balancer if no — but don't kill the process (it might be loading caches, draining, etc.). Both probes are essential; conflating them causes restart loops.

Question

What is an API gateway?

Answer

An API gateway is a single entry point in front of your microservices. It handles routing, authentication, rate limiting, request/response transformation, caching, and observability. Without one, every service must implement those concerns separately. Examples: Kong, AWS API Gateway, Nginx, Envoy.

Question

What is service discovery?

Answer

Service discovery is dynamically finding where service instances live, since they come and go in dynamic environments. Solutions: DNS-based (k8s Services, Cloud Map), key-value stores (Consul, etcd), or platform-native (k8s endpoints). Without it, you'd hardcode IPs and break every deploy.

Question

Why is async I/O important in Node?

Answer

Node is single-threaded — a synchronous I/O call would block the event loop, freezing the entire process. Async I/O lets the loop continue serving other requests while the kernel handles disk/network in the background. It's the entire reason Node can handle thousands of connections on one CPU.

Question

CPU-bound vs I/O-bound?

Answer

I/O-bound work waits on disk/network — Node handles tons of it concurrently. CPU-bound work (image transforms, parsing, ML inference) blocks the event loop and stalls everyone else's requests. For CPU work, use worker threads, offload to a queue + workers, or use a different runtime entirely.

Question

Where do you store secrets?

Answer

In a secret manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager) or as env vars injected by the platform. Rotate regularly, audit access, and never commit secrets to git. Tools like git-secrets, trufflehog, or pre-commit hooks catch accidental leaks.

Question

What is OpenAPI?

Answer

OpenAPI (formerly Swagger) is a spec for describing REST APIs in YAML/JSON. From one spec you get API docs (Swagger UI), client SDKs in many languages, mock servers, and request validation. Treat the spec as source of truth — design API first, then generate.

Question

What is structured logging?

Answer

Logs emitted as JSON with consistent fields: timestamp, level, message, trace_id, user_id, latency_ms. Machine-queryable, filterable, and aggregatable — versus plain-text logs you have to grep. Tools: pino (Node), logrus/zap (Go), structlog (Python), Logback with JSON encoder (Java).

Question

What is observability?

Answer

Observability is the ability to understand a system's internal state from external signals: logs (what happened), metrics (how much/how often), and traces (the path of a single request across services). Without it, debugging production is guesswork. OpenTelemetry is the emerging standard for all three.

Question

What is distributed tracing?

Answer

Distributed tracing follows a single request as it flows through many services. Each hop creates a span (with timing, metadata); spans share a trace ID. You see exactly where time is spent and where failures originate. Tools: Jaeger, Zipkin, Datadog APM, and OpenTelemetry SDKs.

Question

What is backpressure?

Answer

Backpressure is when a slow consumer signals upstream to slow down, preventing queue overflow and OOM crashes. In Node streams, this is the .pause/.resume protocol. In queues, it's bounded buffers and rejecting/retrying when full. Designing for backpressure is essential at any real scale.

Question

What is a webhook?

Answer

A webhook is an HTTP callback: another service POSTs to a URL you provide when something happens (payment succeeded, GitHub push, Stripe event). Webhooks invert the polling model — you get notified instead of asking. They must be idempotent and signed to verify the sender.

Question

How do you make webhooks reliable?

Answer

Receiver: idempotency keys so duplicate deliveries don't double-process; verify HMAC signatures; respond 2xx fast (queue work for later). Sender: retry with exponential backoff, send to a dead-letter queue after max attempts, store delivery attempts for debugging, expose a manual replay tool.

Question

What is the N+1 query problem?

Answer

You load a list (1 query), then loop and load related data for each item (N more queries). 1 + N round trips kills perf at scale. Fix with eager loading (JOIN), batched queries (DataLoader pattern in GraphQL), or projections that fetch what you need upfront.

Question

What is request validation?

Answer

Verifying incoming data matches the expected shape and types before processing — preventing crashes, bad data, and security holes. Schema-based libs: Zod (TS), Joi, AJV (JSON Schema), Pydantic (Python), Spring's @Valid + Bean Validation (Java). Validate at the boundary, then trust internally.

Question

When to use HTTP/2 or HTTP/3?

Answer

HTTP/2: multiplexes many requests over one TCP connection — great default today. HTTP/3 (QUIC over UDP): lower latency on lossy networks (mobile), faster connection setup. CDNs and modern load balancers support both transparently — usually 'just turn it on' wins.

Question

What are Server-Sent Events (SSE)?

Answer

SSE is a one-way streaming protocol from server to client over HTTP. The server sends 'event:' messages on a long-lived connection; the client reads them via EventSource. Simpler than WebSockets when you only need server pushes (live dashboards, LLM token streaming) — and works over plain HTTP.

Question

When to choose WebSocket?

Answer

When you need full-duplex, low-latency, frequent two-way messages — chat, collaborative editing, multiplayer games, live presence indicators. Both client and server can send at any time. For one-way pushes, prefer SSE (simpler). For request/response, just use HTTP.

Question

What is a database transaction?

Answer

A transaction is a unit of work treated atomically — either all statements commit, or all roll back if any fails. Wrap related writes in one transaction so partial failures don't leave the DB inconsistent. Powered by the DB's ACID guarantees.

Question

What is a connection leak?

Answer

A connection leak is when code opens a DB connection but never returns it to the pool — eventually the pool is exhausted and new requests hang. Fix: always release in a finally block, use try-with-resources (Java), or context managers (Python with). ORMs usually handle this automatically.

Question

What is the thread-per-request model?

Answer

Each incoming request runs on its own dedicated thread. Simple to reason about and works fine at moderate scale, but each thread costs memory (~1MB) — at very high concurrency you run out. This is why async/reactive models exist for I/O-heavy workloads.

Question

What is reactive programming?

Answer

Async, non-blocking, push-based data flow modeled as streams that you compose with operators (map, filter, debounce, retry). Libraries: Project Reactor (Java), RxJava, RxJS. Particularly good under high concurrency — one thread can serve thousands of requests. Steeper learning curve than imperative code.

Question

What is dependency injection (DI)?

Answer

DI is providing a class with its dependencies from outside instead of constructing them internally. Instead of `new Database()` inside, you accept a Database in the constructor. Makes code testable (pass in mocks), flexible (swap implementations), and avoids hidden coupling. Frameworks like Spring/Nest automate the wiring.

Question

What is Inversion of Control (IoC)?

Answer

IoC is letting a framework or container control flow and wiring instead of writing it yourself. DI is one form of IoC. Instead of your code calling 'new', creating instances, and managing lifecycles, you declare what you need and the container provides it.

Question

How do you implement retry logic?

Answer

Catch transient errors (timeouts, 503, network errors), retry with exponential backoff and jitter (so retries don't synchronize across clients), cap attempts, and CLASSIFY errors — don't retry 4xx (your bug) or business-logic failures. Use libraries (axios-retry, resilience4j) rather than rolling your own loop.

Question

What is exponential backoff?

Answer

Each retry waits exponentially longer: 200ms, 400ms, 800ms, 1.6s… It gives the failing dependency room to recover. Always add JITTER (a random fraction) so many clients retrying simultaneously don't thunder herd back into the dependency at the same instant.

Question

What is connection draining?

Answer

When a server is being taken offline (deploy, scale-in), connection draining keeps existing connections alive while new ones are routed to other instances. Once existing connections close or hit a timeout, the instance is removed. Critical for zero-downtime deploys.

Question

What are signed URLs?

Answer

Time-limited URLs that grant temporary access to a private resource (typically S3 or another object store) without exposing credentials. Server signs the URL with its key; client (or anyone with the URL) uses it directly. Common for downloads, uploads, and embedding private images.

Question

How do you handle large file downloads?

Answer

Stream the response body (don't load into memory), support HTTP Range requests so clients can resume after a disconnect, set Content-Length and Accept-Ranges headers, and use signed S3 URLs to offload bandwidth from your app servers entirely.

Question

What is response compression?

Answer

Gzip or Brotli the response body for text-heavy responses (JSON, HTML, JS). The browser sends Accept-Encoding; the server replies with Content-Encoding. Cuts payload by 60-90% for typical JSON APIs — one of the highest-leverage perf settings to flip on.

Question

Why prefer constructor injection?

Answer

Constructor injection forces dependencies to be declared explicitly in the signature, makes objects immutable (final fields), and makes unit tests trivial — you just pass mocks in. Field injection (via @Autowired) hides dependencies and requires reflection-based test setup. Constructor wins on every axis.

Question

What is the repository pattern?

Answer

An abstraction layer between business logic and data access. The service depends on an interface like UserRepository, not on Mongo or Postgres directly. You can swap implementations (in-memory for tests, real DB for prod) and the business code doesn't change. Slightly extra boilerplate, big testability gain.

Question

What is API throttling?

Answer

Throttling slows down or rejects requests once a client exceeds a limit. Often used interchangeably with rate limiting, but throttling usually applies at the gateway layer and may queue or delay rather than reject outright. Both protect downstream services from being overwhelmed.

Question

Short-lived vs long-lived tokens?

Answer

Short-lived access tokens (5-15 min) limit damage if stolen. Long-lived refresh tokens (days to weeks), stored securely, are used to get fresh access tokens silently. This pair gives you UX (no constant logins) and security (small blast radius for stolen access tokens).

Question

How do you revoke JWTs?

Answer

JWTs are stateless, so revocation needs an external store. Options: a Redis deny-list of jti (token id) or 'tokens issued before X' per user; or keep access tokens very short-lived and revoke via the refresh token's deny-list. Trade-off: stateless vs revocable — pick where you compromise.

Question

What is HTTP keep-alive?

Answer

Keep-alive reuses a single TCP connection for multiple HTTP requests, avoiding the cost of repeated TCP/TLS handshakes. Default in HTTP/1.1. Tune Connection and Keep-Alive headers carefully behind load balancers — too long keeps stale connections; too short defeats the purpose.

Question

What is an idempotency key?

Answer

A client-provided unique key (often a UUID per logical operation) the server caches alongside the result. If the same key arrives again (network retry), the server returns the cached response instead of doing the work twice. Essential for payment APIs and any non-idempotent operation.

Question

How do you design pagination?

Answer

Offset-based (page + size) is simple but slow on big tables and prone to skipping/dup on inserts. Cursor-based (after=lastId) uses the last seen ID as a pointer — scales better and is stable under concurrent inserts. For very large data, cursor is the right default.

Question

What is the GraphQL N+1 problem?

Answer

Each resolver fetches one record per parent, so a list of 100 users with their posts triggers 1 + 100 queries to the DB. Fix with DataLoader: collect the IDs requested in this tick, batch them into a single query, and distribute the results back to each resolver.

Question

What is gRPC streaming?

Answer

gRPC supports four call types: unary (req → resp), server-streaming (req → stream of resps), client-streaming (stream → resp), and bidirectional (stream ↔ stream). Built on HTTP/2 multiplexing. Great for telemetry uploads, chat protocols, and any long-running response.

Practise Backend Engineering in the app
Track your progress, flag tricky cards and write your own answers.

Open in the app

More topics: React & Frontend JavaScript & TypeScript Databases System Design AI & Agentic AI DevOps & Cloud Security Testing DSA Coding Problems (Python)