Backend Fundamentals: Memory, Serialization, gRPC, Kafka, SQL, and CI/CD
Medium · System Design · Software Engineer · Technical Screen
Prompt
Walk through the core backend engineering concepts below and explain how each choice shapes production service design:
- Stack vs. heap memory: How do stack allocation and heap allocation differ in lifetime, allocation cost, capacity limits, and thread safety?
- Binary vs. text serialization: How does Protocol Buffers (
Protobuf) compare againstJSONwhen encoding structured payloads? - Service-to-service communication: How does
gRPCdiffer from older RPC frameworks (as well as plain HTTP/REST APIs), and where does each fit best? - Distributed event logs: Under what workload patterns should you introduce an event-streaming platform such as Apache Kafka—and when is it the wrong tool?
- Relational queries: In what situations should a service combine records with a
SQLtable join rather than querying separately or denormalizing? - Core terminology: Expand the acronyms
SQLandCI/CD, briefly describing the practical engineering role of each.
Scope & Expectations
- Ground each comparison in concrete systems trade-offs—latency, CPU and memory overhead, wire compatibility, operational burden, and failure modes—rather than isolated dictionary definitions.
- Show how these building blocks fit together inside a cohesive multi-service backend (public client edge vs. internal service calls, transactional tables vs. asynchronous event fan-out).
- Call out common failure modes and edge cases across memory safety, schema evolution, network load balancing, asynchronous event delivery, and relational query design.
Step-by-step walkthrough
Frame the round around one concrete architecture
Note: Older RPC systems can refer either to classic IDL-based frameworks (Sun RPC, CORBA, Java RMI, SOAP) or to plain HTTP/REST APIs; this walkthrough contrasts gRPC with both.
When an interviewer asks seven rapid-fire infrastructure questions in a single round, reciting dry dictionary definitions makes the conversation feel shallow. Two habits turn a multi-part screen into a senior-level design discussion:
- Use a three-beat rhythm per topic: (1) a one-sentence plain-English definition, (2) the core engineering trade-off, and (3) one concrete number or decision. Budget ~4 minutes for each comparison and ~60 seconds for the two acronyms so time remains for follow-ups.
- Anchor all seven answers on one running system so every comparison ends in a real architectural choice.
Running example: a hotel-booking platform
searchhandles 5,000 requests/s at peak, returning 50 hotel offers per response under a strict 300 ms latency budget.bookingconfirms 50 room bookings/s at peak in Postgres.- Every confirmed booking must notify four independent downstream consumers: confirmation email, loyalty points, search availability index, and analytics.
- Engineers merge and deploy changes dozens of times per day.
Sub-question Where it lives in the hotel platform Heap vs. stack memory Memory layout inside every searchandbookingserver processProtobuf vs. JSON Wire format for public browser responses vs. internal service payloads gRPC vs. traditional RPC / REST Synchronous calls from searchtopricingandavailabilityEvent streaming (Kafka) Fanning one BookingConfirmedevent out to 4 downstream consumersSQL table joins Querying normalized bookings,hotels, andpaymentsinsidebookingSQL & CI/CD acronyms Declarative database querying and safe automated production rollouts Heap vs. stack memory
Every running process divides its working RAM into two main regions for program data. Each thread gets its own private stack, where every function call pushes a contiguous block called a stack frame (holding local variables, parameters, and the return address) that pops off automatically the instant the function returns. All threads in the process share a single heap, a dynamic memory pool for objects whose size is unknown at compile time or whose lifetime outlives the function that created them.
Process Memory Layout +-------------------------------------------------------------------+ | Thread 1 Stack (private, LIFO, ~1-8 MB) | | [Frame: main()] -> [Frame: handleSearch(reqPtr)] | | int limit = 50; offerPtr ------+ | | (popped automatically on return)| | +-------------------------------------------------------|-----------+ | Thread 2 Stack (private, LIFO, ~1-8 MB) | | | [Frame: main()] -> [Frame: confirmBooking()] | | +-------------------------------------------------------|-----------+ | Shared Process Heap (up to GBs of RAM, all threads) v | | [HotelOffer[50] array] [DB Connection Pool] [Cache Map] | | (freed explicitly via free()/RAII, or reclaimed by GC) | +-------------------------------------------------------------------+Dimension Stack memory Heap memory Lifetime Strictly tied to one function call (LIFO) Lives until explicitly freed or garbage-collected Allocation cost 1 CPU instruction (move stack pointer register) Slower: allocator searches free lists or triggers garbage collection (GC) (automatic background cleanup of unreachable heap objects) Thread safety Private to one thread—zero locking needed Shared across threads—concurrent writes require locks or atomics Typical size Small & bounded: ~8 MB Linux C thread ( ulimit -s), ~1 MB JVM thread (-Xss), ~2 KB initial growable Go goroutine stackLarge: bounded by container RAM / -Xmx(gigabytes)Failure modes Stack overflow from unbounded recursion or giant local arrays Memory leaks, out-of-memory kills, fragmentation, dangling pointers, GC latency spikes A 10-line C example illustrates the lifetime difference:
#include <stdlib.h> int *make_counter_broken(void) { int count = 0; /* Allocated on this call's stack frame */ return &count; /* BUG: frame vanishes on return -> dangling pointer! */ } int *make_counter_safe(void) { int *count = malloc(sizeof(*count)); /* Allocated on the shared heap */ if (count != NULL) *count = 0; return count; /* Safe after return; caller owns free(count) */ }How modern languages decide placement—and why it matters in
search: - C / C++ / Rust: You choose directly (local value vs.malloc/std::make_unique/Box::new). - Java & Go: Compilers run escape analysis (a compile-time check of whether a variable's reference can escape the current function). In Go (go build -gcflags=-m), non-escaping structs stay cheaply on the goroutine stack; escaping ones move to the heap. - Python: All objects live on the heap; the call stack holds frame pointers capped bysys.getrecursionlimit()(default 1,000). - Clarification worth stating: Heap memory (an allocator pool) is unrelated to the heap data structure (a tree-based priority queue). - Impact on our backend: Running 400 Java threads reserves400 * 1 MB = 400 MBjust for thread stacks, and allocating millions of temporary heap objects per second at 5,000 searches/s causes GC pauses that blow our 300 ms p99 budget—so pooling buffers on the hot path and avoiding recursive parsers on untrusted user JSON both matter in production.Binary vs. text serialization: Protobuf and JSON
Serialization converts in-memory data structures into a sequence of bytes to send across a network or save to disk. JSON is a self-describing human-readable text format that repeats field names inside every single record. Protocol Buffers (Protobuf) is a binary format defined by an explicit
.protoschema: field names are replaced on the wire by tiny numeric field tags, and integers use varints (variable-length integers that pack 7 bits of value per byte, using the 8th bit as a "more bytes follow" flag).// hotel.proto message HotelOffer { int64 hotel_id = 1; int64 price_cents = 2; string currency = 3; float rating = 4; bool available = 5; }Here is how Protobuf encodes a tag and varint in plain Python (tag byte =
(field_number << 3) | wire_type, fitting in 1 byte for fields1..15):def encode_varint(value: int) -> bytes: """Encode a non-negative integer into 7-bit Protobuf varint bytes.""" encoded = bytearray() while True: lowest_7_bits = value & 0x7F value >>= 7 if value > 0: # Set the top continuation bit (0x80) because more 7-bit groups follow. encoded.append(lowest_7_bits | 0x80) else: encoded.append(lowest_7_bits) return bytes(encoded) # Field 1 (wire type 0 = varint) with value 150 -> tag 0x08 + varint 0x96 0x01 (3 bytes total, # compared with 10 bytes for JSON '{"id":150}'). tag_byte = (1 << 3) | 0 assert bytes([tag_byte]) + encode_varint(150) == bytes([0x08, 0x96, 0x01])Exact byte comparison on one
HotelOfferin oursearchservice:Sample offer: {"hotel_id":123456789,"price_cents":12999,"currency":"EUR","rating":4.5,"available":true} JSON (compact UTF-8): 89 bytes total Protobuf binary: 20 bytes total Field 1 (hotel_id = 123456789): 1 tag byte + 4 varint bytes = 5 bytes Field 2 (price_cents = 12999): 1 tag byte + 2 varint bytes = 3 bytes Field 3 (currency = "EUR"): 1 tag byte + 1 len byte + 3 chars = 5 bytes Field 4 (rating = 4.5): 1 tag byte + 4 IEEE-754 bytes = 5 bytes Field 5 (available = true): 1 tag byte + 1 bool byte = 2 bytes At search scale (50 offers per response * 5,000 responses/s): 1 response (50 offers, raw): JSON ~4.5 KB vs. Protobuf ~1.1 KB (~4x smaller) 1 response (50 offers, gzipped): JSON ~0.75 KB vs. Protobuf ~0.60 KB (gzip closes much of the size gap!) Raw internal network bandwidth: JSON ~22.6 MB/s vs. Protobuf ~5.5 MB/s (zero gzip CPU needed)Dimension JSON Protobuf Contract & types Schema optional (OpenAPI); untyped on the wire Mandatory .protoschema; generates strongly typed classes in Go, Java, Python, C++CPU & wire size Larger text; slower string/number parsing (though gzip shrinks wire size at CPU cost) Compact binary; fast tag-jump parsing without scanning quotes and escapes Human debugging Instant in browser DevTools and curlOpaque bytes without .protodefinitions (grpcurl, Wireshark plugin)Schema evolution Ad-hoc; renaming a key silently breaks consumers Safe if you only add new field numbers and mark deleted numbers reservedSharp edge JavaScript Numberis 64-bit float—integers> 2^53 - 1silently lose precision (send 64-bit IDs as strings!)proto3scalar fields default to0/""/falseunless markedoptionalto track explicit presenceArchitectural choice: Serve JSON at our public API gateway for web browsers and third-party partners; use Protobuf between internal microservices and inside Kafka events where schema enforcement and parsing CPU matter.
Service-to-service calls: gRPC, legacy RPC, and REST
Remote Procedure Call (RPC) lets a program invoke a function on another machine using a generated client stub (auto-generated code that serializes parameters, sends the network request, and unpacks the reply) defined by an Interface Definition Language (IDL) (a language-neutral contract file).
Dimension Classic RPC (Sun RPC, CORBA, Java RMI, SOAP) REST + JSON over HTTP gRPC Contract / IDL XDR, CORBA IDL, Java interfaces (Java-only!), verbose XML WSDL Resource URLs + HTTP verbs; OpenAPI optional Clean .protoservice & message definitions across 10+ languagesWire format Custom binary, brittle Java serialization, or bloated SOAP XML Text JSON Compact binary Protobuf Transport Custom TCP/UDP sockets or HTTP/1.1 HTTP/1.1 or HTTP/2 HTTP/2 multiplexing (many concurrent requests share a single TCP connection without head-of-line HTTP/1.1 blocking) Streaming Rarely built in Separate protocols (SSE, WebSockets) Native unary, server-stream, client-stream, and bidirectional streams Timeouts & cancel Custom per framework Per-hop client socket timeouts only Built-in grpc-timeoutheader & cancellation propagate automatically down call chainsBrowser & CDN caching Poor Native browser fetch()+ standard HTTPGETcachingNeeds a gRPC-Webtranslation proxy;POST-based calls bypass HTTP URL cachesWhy gRPC beats both classic RPC and internal REST inside our backend—plus one production trap: - Classic RPC suffered from language lock-in (Java RMI) or heavyweight, incompatible XML vendor stacks (CORBA/SOAP). Internal REST fixes portability yet loses strict codegen contracts and built-in deadline propagation. With gRPC, when
searchsets a 300 ms deadline and spends 20 ms locally, its outbound gRPC calls topricingandavailabilityautomatically carry the remaining 280 msgrpc-timeout—if the user disconnects, cancellation propagates downstream immediately. - Load-balancing trap: Because HTTP/2 multiplexes thousands of gRPC calls over one long-lived TCP connection, a Layer 4 (L4) TCP load balancer (which picks a backend only once when the TCP connection opens) pins all traffic from a client onto whichever old pods existed at startup! Always pair gRPC with a Layer 7 (L7) HTTP/2-aware proxy (like Envoy) that balances every individual RPC call, or use client-side load balancing withMAX_CONNECTION_AGE.When event streaming (Kafka) is the right tool
Apache Kafka is a distributed, replicated append-only log split into partitions. Producers append immutable events at the end; independent consumer groups track their own read offsets and process the log at their own pace without deleting messages for others.
Use event streaming when the problem looks like "one business fact, many independent readers, over time": 1. Multi-service fan-out without coupling: When
bookingconfirms one reservation (50/s * 2 KB = 100 KB/s), publishingBookingConfirmedonce letsemail,loyalty,search-index, andanalyticsreact independently—adding a fifth fraud-scoring consumer requires zero code changes inbooking. 2. Temporal decoupling & burst absorption: If theloyaltydatabase goes down for 30 minutes of maintenance, bookings continue succeeding at 100% availability while loyalty events wait safely in Kafka. 3. Historical replay: With 7-day retention, deploying a bug fix toanalyticslets that consumer rewind its offset to Tuesday and recompute accurate totals. 4. High-throughput key-ordered streams: User clickstreams (50,000 clicks/s keyed bysession_id), metrics, and database change streams.Do NOT reach for Kafka when: - The caller needs an immediate synchronous answer ("Is Room 302 still available right now?") -> use synchronous gRPC/REST plus Postgres locks. - You need a per-task work queue with individual message priorities, 15-minute delayed retries, or out-of-order single-task acknowledgments -> a dedicated queue like SQS or RabbitMQ is far simpler because classic Kafka consumer groups track a single linear offset per partition (a single stuck task blocks its partition, though newer Kafka releases introduce queue-like share groups via KIP-932). - Volume is tiny with a single consumer -> Kafka adds operational overhead (brokers, partition tuning, lag alerts, schema registry). - Watch out for dual-writes: Never commit to Postgres and
send()to Kafka as two separate steps; write an outbox row inside the same Postgres transaction and let a relay publish it so crashes never drop events.When to use a SQL join (and when not to)
In a relational database, normalization stores each fact in one place (hotel names live in
hotels, reservations live inbookingslinked by a foreign keyhotel_id) so renaming a hotel updates 1 row instead of 50,000 old booking rows. Use a SQL join whenever one query needs columns from related tables inside the same database:-- Fetch a guest's 20 most recent bookings together with hotel name and city in 1 round trip SELECT b.booking_id, b.check_in, b.total_cents, h.name AS hotel_name, h.city FROM bookings AS b INNER JOIN hotels AS h ON h.hotel_id = b.hotel_id WHERE b.user_id = 42 ORDER BY b.check_in DESC LIMIT 20;Why joining in SQL beats joining in application loops: Fetching 20 bookings first and then running 20 separate
SELECT ... FROM hotels WHERE hotel_id = ?queries inside aforloop is the classic N+1 query problem:21 round trips * 0.5 ms network RTT = 10.5 msof idle waiting, whereas a single indexed SQL join (PRIMARY KEY (hotel_id)+ composite indexbookings(user_id, check_in DESC)) finishes in 1 round trip (~1 ms).Choosing the right join—and avoiding the one-to-many double-counting trap: -
INNER JOINkeeps only rows matching on both sides. -LEFT JOINkeeps every left row even when zero right rows match (for example, listing every hotel with its review count—always writeCOUNT(r.review_id), neverCOUNT(*), which counts aNULL-padded unmatched hotel row as1!). - Semi-join (WHERE EXISTS) when filtering across a 1-to-many table: Suppose Booking#10(total = $200) had 2 failed card retries followed by 1 succeeded row inpayments:bookings payments +------------+-------+ +------------+------------+----------+ | booking_id | total | | payment_id | booking_id | status | +------------+-------+ +------------+------------+----------+ | 10 | 200 | | 501 | 10 | FAILED | +------------+-------+ | 502 | 10 | FAILED | | 503 | 10 | CAPTURED | +------------+------------+----------+ Naive JOIN: bookings JOIN payments produces 3 rows for booking #10 -> SUM(b.total) = $600 (3x WRONG!)-- Correct: filter with a semi-join (EXISTS) so each booking row is counted at most once SELECT SUM(b.total_cents) FROM bookings AS b WHERE EXISTS ( SELECT 1 FROM payments AS p WHERE p.booking_id = b.booking_id AND p.status = 'CAPTURED' );Three places NOT to use a SQL join: 1. Across microservice boundaries:
bookingmust never reach directly intoloyalty's Postgres database (that couples deployments and schemas); call an API or consume events instead. 2. Ultra-hot read paths (5,000 searches/s): Denormalize (pre-embed hotel name, city, and star rating directly into each search-index document, refreshed asynchronously via Kafka events) sosearchserves reads with zero runtime joins. 3. Heavy multi-terabyte analytics: Run those on a read replica or columnar data warehouse, never on the live booking primary.Expanding SQL and CI/CD in production workflows
SQL stands for Structured Query Language. - Originated at IBM in the 1970s (originally spelled SEQUEL) and standardized by ANSI/ISO in 1986–1987. - Its defining superpower is that it is declarative: you specify what result set you want, and the database's query planner / optimizer inspects table statistics and indexes (
EXPLAIN ANALYZE) to pick the fastest physical execution plan (index nested-loop join, hash join, or sort-merge join).CI/CD stands for Continuous Integration and Continuous Delivery (or Continuous Deployment). - Continuous Integration (CI): Engineers merge small commits into
mainat least daily; every pull request and merge automatically runs linting, unit tests, Protobuf backward-compatibility checks, and containerized integration tests so broken code is caught within minutes. - Continuous Delivery (CD): Every commit that passes CI produces a signed, immutable container artifact ready to go live in production with a single manual approval click. - Continuous Deployment (also CD): Removes the manual button—every green merge rolls out to production automatically, guarded by progressive traffic shifting and automated rollback.Automated CI/CD Pipeline for the "booking" Service [Pull Request] --> Lint + Unit Tests + Protobuf Wire-Break Check (< 8 min) | merge to main v [Build Once] --> Immutable Docker image tagged sha-9f3a2c + Integration Tests | (real Postgres + Kafka in ephemeral containers, < 12 min) v [Staging] --> Deploy exact sha-9f3a2c image -> automated end-to-end smoke suite | v [Production] --> Canary rollout: 5% live traffic for 15 min Compare error rate & p99 latency vs. baseline pods: - healthy -> ramp 25% -> 100% - degraded -> automatic instant rollback to previous imageTo keep instant rollback safe when Postgres tables change, pair CI/CD with expand-and-contract database migrations: (1) add a nullable new column first, (2) deploy code writing both old and new columns, (3) backfill historical rows, (4) switch reads to the new column, and (5) drop the old column in a later release.
Unified system architecture and decision matrix
Here is how all seven concepts fit together cleanly inside one production architecture:
Web Browsers & Mobile Apps | | HTTPS + REST / JSON (human-readable, browser-native, CDN-cacheable GETs) v +---------------+ | API Gateway | Auth, rate limiting, JSON <-> Protobuf translation +---+-------+---+ | | | | gRPC + Protobuf over HTTP/2 (L7 Envoy load-balanced, 300 ms deadline) | v | +--------+ ---- gRPC ----> [pricing] | | search | ---- gRPC ----> [availability] | +--------+ (reads denormalized search index: zero SQL joins at 5,000 req/s; | reuses heap buffers to avoid GC latency spikes) v +---------+ Indexed SQL Joins (bookings + hotels; EXISTS on payments) | booking | -------------------------> [Postgres Primary] +---------+ | | Transactional outbox row v [Kafka: "booking-events" (Protobuf)] | +----------------+--------+--------+----------------+ v v v v [email] [loyalty] [search-index] [analytics] * Inside every process: bounded per-thread Stacks + GC-monitored shared Heap * Every code change: CI tests -> single immutable image -> Canary CD rolloutDecision Choose Option A when... Choose Option B when... Stack vs. Heap Small, fixed-size data confined to a single function call Large, dynamically sized, or long-lived data shared across calls/threads Protobuf vs. JSON High-QPS internal RPCs & Kafka events needing strict schemas and low CPU Browser clients, public third-party APIs, and easy curldebugginggRPC vs. REST Internal microservice calls needing codegen types, streaming, and propagated deadlines Public edge APIs needing native browser support and HTTP GETcachingKafka vs. RPC / Queue One event fans out to multiple independent readers or requires historical replay Caller needs an immediate synchronous reply, or tasks need per-item priority/retry queues SQL Join vs. Denormalize Normalized single-service OLTP queries backed by foreign-key indexes 5,000+ req/s read-heavy endpoints or data owned by separate microservices Continuous Delivery vs. Deployment Regulated/high-risk changes requiring human release sign-off High test coverage + automated canary rollback allow hands-free production pushes
Intuition & how it works
Picture these seven concepts not as random flashcards, but as the exact path a single customer request takes through a busy hotel-booking kitchen. Each chef keeps a tiny personal scratchpad clipped to their apron (stack memory) for the current step and throws the slip away the instant that step finishes, while ingredients that must outlive one step sit on labeled shelves in a shared walk-in pantry (heap memory). At the front counter, guests read full English menus (JSON over REST), whereas back-of-house stations pass compact numbered shorthand tickets (Protobuf) over multi-line direct intercoms with countdown timers (gRPC). When a chef needs a guest's reservation paired with the room's floor plan from two filing cabinets in the same office, they cross-reference both drawers at once (SQL join using Structured Query Language). Once the booking is confirmed, instead of running around interrupting four departments, the chef pins one notice to an ordered bulletin board (Kafka event streaming) so Email, Loyalty, Search, and Analytics each read it at their own speed. Finally, every change to kitchen procedures runs through an automated safety checklist and a one-table taste test before rolling out kitchen-wide (CI/CD—Continuous Integration / Continuous Delivery or Deployment).
Why does giving isolated textbook definitions fall short in an interview? Every tool here fixes one bottleneck while introducing a new failure mode. Using verbose JSON or multi-table SQL joins on a 5,000-requests/s search endpoint wastes CPU and latency; conversely, forcing browsers to speak raw gRPC or publishing to Kafka when a user is waiting synchronously to see whether a room is still free makes the system brittle and over-complicated.
Trace one guest's journey—searching for 3 Madrid hotels and confirming a $200 room—to see every piece working together:
1. Search (5,000 req/s hot path): The browser sends a GET request and receives JSON. Inside the gateway, search fans out via gRPC + Protobuf with a 300 ms propagated deadline to pricing and availability (shrinking each offer from 89 bytes of JSON to 20 bytes of binary Protobuf) and reads a denormalized hotel index with zero SQL joins while keeping temporary variables short-lived to avoid heap garbage-collection pauses.
2. Confirm booking (50 req/s transactional path): booking runs SQL against Postgres, using an indexed INNER JOIN between bookings and hotels to fetch confirmation details in one round trip (instead of N+1 queries) and writes both the reservation and an outbox event atomically.
3. Asynchronous fan-out: A relay publishes the Protobuf BookingConfirmed event to Kafka, where four independent consumer groups (email, loyalty, search-index, analytics) process it at their own pace without slowing down the guest's checkout screen.
4. Safe daily shipping: When an engineer adds a breakfast_included field to .proto, CI verifies backward compatibility and integration tests in under 15 minutes, and CD shifts 5% canary traffic to the new container image with automatic rollback if error rates rise.
Key trade-offs
- Stack vs. heap memory: instant automatic cleanup vs. flexible lifetime and size. Allocating on the stack moves a CPU pointer in one instruction and frees memory automatically on return, yet stack space is small (~1–8 MB per OS thread), private to one thread, and vanishes when the function exits. The heap holds large, dynamically sized, or cross-thread objects, paying for that flexibility with allocator overhead, memory leaks or garbage collection (GC) pauses, and synchronization costs.
- Protobuf vs. JSON: wire/CPU efficiency and strict contracts vs. universal readability. Raw Protobuf is roughly 4x smaller than compact JSON (20 bytes vs. 89 bytes per hotel offer), though gzip compression narrows the wire-size gap to ~20% (~0.60 KB vs. ~0.75 KB for 50 offers) at the price of compression CPU on both ends. Protobuf's decisive advantage inside backends is its enforced
.protoschema, generated types, and faster parsing; JSON wins at public edges where browsers,curl, and third-party developers value human readability. - gRPC vs. legacy RPC and REST: strongly typed multiplexed calls vs. web ecosystem compatibility. Compared with legacy RPC (Java-only RMI or heavyweight XML SOAP) and internal REST, gRPC delivers multi-language code generation, bidirectional streaming, and automatic deadline propagation over HTTP/2. In return, you give up native browser
fetch()support (requiring agRPC-Webproxy), standard HTTPGETCDN caching, and naive Layer-4 TCP load balancing. - Event streaming (Kafka) vs. synchronous RPC vs. traditional task queues. Synchronous RPC gives an immediate answer ("room locked!") while coupling caller uptime to callee uptime. Kafka decouples availability, fans one event out to many independent consumer groups, and supports multi-day replay, trading immediate consistency for eventual consistency and broker operational cost. Traditional queues (SQS, RabbitMQ) beat Kafka when workers need per-message priorities, arbitrary retry delays, or out-of-order task acknowledgments rather than ordered partition logs.
- SQL joins vs. denormalization. Normalized tables queried with indexed SQL joins eliminate duplicate data updates and avoid N+1 network round trips inside a single service's database, at the cost of per-query join CPU and cross-table lookups. Denormalization (storing pre-joined copies in a search index kept fresh via Kafka events) makes 5,000 req/s reads instantaneous, trading storage duplication and brief eventual-consistency lag.
- Continuous Delivery vs. Continuous Deployment. Continuous Delivery stops at a human approval button before production, fitting regulated financial or mobile releases. Continuous Deployment pushes every passing commit straight into production, maximizing engineering velocity while requiring high-signal automated tests, canary rollouts (sending 5% of live traffic to the new version first), automated rollback, and backward-compatible database migrations.
Common mistakes
- Stating "primitives always live on the stack and objects always live on the heap" as a universal law—in C/C++/Rust structs live on the stack by default, Go places structs on the stack whenever escape analysis proves they do not outlive the function, and Python stores even small integers as heap objects.
- Confusing the OS/runtime memory heap with the binary heap priority-queue data structure.
- Returning a pointer to a stack-allocated local variable in C/C++ (creating a dangling pointer) or parsing untrusted deeply nested JSON recursively until an attacker triggers a stack overflow.
- Reusing or renumbering deleted Protobuf field tags, causing older deployed services to silently decode the new field's bytes into the wrong type; always mark removed tag numbers
reserved. - Sending 64-bit integer IDs as JSON numbers to JavaScript browsers, which use IEEE-754 doubles and silently corrupt integers larger than
2^53 - 1(9,007,199,254,740,991); serialize 64-bit IDs as JSON strings at the edge. - Treating gRPC calls like infallible local function calls without deadlines, bounded retries, or Layer 7 (HTTP/2 request-aware) load balancing, leaving one backend pod overloaded on a sticky HTTP/2 TCP connection.
- Using Kafka for synchronous request/response workflows or dual-writing to Postgres and Kafka without a transactional outbox table.
- Falling into three classic SQL join bugs: running N+1 queries in a
forloop instead of one join, writingCOUNT(*)instead ofCOUNT(right_table.id)after aLEFT JOIN, or computingSUM(parent.amount)across a one-to-manyJOINinstead of filtering withWHERE EXISTS (...). - Reaching directly across microservice databases with a SQL join, tightly coupling two teams' schemas and preventing independent deployments.
- Saying "we do CI" when feature branches live unmerged for three weeks merely because Jenkins runs on them—true Continuous Integration requires merging small, green changes into
mainat least daily.
Follow-up questions
- How can you modify a Protobuf schema in production without breaking older deployed services? Only add new fields using brand-new tag numbers, never change an existing field's tag number or incompatible wire type, and mark any removed field number and name
reservedin the.protofile so a teammate never reuses it months later. Protobuf decoders safely skip unknown tag numbers (forward compatibility for old readers) and populate sensible defaults when expected tags are absent (backward compatibility for new readers). Enforce these rules automatically in CI using tools likebuf breakingor a Kafka Schema Registry compatibility gate. - Why do gRPC backends suffer uneven traffic behind a Layer-4 TCP load balancer, and how do you fix it? gRPC multiplexes hundreds of concurrent RPC calls over a single persistent HTTP/2 TCP connection, and an L4 load balancer chooses a target pod only once when that TCP connection is established. If two pods existed during a traffic ramp-up and Kubernetes scales the deployment up to ten pods, existing clients stay pinned to the original two pods while the eight new pods sit idle! Fix this either by routing through a Layer-7 HTTP/2 proxy (such as Envoy or a service mesh) that load-balances each individual HTTP/2 stream, enabling gRPC client-side round-robin load balancing via headless DNS, or configuring
MAX_CONNECTION_AGEon servers to force periodic reconnects. - How do you safely rename or remove a database column when Continuous Deployment rolls pods out gradually? Never run
ALTER TABLE ... RENAME COLUMNorDROP COLUMNin lockstep with a code deploy, because during a 15-minute canary rollout both old pods and new pods query the exact same Postgres database simultaneously! Instead, use the expand-and-contract pattern across separate commits: first add the new nullable column, second deploy code that dual-writes both columns while still reading the old one, third backfill existing rows in small batches, fourth switch reads to the new column, and finally stop writing and drop the old column once zero old pods remain.
Follow-up questions
- How can you modify a Protobuf schema in production without breaking older deployed services?
- Why do gRPC backends suffer uneven traffic behind a Layer-4 TCP load balancer, and how do you fix it?
- How do you safely rename or remove a database column when Continuous Deployment rolls pods out gradually?
Similar questions
- Real-Time Log and Metrics Telemetry Platform
- Designing a Safe Ticket-to-PR Agent Pipeline
- Payment Coverage per Booking
- Anagram Buckets, One-Swap Digit Maximization, and Hotel Review Ranking
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor