Skip to content
notes.vinhnq.com

Search

Review

Collected from every post: trade-offs, edge cases, interview questions and things worth remembering.

Edge caseMid(int) amount * 26000 casts before multiplying and drops the centsA cast binds tighter than multiplication, so this means ((int) amount) 26000: 12.99 USD becomes 12 and the customer pays 25,740 VND too little; 0.99 USD becomes 0 dong. Writing (int) (amount 26000) still leaves two bugs: int overflows at around 82,600 USD (99,999 USD comes out negative), and it truncates instead of rou

A cast binds tighter than multiplication, so this means ((int) amount) * 26000: 12.99 USD becomes 12 and the customer pays 25,740 VND too little; 0.99 USD becomes 0 dong. Writing (int) (amount * 26000) still leaves two bugs: int overflows at around 82,600 USD (99,999 USD comes out negative), and it truncates instead of rounding. Money conversion tests need fractional amounts, amounts below 1, and large amounts.

Read in post: Adapter and Factory
Edge caseMiddouble for money: 19.99 × 26000 is 519739.99999999994double stores binary fractions, so 19.99 isn't exact; multiply and truncate and you get 519,739 instead of 519,740. One dong off per transaction is a reconciliation mismatch. Money is a BigDecimal built from a string (new BigDecimal("19.99"), not new BigDecimal(19.99)) or an integer in minor units (cents, dong), rounde

double stores binary fractions, so 19.99 isn't exact; multiply and truncate and you get 519,739 instead of 519,740. One dong off per transaction is a reconciliation mismatch. Money is a BigDecimal built from a string (new BigDecimal("19.99"), not new BigDecimal(19.99)) or an integer in minor units (cents, dong), rounded with setScale and an agreed RoundingMode.

Read in post: Adapter and Factory
TILJuniorCurrency.getDefaultFractionDigits tells you how many decimals a currency hasjava.util.Currency knows the standard number of decimals for each ISO 4217 code: VND 0, JPY 0, USD 2, BHD (Bahraini dinar) 3. Use it to validate input (1.5 VND is bad data) and to round, instead of hard-coding setScale(2). A gateway may have its own convention (some expect amounts multiplied by 100 even for VND); the a

java.util.Currency knows the standard number of decimals for each ISO 4217 code: VND 0, JPY 0, USD 2, BHD (Bahraini dinar) 3. Use it to validate input (1.5 VND is bad data) and to round, instead of hard-coding setScale(2). A gateway may have its own convention (some expect amounts multiplied by 100 even for VND); the adapter is where that convention lives.

Read in post: Adapter and Factory
Trade-offSeniorRounding during currency conversion: who absorbs the fractionHALFUP: what users expect, common for display and charging. Biased upwards when you add up many lines. HALFEVEN (banker's rounding, ties go to the even digit): no average bias, common in accounting and aggregate reports. DOWN/FLOOR: never charges more than the customer agreed to; the business absorbs the fraction. More
  • HALF_UP: what users expect, common for display and charging. Biased upwards when you add up many lines.
  • HALF_EVEN (banker's rounding, ties go to the even digit): no average bias, common in accounting and aggregate reports.
  • DOWN/FLOOR: never charges more than the customer agreed to; the business absorbs the fraction.

More important than the mode: convert once, and store the original amount, the converted amount, the rate and when it was fetched on the transaction. Recomputing a refund at today's rate is a classic source of mismatches.

Read in post: Adapter and Factory
Edge caseMidA default branch in a switch on an enum hides new typesThe sample's BookingFactory reads case APARTMENT - ...; case VILLA - ...; default - baseBookingService;. Add RESORT to the enum and it still compiles; resorts silently take the default path. Drop the default: a switch expression over an enum (Java 14+) must cover every constant, so forgetting the factory is the compile

The sample's BookingFactory reads case APARTMENT -> ...; case VILLA -> ...; default -> baseBookingService;. Add RESORT to the enum and it still compiles; resorts silently take the default path. Drop the default: a switch expression over an enum (Java 14+) must cover every constant, so forgetting the factory is the compile error the switch expression does not cover all possible input values. Keep default only when "every other type takes the common path" is a documented business decision.

Read in post: Adapter and Factory
Trade-offMidA switch-based simple factory or a Map registry from type to beanA switch expression on an enum: every choice in one place, coverage enforced by the compiler. But the factory must inject every implementation, and a new type means editing it. A registry from List<Handler: a new type is a new bean and the factory doesn't change; misconfiguration fails at startup. But to find who handl
  • A switch expression on an enum: every choice in one place, coverage enforced by the compiler. But the factory must inject every implementation, and a new type means editing it.
  • A registry from List<Handler>: a new type is a new bean and the factory doesn't change; misconfiguration fails at startup. But to find who handles type X you have to look for the class whose type() returns X.

Under five types that rarely change: switch. Many types, many teams, or implementations in other modules: registry.

Read in post: Adapter and Factory
Edge caseMidCalling a simple factory an Abstract Factory sends readers looking for a family that doesn't existA pattern name is documentation: a reader who sees "Abstract Factory" looks for an interface with several creation methods and families of implementations. The repo's BookingFactory just picks an existing bean, so it's a simple factory or a selector; clearer names are BookingServiceSelector or BookingHandlerRegistry. I

A pattern name is documentation: a reader who sees "Abstract Factory" looks for an interface with several creation methods and families of implementations. The repo's BookingFactory just picks an existing bean, so it's a simple factory or a selector; clearer names are BookingServiceSelector or BookingHandlerRegistry. It doesn't even "create" anything: Spring created the beans.

Read in post: Adapter and Factory
Edge caseMid@RequiredArgsConstructor only injects final fieldsForget final and the field isn't in the constructor, Spring doesn't inject it, the app still starts, and a NullPointerException appears on the first request that uses it. Prevention: Always declare dependencies as private final. Turn on the IDE inspection or an ArchUnit rule "fields in a @Service must be final". Have a

Forget final and the field isn't in the constructor, Spring doesn't inject it, the app still starts, and a NullPointerException appears on the first request that uses it. Prevention:

  • Always declare dependencies as private final.
  • Turn on the IDE inspection or an ArchUnit rule "fields in a @Service must be final".
  • Have at least one context-starting test (@SpringBootTest or a slice test) that calls through each main endpoint.
Read in post: Adapter and Factory
Edge caseSeniorInjecting by a parent class whose subclasses are also beans relies on parameter namesWhen several beans match, Spring tries @Primary, then @Qualifier, then matches the constructor parameter name against bean names (baseBookingService). That last step only works if the class was compiled with -parameters: Spring Framework 6.1 dropped reading names from debug info. Spring Boot's Maven/Gradle plugins turn

When several beans match, Spring tries @Primary, then @Qualifier, then matches the constructor parameter name against bean names (baseBookingService). That last step only works if the class was compiled with -parameters: Spring Framework 6.1 dropped reading names from debug info. Spring Boot's Maven/Gradle plugins turn the flag on for you, but a module built some other way gets NoUniqueBeanDefinitionException. Don't let wiring depend on variable names: inject by interface into a registry (section 2.2), or add an explicit @Qualifier.

Read in post: Adapter and Factory
InterviewJuniorWhat is the Adapter pattern? Give an example.

An adapter wraps a class with a mismatched interface (often a third-party SDK) so it looks like the interface your code needs.

Example: your service uses a PaymentGateway taking Money, while the SDK takes an integer amount in VND and returns string codes; the adapter converts the units, calls the SDK and translates the codes into your own result type.

Read in post: Adapter and Factory
InterviewJuniorHow does Factory Method differ from Abstract Factory?

Factory Method creates one object and lets a subclass choose its type; Abstract Factory creates a family of related objects that must match.

Factory Method is one method (often abstract). Abstract Factory is an interface with several creation methods, each implementation producing one family. A simple factory is just a switch function picking an implementation; it isn't a GoF pattern.

Read in post: Adapter and Factory
InterviewMidWhy not use double for money? What instead?

Because double is binary floating point and 19.99 isn't exact; use BigDecimal built from strings, or a long in minor units.

Multiply and truncate and you get 519,739 instead of 519,740. Round explicitly with an agreed RoundingMode and the currency's number of decimals.

Read in post: Adapter and Factory
InterviewMidWhat happens with @RequiredArgsConstructor and a non-final field?

That field isn't in the constructor Lombok generates, so Spring doesn't inject it and it stays null.

The app starts fine; the NPE appears only when code using the field runs. Prevent it with private final for all dependencies, static rules (IDE inspections, ArchUnit), and a context-starting test that exercises the main flows.

Read in post: Adapter and Factory
InterviewMidA factory picks an implementation with a switch that has a default branch. What's your review comment?

Drop the default, because it makes any new enum value silently take the default path.

Without default, the switch expression must cover every constant: a new type without a factory case becomes a compile error. Or move to a registry built from List<Handler> that checks for gaps and duplicates at startup. Keep default only if "every other type takes the common path" is a documented business decision.

Read in post: Adapter and Factory
InterviewSeniorA call to the payment gateway times out. What should the adapter return?

An explicit "unknown" state, not a failure, because the money may already have moved.

Treating it as failed and letting the user retry with a new key charges them twice. The order stays pending; the system queries the transaction status with the same idempotency key, accepts the callback (IPN), and a reconciliation job handles orders pending for too long.

Read in post: Adapter and Factory
InterviewSeniorHow do Adapter, Facade, Decorator and an anti-corruption layer differ?

Adapter changes an interface, Facade simplifies one, Decorator keeps it and adds behaviour, and an anti-corruption layer is a whole boundary layer that keeps an outside model out.

Facade sits in front of a complex subsystem. Decorator adds retry, logging, caching. An anti-corruption layer lives at a bounded context's edge, made of adapters and translators, so outside error codes, concepts and units don't leak into your domain.

Read in post: Adapter and Factory
Trade-offSeniorADRs in the repo or on a wikiIn the repo (docs/adr/0004-admin-levels.md, in the same PR as the code): reviewed like code, with git history, sitting next to what it explains. Cons: harder for non-technical people to find; decisions spanning several repos need a home. On a wiki (Confluence, Notion): easy for product and business to read and comment
  • In the repo (docs/adr/0004-admin-levels.md, in the same PR as the code): reviewed like code, with git history, sitting next to what it explains. Cons: harder for non-technical people to find; decisions spanning several repos need a home.
  • On a wiki (Confluence, Notion): easy for product and business to read and comment on. Cons: detached from the code, nobody knows if it's still true, links die when the tool changes.
  • What usually works: a service's ADRs live in that service's repo; company-level decisions live in a dedicated architecture repo rendered to an internal site.
Read in post: Architecture docs part 2
Edge caseMidEditing an old ADR erases the trail of reasoningAn ADR is a historical record: once Accepted, you don't rewrite its decision to match the present. When you change your mind, write a new ADR marked Supersedes ADR-004 and set the old one to Superseded by ADR-011. Editing the old ADR in place deletes the answer to "why did we do it that way back then?", which is exactl

An ADR is a historical record: once Accepted, you don't rewrite its decision to match the present. When you change your mind, write a new ADR marked Supersedes ADR-004 and set the old one to Superseded by ADR-011. Editing the old ADR in place deletes the answer to "why did we do it that way back then?", which is exactly what ADRs exist to keep.

And don't write an ADR without an Alternatives section: with no rejected option there's no decision, only a description.

Read in post: Architecture docs part 2
Edge caseSeniorA quality requirement without measurement conditions can't be verified"1,500 TPS" on its own isn't a requirement yet. A system doing 1,500 TPS for 10 seconds against an empty table with p99 = 5 seconds still "passes" to the letter. The minimum: load type (reads or writes, payload size), load level, how long it's sustained, latency as a percentile (not an average), error rate, data volume

"1,500 TPS" on its own isn't a requirement yet. A system doing 1,500 TPS for 10 seconds against an empty table with p99 = 5 seconds still "passes" to the letter.

The minimum: load type (reads or writes, payload size), load level, how long it's sustained, latency as a percentile (not an average), error rate, data volume and the measurement infrastructure. When you get a vague requirement ("fast", "handles load well"), ask until you have those numbers.

Read in post: Architecture docs part 2
Edge caseMidToo much coordinate precision is waste, too little puts you in the wrong placeThe original declares latitude as DECIMAL(16,14) and longitude as DECIMAL(17,14): fourteen decimal places of a degree ≈ 1 nanometre, while phone GPS is off by a few metres. Quick reference: 4 decimals ≈ 11 m, 5 ≈ 1.1 m, 6 ≈ 0.11 m. NUMERIC(9,6) (or (10,7)) is plenty for addresses. On the other hand, a 4-byte FLOAT keep

The original declares latitude as DECIMAL(16,14) and longitude as DECIMAL(17,14): fourteen decimal places of a degree ≈ 1 nanometre, while phone GPS is off by a few metres. Quick reference: 4 decimals ≈ 11 m, 5 ≈ 1.1 m, 6 ≈ 0.11 m. NUMERIC(9,6) (or (10,7)) is plenty for addresses.

On the other hand, a 4-byte FLOAT keeps only ~7 significant digits, so at longitude 105.xx the error reaches a few metres. For "within radius" queries, use PostGIS's geography(Point, 4326) instead of two number columns.

In the same spirit: an ISO 3166-1 alpha-2 country_code is exactly 2 characters, and the original VARCHAR(4) lets junk through; MySQL's DATETIME(3) stores no time zone, so on PostgreSQL use timestamptz.

Read in post: Architecture docs part 2
Trade-offSeniorVerify addresses against master data synchronously or asynchronouslySynchronous, fail-closed (block on error): call master data within the request; on error or timeout, block onboarding. The data is always clean, but onboarding's uptime depends on master data, and the call adds latency. Synchronous, fail-open (let through on error): a short timeout (say 800 ms); on failure store UNVERI
  • Synchronous, fail-closed (block on error): call master data within the request; on error or timeout, block onboarding. The data is always clean, but onboarding's uptime depends on master data, and the call adds latency.
  • Synchronous, fail-open (let through on error): a short timeout (say 800 ms); on failure store UNVERIFIED and continue. You need a re-verification job and rules for unverified addresses (for example, no card issuance yet).
  • Asynchronous: store UNVERIFIED, a worker verifies and publishes AddressVerified. The fastest and best at isolating failures; the UI must handle a "verifying" state and users may have to come back to fix things.

This is a business decision: ask product what a wrong address costs, then record it in an ADR.

Read in post: Architecture docs part 2
InterviewJuniorWhat is an ADR and what does it contain?

A short note about one architectural decision, so later readers understand why the system is the way it is.

It contains: title, status, context (the problem and constraints), the decision, the alternatives considered, and both positive and negative consequences.

Read in post: Architecture docs part 2
InterviewJuniorWhat is a risk and technical-debt register for?

It records what the team knows isn't right yet, turning "everyone knows, nobody acts" into owned work.

It covers risks (an undrilled failover, latency above target) and technical debt (shortcuts taken), with priority, who is affected, how to fix it, status, an owner and a review date. "We accept the risk" becomes a decision someone signed off.

Read in post: Architecture docs part 2
InterviewMidWhy is "the system must handle 1,500 TPS" not yet a good requirement?

Because without measurement conditions it can't be verified.

It's missing the request type, payload, how long it's sustained, a percentile latency threshold, error rate, data volume and the measurement environment. A system doing 1,500 TPS for 10 seconds with a multi-second p99 still "passes". Write it as a quality scenario with a concrete response measure.

Read in post: Architecture docs part 2
InterviewMidWhat do you do when you change your mind about a decision that already has an ADR?

Write a new ADR marked Supersedes the old one, set the old one to Superseded, and leave its content untouched.

That way the history of reasoning survives: anyone can see what was decided back then, why, and why it later changed.

Read in post: Architecture docs part 2
InterviewSeniorIn what order do you present a solution design to reviewers?

From the problem and requirements to the decisions, then risks and open questions; reviewers should spend their time on requirements and decisions, not class names.

  1. Problem, goals, scope and out of scope, constraints.
  2. Measurable quality requirements, because they drive the architecture.
  3. Context, containers, runtime views for the main use cases including failure paths, deployment.
  4. ADRs with the rejected alternatives and trade-offs.
  5. Risks, technical debt, and the open questions I need reviewers to decide.
Read in post: Architecture docs part 2
InterviewSeniorGive an example of a quality requirement that changes the architecture.

"Payment creation p99 ≤ 300 ms at 1,500 TPS" when the synchronous fraud-check call alone takes 200 ms at p99.

That requirement forces the fraud check to go async (let it through, check afterwards, reverse if needed) or a latency budget per hop. Similarly, "RPO = 0" forces synchronous replication, at the cost of higher write latency. Quality requirements are what choose between options, so they must be settled before the design.

Read in post: Architecture docs part 2
Trade-offSeniorTransparent huge pages: on for the JVM, off for Redis and many databasesTHP (transparent huge pages): the kernel merges contiguous 4 KB pages into 2 MB pages on its own. Large JVM heap: fewer TLB misses, from a few percent to over ten percent faster for memory-heavy workloads. Enable it just for the JVM with -XX:+UseTransparentHugePages (when THP is in madvise mode). Redis, MongoDB, many d

THP (transparent huge pages): the kernel merges contiguous 4 KB pages into 2 MB pages on its own.

  • Large JVM heap: fewer TLB misses, from a few percent to over ten percent faster for memory-heavy workloads. Enable it just for the JVM with -XX:+UseTransparentHugePages (when THP is in madvise mode).
  • Redis, MongoDB, many databases: recommend turning it off. Background merging causes unpredictable stalls, and with copy-on-write after fork() every write copies 2 MB instead of 4 KB.
  • The safe default on shared servers is madvise: only processes that ask get huge pages.
Read in post: Virtual memory, page cache, swap and the JVM in containers
TILSenior-XX:+AlwaysPreTouch pays the heap's page faults up frontThe heap only becomes real RAM when first touched, so latency is higher for the first minutes after startup. -XX:+AlwaysPreTouch makes the JVM touch the whole heap at startup: a few seconds slower for a heap of tens of GB, but RSS equals the heap from the start and there are no page faults while serving. If the contain

The heap only becomes real RAM when first touched, so latency is higher for the first minutes after startup. -XX:+AlwaysPreTouch makes the JVM touch the whole heap at startup: a few seconds slower for a heap of tens of GB, but RSS equals the heap from the start and there are no page faults while serving. If the container lacks RAM, it dies at startup instead of at peak traffic.

Read in post: Virtual memory, page cache, swap and the JVM in containers
Edge caseMidVirtual memory is not "RAM plus swap"On x86-64 each process has up to 128 TB of virtual addresses, far more than RAM plus swap. A JVM with -Xmx1g usually has a VSZ (virtual size) of several GB because it reserves space for the heap, metaspace, code cache and every thread's stack, but its RSS (memory actually in use) is a few hundred MB. What RAM plus swap

On x86-64 each process has up to 128 TB of virtual addresses, far more than RAM plus swap. A JVM with -Xmx1g usually has a VSZ (virtual size) of several GB because it reserves space for the heap, metaspace, code cache and every thread's stack, but its RSS (memory actually in use) is a few hundred MB.

What RAM plus swap really limits is memory that has been touched and can't be dropped. A virtual page can come from RAM, swap, or a file on disk (program code, mmap'd files). Don't panic over a big VSZ; watch RSS, and in a container the working set.

Read in post: Virtual memory, page cache, swap and the JVM in containers
Edge caseSeniorSwap and a garbage collector are the worst possible pairSwap suits rarely used data, like the pages of a daemon that sleeps all day. A JVM heap is the opposite: every GC (especially a full GC or the marking phase) walks most of it. If part of the heap was swapped out, GC triggers thousands of major faults, a 50 ms pause becomes seconds, and the service looks hung while stil

Swap suits rarely used data, like the pages of a daemon that sleeps all day. A JVM heap is the opposite: every GC (especially a full GC or the marking phase) walks most of it. If part of the heap was swapped out, GC triggers thousands of major faults, a 50 ms pause becomes seconds, and the service looks hung while still alive.

That's why JVM servers usually disable swap or set vm.swappiness very low, and Kubernetes runs nodes without swap by default. If you want headroom, put it in RAM and size the heap correctly.

Read in post: Virtual memory, page cache, swap and the JVM in containers
Trade-offSeniorWhat fraction of the memory limit should the heap getThe default 25% is safe but wasteful: a 2 GB pod gets a 512 MB heap and most of the RAM sits idle. MaxRAMPercentage=75 is a common choice for an ordinary web service: the other 25% covers metaspace, code cache, a few hundred threads and GC. It isn't enough when the app uses a lot of direct memory (Netty, gRPC, a Kafka
  • The default 25% is safe but wasteful: a 2 GB pod gets a 512 MB heap and most of the RAM sits idle.
  • MaxRAMPercentage=75 is a common choice for an ordinary web service: the other 25% covers metaspace, code cache, a few hundred threads and GC. It isn't enough when the app uses a lot of direct memory (Netty, gRPC, a Kafka client with big batches) or very many threads.
  • A fixed -Xmx (say -Xmx1g with a 1.5 GB limit) is clearer once you've measured, but you must change both places whenever the limit changes.

The right approach is to measure: run real load, look at RSS or the working set and NMT, and set the limit to what you measured plus 20–30%. Add -XX:+ExitOnOutOfMemoryError so the JVM dies and gets restarted instead of limping on after an OOM, and cap direct memory with -XX:MaxDirectMemorySize if the app uses a lot of it.

Read in post: Virtual memory, page cache, swap and the JVM in containers
Edge caseSeniorThe page cache counts toward a container's memoryIn a cgroup, page cache read or written by processes in the container is charged to the container. A service writing logs or large files sees containermemoryusagebytes creep up to the limit while the heap is flat, and people suspect a leak. The kernel reclaims clean page cache before an OOM kill, so the right number to

In a cgroup, page cache read or written by processes in the container is charged to the container. A service writing logs or large files sees container_memory_usage_bytes creep up to the limit while the heap is flat, and people suspect a leak.

The kernel reclaims clean page cache before an OOM kill, so the right number to alert on is the working set (container_memory_working_set_bytes = usage minus inactive file), which is also what the kubelet uses to decide on evictions. The scarier exceptions: dirty pages not yet written and tmpfs (emptyDir with medium: Memory) can't be dropped and can push a container to OOMKilled.

Read in post: Virtual memory, page cache, swap and the JVM in containers
TILSeniorLongAdder avoids false sharing with @ContendedLongAdder splits a counter into several cells (Cell); each thread adds to its own cell, and reading sums them all. The Cell class is annotated @jdk.internal.vm.annotation.Contended, so the JVM pads it (128 bytes by default) to keep cells off a shared cache line. Application code can use the annotation too, but needs --

LongAdder splits a counter into several cells (Cell); each thread adds to its own cell, and reading sums them all. The Cell class is annotated @jdk.internal.vm.annotation.Contended, so the JVM pads it (128 bytes by default) to keep cells off a shared cache line.

Application code can use the annotation too, but needs --add-exports java.base/jdk.internal.vm.annotation=ALL-UNNAMED and -XX:-RestrictContended. In practice, using LongAdder instead of AtomicLong for a metric counter written by many threads is usually enough.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewJuniorWhat is virtual memory and what problem does it solve?

Every process sees its own virtual address space; the MMU in the CPU translates it to physical addresses through page tables managed by the kernel.

It stops processes from overwriting each other's memory, allows per-page read/write/execute permissions, and enables lazy allocation, shared pages (libraries, copy-on-write) and mapping files into memory.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewJuniorfree on Linux shows very little free memory. Should you worry?

Usually not: Linux uses idle RAM as page cache and drops it when processes need memory. Read the available column, not free.

Worry only when available is low, swap-in/out is constant (si, so in vmstat) or major faults are rising.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewJuniorWhat is a page fault? How do minor and major faults differ?

A page fault happens when a process touches a virtual page that has no physical frame or isn't allowed. A minor fault needs no disk; a major fault needs a disk read.

Minor: a fresh page, or the page is already in the page cache, costing microseconds. Major: a swapped-out page or an unloaded mmap'd file, costing tens of µs to ms. Constant major faults mean the machine is short on RAM.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewMidWhy is a JVM's RSS larger than -Xmx?

The heap is only one part; a Spring Boot service typically has 300–600 MB outside the heap.

The JVM also has metaspace, the code cache, a stack per thread, direct buffers and mmap'd regions, GC data structures, and malloc memory from native libraries. Measure it with -XX:NativeMemoryTracking=summary and jcmd <pid> VM.native_memory summary.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewMidHow is an OutOfMemoryError different from a pod being OOMKilled?

OutOfMemoryError is the JVM reporting a full heap; OOMKilled is the kernel killing the process because the cgroup's RSS went over the limit.

OutOfMemoryError: Java heap space comes with a stack trace and possibly a heap dump. OOMKilled (exit 137) is a SIGKILL, so there's no log or dump. The first is fixed by finding a heap leak; the second by shrinking the heap relative to the limit or finding what's growing off-heap.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewMidWhy shouldn't a JVM use swap?

GC walks most of the heap; heap pages in swap turn every GC cycle into a burst of major faults, and pauses of tens of ms become seconds.

Disable swap or set vm.swappiness very low, and size the heap so the whole process fits in RAM.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewMidWhy don't PostgreSQL and Kafka use all the RAM for their own caches?

Because they rely on the OS page cache: it survives process restarts, puts no pressure on a GC, and the kernel manages eviction.

PostgreSQL sets shared_buffers to about 25% of RAM and leaves the rest to the page cache; Kafka reads and writes its log through the page cache and sends data to consumers with zero-copy from it.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewSeniorHow do you size the memory limit for a Java service on Kubernetes?

Measure, don't guess: heap from live data, off-heap from NMT, add them up and add 20–30%.

Run real load, use the live data after a full GC to choose the heap (about 2–3×), and measure off-heap with NMT (metaspace, code cache, threads, direct buffers, GC). Set -Xmx or MaxRAMPercentage accordingly, cap MaxDirectMemorySize, enable ExitOnOutOfMemoryError, and set the request equal to the limit. Monitor the working set, not usage (usage includes page cache).

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewSeniorWhat is false sharing, and when should you care?

Two threads writing different variables on the same cache line keep invalidating each other's copy; it only matters for variables written very often by many threads.

Cache coherence works per cache line (64 bytes, or 128 on some ARM chips), so it's as slow as real contention; in my test on an Apple M4 it was about 3× slower. Examples worth caring about: counters, ring buffer cursors. Fixes: padding, @Contended, or just LongAdder.

Read in post: Virtual memory, page cache, swap and the JVM in containers
InterviewSeniorCPU cache coherence keeps caches consistent, so why does Java still need volatile?

Coherence only makes cores agree on a cache line once the value has reached the cache; volatile is what creates happens-before.

Before that the value can sit in a core's store buffer or a register, or be reordered by the JIT or the CPU. volatile and the other synchronization tools insert memory barriers and stop the JIT from optimizing reads away, creating the happens-before edges the Java Memory Model defines, so the code is correct on every CPU architecture, including ARM with its weaker memory model.

Read in post: Virtual memory, page cache, swap and the JVM in containers
Edge caseSeniorInnoDB's adaptive hash index can become a bottleneckAHI speeds up repeated point lookups, but every change to those pages must also update the AHI, which is guarded by latches (lightweight in-memory locks) partitioned by innodbadaptivehashindexparts. Under heavy concurrent writes, big JOINs or LIKE scans touching many pages, waiting on AHI latches can become the bottlen

AHI speeds up repeated point lookups, but every change to those pages must also update the AHI, which is guarded by latches (lightweight in-memory locks) partitioned by innodb_adaptive_hash_index_parts. Under heavy concurrent writes, big JOINs or LIKE scans touching many pages, waiting on AHI latches can become the bottleneck, and dropping a large table has to purge its AHI entries. Since MySQL 8.4 innodb_adaptive_hash_index defaults to OFF (confirmed in the lab on 8.4.11); on 5.7 and 8.0 it defaults to ON. Only turn it on when you can measure a benefit under real load.

Read in post: Index types beyond the B-tree
Edge caseMid'x' = ANY(tags) cannot use a GIN index on an arrayGIN only serves the operators in its operator class (the set of operators an index supports); for arrays those are @, <@, && and =. 'tag49' = ANY(tags) returns the same rows as tags @ ARRAY['tag49'], but the planner won't rewrite it: 18 ms versus 3.6 ms. With JPA/Hibernate or jOOQ, check the generated SQL; if the ORM c

GIN only serves the operators in its operator class (the set of operators an index supports); for arrays those are @>, <@, && and =. 'tag49' = ANY(tags) returns the same rows as tags @> ARRAY['tag49'], but the planner won't rewrite it: 18 ms versus 3.6 ms. With JPA/Hibernate or jOOQ, check the generated SQL; if the ORM can't produce the operator, use a native query with tags @> CAST(:tags AS text[]).

Read in post: Index types beyond the B-tree
Trade-offSeniorGIN on the whole jsonb column vs an expression index on one keyGIN jsonbpathops on the whole column: one index serves @ for every key, including keys added later. The price: containment only (no ranges, no sorting), slower writes, and fairly rough selectivity estimates for @. Expression B-tree on one key: small, cheap to write, supports =, ranges and ORDER BY, with good estimates.
  • GIN jsonb_path_ops on the whole column: one index serves @> for every key, including keys added later. The price: containment only (no ranges, no sorting), slower writes, and fairly rough selectivity estimates for @>.
  • Expression B-tree on one key: small, cheap to write, supports =, ranges and ORDER BY, with good estimates. The price: one index per key, and queries must use exactly the indexed expression, cast included.
  • In practice: keys with hot queries, ranges or sorting become generated columns or expression indexes; GIN is for the flexible attributes users filter on in arbitrary combinations.
Read in post: Index types beyond the B-tree
Edge caseSeniorOne unique token per row bloats a full-text GIN indexGIN stores each distinct lexeme once. If the indexed text contains something nearly unique per row (an order code, a sequence number, a UUID, a URL), every row adds a new key with a one-element posting list. In the lab, titles with a <id suffix produced a 19 MB GIN index on the tsvector of 300,000 rows; without the suf

GIN stores each distinct lexeme once. If the indexed text contains something nearly unique per row (an order code, a sequence number, a UUID, a URL), every row adds a new key with a one-element posting list. In the lab, titles with a #<id> suffix produced a 19 MB GIN index on the tsvector of 300,000 rows; without the suffix it needed 2.5 MB, and index build time dropped from 0.8 s to 0.28 s. Only put text people actually search for into the tsvector; keep identifiers in their own column with a B-tree.

Read in post: Index types beyond the B-tree
Trade-offSeniorGIN fastupdate on or offOn (default): much faster writes, but every query also scans the pending list, and whichever INSERT pushes the list past the limit pays for merging all of it, which shows up as p99 spikes. Off: every write pays the full cost; latency is steady but higher, and reads never scan a pending list. Batch-loaded or moderately
  • On (default): much faster writes, but every query also scans the pending list, and whichever INSERT pushes the list past the limit pays for merging all of it, which shows up as p99 spikes.
  • Off: every write pays the full cost; latency is steady but higher, and reads never scan a pending list.
  • Batch-loaded or moderately written tables: leave it on and let autovacuum clean up regularly. OLTP tables sensitive to p99: lower gin_pending_list_limit for that index or turn fastupdate off, then measure. For a large initial load, build the GIN index after loading (lab: 0.14 s for 300,000 rows).
Read in post: Index types beyond the B-tree
Edge caseSeniorA btree_gist index on a bigint column is skipped when compared with an int literalbtreegist only defines same-type operators (int8 = int8), not the cross-type ones a regular B-tree has (int8 = int4). On the 200,000-row roombooking table, WHERE roomid = 500 AND during && ... (the literal 500 is an int4) puts only during into the Index Cond and filters roomid afterwards: 6.4 ms, 1,999 rows removed. Wr

btree_gist only defines same-type operators (int8 = int8), not the cross-type ones a regular B-tree has (int8 = int4). On the 200,000-row room_booking table, WHERE room_id = 500 AND during && ... (the literal 500 is an int4) puts only during into the Index Cond and filters room_id afterwards: 6.4 ms, 1,999 rows removed. Writing room_id = 500::bigint puts both columns into the Index Cond and turns it into a 0.65 ms Index Only Scan. Through JDBC a Long parameter is sent as bigint, so you usually don't hit this; you do in hand-written SQL, or when an entity maps a bigint column as Integer.

Read in post: Index types beyond the B-tree
Edge caseSeniorStored bitmap indexes are not for OLTP tablesIn an Oracle-style bitmap index one bit maps to one row, but an update locks a whole bitmap segment covering many rows. Two transactions changing the status of two different orders can fight over the same segment, causing lock waits and deadlocks, and every update has to decompress and recompress. Bitmap indexes only f

In an Oracle-style bitmap index one bit maps to one row, but an update locks a whole bitmap segment covering many rows. Two transactions changing the status of two different orders can fight over the same segment, causing lock waits and deadlocks, and every update has to decompress and recompress. Bitmap indexes only fit batch-loaded warehouses. For an orders table that is written continuously, use a partial index on PostgreSQL, a summary counter table, or push reporting to a separate warehouse.

Read in post: Index types beyond the B-tree
Trade-offSeniorB-tree or LSM tree: the three amplificationsWrite amplification (bytes actually written per logical byte): a B-tree writes a whole 8–16 KB page for a small change, plus the WAL; an LSM tree writes sequentially, but every byte is rewritten several times as it moves down the levels (leveled can reach 10–30x). On SSDs, LSM trees usually still win on write throughpu
  • Write amplification (bytes actually written per logical byte): a B-tree writes a whole 8–16 KB page for a small change, plus the WAL; an LSM tree writes sequentially, but every byte is rewritten several times as it moves down the levels (leveled can reach 10–30x). On SSDs, LSM trees usually still win on write throughput thanks to sequential I/O and good compression.
  • Read amplification: a B-tree reads one root-to-leaf path (3–4 pages); an LSM tree may check the memtable and several SSTables, and bloom filters only help point lookups, not range scans.
  • Space amplification: B-trees have partly empty pages (fill factor, bloat); LSM trees keep old versions and tombstones until compaction catches up.
  • Pick an LSM engine (RocksDB, Cassandra/ScyllaDB, MyRocks, TiKV, CockroachDB) when writes dominate: events, logs, time series, counters. Keep B-trees (InnoDB, PostgreSQL) for read-heavy OLTP, range scans and ad-hoc queries that need steady read latency. The classic LSM incident is compaction falling behind: read latency creeps up and the disk fills.
Read in post: Index types beyond the B-tree
Edge caseSeniorORDER BY ... LIMIT over a time B-tree can scan most of the index when the filter is very rareFor WHERE tags @ '{x}' ORDER BY createdat DESC LIMIT 20, the planner likes to walk the createdat B-tree backwards and filter the tag row by row, because it assumes matching rows are spread evenly over time. In the lab a common tag read 67 rows (0.02 ms) and tag49 (2.5% of the table) read 487 rows (0.13 ms). If the tag

For WHERE tags @> '{x}' ORDER BY created_at DESC LIMIT 20, the planner likes to walk the created_at B-tree backwards and filter the tag row by row, because it assumes matching rows are spread evenly over time. In the lab a common tag read 67 rows (0.02 ms) and tag49 (2.5% of the table) read 487 rows (0.13 ms). If the tag is very rare, or all its posts sit far in the past, this plan walks most of the index before it collects 20 rows, and latency jumps from microseconds to hundreds of milliseconds for the same SQL statement. Watch max time in pg_stat_statements or use auto_explain; for rare filters, rewrite the query so the planner starts from GIN and sorts a small set.

Read in post: Index types beyond the B-tree
InterviewJuniorWhy can't a hash index serve range queries or ORDER BY?

Because a hash function deliberately destroys ordering: the index doesn't know which key sits next to which.

Neighbouring keys land in arbitrary buckets, so you can't move from one key to the next. A hash index only answers "equal to this value", and because of collisions the database still compares the real values.

Read in post: Index types beyond the B-tree
InterviewJuniorWhat is an inverted index?

A structure that stores, for each element (a word, a tag, a JSON key), the list of rows that contain it, like the index at the back of a book.

"Contains X" is a lookup of X; "contains X and Y" is an intersection of two lists. PostgreSQL's GIN and Elasticsearch both follow this idea.

Read in post: Index types beyond the B-tree
InterviewMidHow do jsonb_ops and jsonb_path_ops differ?

jsonb_ops indexes each key and value and also supports ?; jsonb_path_ops indexes a hash of the whole path, smaller and faster for @> but without ?.

The key-existence operators of jsonb_ops are ?, ?|, ?&. Neither serves attrs->>'k' = 'v'; that needs an expression index.

Read in post: Index types beyond the B-tree
InterviewMidHow does full-text search work in PostgreSQL?

Text becomes a tsvector, the search string a tsquery, @@ tests for a match, and a GIN index on the tsvector makes it fast.

A tsvector holds normalised lexemes with positions under a language configuration; ts_rank ranks results. The tsvector usually lives in a generated column. For Vietnamese, use the simple configuration plus unaccent.

Read in post: Index types beyond the B-tree
InterviewMidWhat does an exclusion constraint solve that UNIQUE can't?

UNIQUE only forbids two equal rows; an exclusion constraint forbids two rows for which all listed operators are true, such as same room and overlapping times.

room_id WITH =, during WITH && forbids two bookings of the same room with overlapping times. It is enforced with a GiST index and holds under concurrent transactions: the later one waits, then gets 23P01.

Read in post: Index types beyond the B-tree
InterviewMidHow does GIN fastupdate affect latency?

On, writes are much cheaper but you get p99 spikes; off, write latency is steady but higher.

With it on, new rows go into an unsorted pending list; reads also scan that list, and whichever write pushes it past gin_pending_list_limit has to merge all of it.

Read in post: Index types beyond the B-tree
InterviewSeniorHow is a bitmap index different from PostgreSQL's bitmap heap scan?

A bitmap index is stored on disk (Oracle, warehouses); a bitmap heap scan uses bitmaps PostgreSQL builds in memory at run time from ordinary indexes.

A bitmap index keeps one bit string per value; it's excellent for low-cardinality columns but locks whole bitmap segments, so it's bad for concurrent OLTP writes. PostgreSQL builds bitmaps from B-tree/GIN/GiST indexes, can AND/OR them, then reads the heap in physical order. "Count the PROCESSING orders" on PostgreSQL is solved with a partial index.

Read in post: Index types beyond the B-tree
InterviewSeniorWhen would you choose an LSM-tree storage engine over a B-tree?

When writes are heavy and dominant (events, logs, time series, counters), access is by key, and compression matters.

You accept read amplification (bloom filters only help point lookups), write amplification from compaction, temporary space overhead, and the risk of compaction falling behind. Read-heavy OLTP, range scans and ad-hoc queries still suit a B-tree better.

Read in post: Index types beyond the B-tree
InterviewSeniorHow do size-tiered and leveled compaction differ?

Size-tiered has cheap writes but worse reads and space; leveled has better reads and space but rewrites more.

Size-tiered merges SSTables of similar size: a key can live in many files and merges need lots of free space. Leveled keeps each level about 10 times the previous one with non-overlapping keys inside a level, so each byte is rewritten more times.

Read in post: Index types beyond the B-tree
InterviewSeniorHow would you index a search screen filtering by tag, keywords and date, newest first?

Start with single indexes that serve many screens (GIN on tags, GIN on the tsvector, B-tree on created_at), measure plans on real data and watch max latency.

The planner usually starts from the most selective condition and filters the rest, or walks the time B-tree backwards when there's a LIMIT. An ORDER BY ... LIMIT plan degrades with rare filters, so look at the max, not just the average. When ranking and Vietnamese handling matter, move search to Elasticsearch synced via CDC.

Read in post: Index types beyond the B-tree
TILJuniorA cache is not a bufferA cache holds a copy so it can be read many times; losing it only makes things slower. A buffer temporarily holds data on its way to another component, like a queue: written once, taken out once (a log write buffer, a socket buffer, a Kafka producer batch). Losing a buffer means losing data.

A cache holds a copy so it can be read many times; losing it only makes things slower. A buffer temporarily holds data on its way to another component, like a queue: written once, taken out once (a log write buffer, a socket buffer, a Kafka producer batch). Losing a buffer means losing data.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseMid"If the cache fails we fall back to the database" is false without a short Redis client timeoutCache-aside only survives a Redis failure if the failure is fast. If Redis hangs (a flaky network, a failover in progress), every request waits for the command timeout; Lettuce's default is 60 seconds. With 200 Tomcat threads, a few seconds drains the pool and the whole service stalls while the database is perfectly he

Cache-aside only survives a Redis failure if the failure is fast. If Redis hangs (a flaky network, a failover in progress), every request waits for the command timeout; Lettuce's default is 60 seconds. With 200 Tomcat threads, a few seconds drains the pool and the whole service stalls while the database is perfectly healthy. Set spring.data.redis.timeout to tens or a few hundred milliseconds, keep connect-timeout short, and use a circuit breaker (a fuse: after enough errors, skip Redis for a while).

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Trade-offMidWrite-through, write-back or write-aroundWrite-through: when reading right after writing is common and must show the new value; one extra round-trip on writes. Two concurrent writers can still race. Write-back: for data written very often where losing a little is fine (counters, likes, last-seen). Never for balances or orders. Write-around + cache-aside: the
  • Write-through: when reading right after writing is common and must show the new value; one extra round-trip on writes. Two concurrent writers can still race.
  • Write-back: for data written very often where losing a little is fine (counters, likes, last-seen). Never for balances or orders.
  • Write-around + cache-aside: the default for business data, with the database as the source of truth. The cost: you own invalidation and accept milliseconds to seconds of stale data.
Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseMidGroup invalidation with KEYS prefix* freezes RedisKEYS walks the whole keyspace in one command on Redis's single command thread; with a few million keys, every other client is blocked for hundreds of milliseconds or more. Use SCAN in batches, a Set holding the group's keys (a tag set), or a versioned namespace: keys look like shop:7:v{n}:page:3, and "deleting" the who

KEYS walks the whole keyspace in one command on Redis's single command thread; with a few million keys, every other client is blocked for hundreds of milliseconds or more. Use SCAN in batches, a Set holding the group's keys (a tag set), or a versioned namespace: keys look like shop:7:v{n}:page:3, and "deleting" the whole group is just INCR shop:7:ver; nobody reads the old keys any more and they expire on their own.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseMidWriting the new value into the cache after the database write still diverges with two writersWhether you update the cache first or later, some interleaving breaks it (diagram above): updating later leaves the cache wrong until the TTL, updating first leaves the database wrong. Without a shared transaction, the order of operations across two systems isn't guaranteed; writers should delete the key, not write a v

Whether you update the cache first or later, some interleaving breaks it (diagram above): updating later leaves the cache wrong until the TTL, updating first leaves the database wrong. Without a shared transaction, the order of operations across two systems isn't guaranteed; writers should delete the key, not write a value.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Trade-offMidDelete the cache before or after the database writeDelete first, write the DB second: the window is the whole database write (tens of ms). Almost certain to happen on a hot key. Commit the DB first, delete second: only breaks if a whole database write fits in a reader's sub-millisecond gap. Rare, and bounded by the TTL. Choose commit first, delete second, with a TTL. I
  • Delete first, write the DB second: the window is the whole database write (tens of ms). Almost certain to happen on a hot key.
  • Commit the DB first, delete second: only breaks if a whole database write fits in a reader's sub-millisecond gap. Rare, and bounded by the TTL.
  • Choose commit first, delete second, with a TTL. If even that rare window is unacceptable, add a double delete, versions or leases (section 7), or don't cache it.
Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseMidDeleting the cache inside @Transactional deletes it before the commitrepo.save(c); redis.delete(key); inside a @Transactional method looks like "write the DB, then delete", but the UPDATE isn't committed when delete runs. A reader that misses then reloads the old value: exactly the "delete first" scenario. The delete must run after commit: @TransactionalEventListener(phase = AFTERCOMMIT

repo.save(c); redis.delete(key); inside a @Transactional method looks like "write the DB, then delete", but the UPDATE isn't committed when delete runs. A reader that misses then reloads the old value: exactly the "delete first" scenario. The delete must run after commit: @TransactionalEventListener(phase = AFTER_COMMIT), TransactionSynchronization.afterCommit, or a transaction-aware cache manager (RedisCacheManager.builder(f).transactionAware(), which defers put/evict until after commit) if you use @CacheEvict.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseSeniorLoading from a replica on a miss can bring the old value back even with the right orderIf readers fill the cache from a read replica, "commit on the primary, then delete" isn't enough: a reader misses right after the delete, the replica is 200 ms behind and returns the old value, and it stays cached until the TTL. This happens whenever replication lag (how far the replica is behind) is longer than the ga

If readers fill the cache from a read replica, "commit on the primary, then delete" isn't enough: a reader misses right after the delete, the replica is 200 ms behind and returns the old value, and it stays cached until the TTL. This happens whenever replication lag (how far the replica is behind) is longer than the gap between two requests. Fixes: fill the cache from the primary, a double delete with a delay longer than the lag, or CDC-driven invalidation that reads from that same replica.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Trade-offSeniorShort TTL, double delete, versions or leasesShort TTL only: simplest, bounds how long data can be wrong; enough for most display data. Delayed double delete: adds a delay queue; covers slow readers and replication lag if the delay is long enough, but not absolutely. Version + tombstone (Lua): deterministic; needs a version column, and every cache fill must go th
  • Short TTL only: simplest, bounds how long data can be wrong; enough for most display data.
  • Delayed double delete: adds a delay queue; covers slow readers and replication lag if the delay is long enough, but not absolutely.
  • Version + tombstone (Lua): deterministic; needs a version column, and every cache fill must go through the script.
  • Leases: solve both stale sets and the thundering herd; need cache-server support or your own implementation.
  • Data that must never be stale (a balance used to approve a withdrawal): don't make the decision from the cache.
Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Trade-offSeniorIn-app retry, outbox or CDC to guarantee invalidationIn-app retry: no new infrastructure; lost if the process dies between the commit and the delete, and every write path must remember to delete. Outbox: atomic with the transaction, only needs a table and a job; every write path still has to write to the outbox. CDC: catches every change, even outside the app, at least o
  • In-app retry: no new infrastructure; lost if the process dies between the commit and the delete, and every write path must remember to delete.
  • Outbox: atomic with the transaction, only needs a table and a job; every write path still has to write to the outbox.
  • CDC: catches every change, even outside the app, at least once, in log order. The cost: running Debezium/Kafka, a few hundred ms of extra lag, mapping table changes to derived keys.
  • Choose retry + TTL for ordinary data; outbox if you already have one for other events; CDC when several services or write paths touch cached data.
Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseSeniorA forgotten PostgreSQL replication slot fills the diskCDC on PostgreSQL reads the WAL through a logical replication slot (wallevel = logical, the pgoutput plugin). The slot retains all WAL the consumer hasn't confirmed; if the connector stops for a few days (or is deleted while the slot isn't), WAL piles up until the primary's disk is full. Monitor pgreplicationslots and

CDC on PostgreSQL reads the WAL through a logical replication slot (wal_level = logical, the pgoutput plugin). The slot retains all WAL the consumer hasn't confirmed; if the connector stops for a few days (or is deleted while the slot isn't), WAL piles up until the primary's disk is full. Monitor pg_replication_slots and set max_slot_wal_keep_size (PG 13+). MySQL has no slots: binlogs are purged after binlog_expire_logs_seconds, so the opposite risk applies: a connector that's down longer than the retention must re-snapshot. MySQL also needs binlog_format = ROW.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewJuniorHow does cache-aside work?

The app reads the cache first; on a miss it reads the database, writes the result into the cache with a TTL and returns it.

The write side is usually write-around: write the database, then delete the key. Pros: if Redis is down you can still read the database, and the cache can hold a different shape than the table. Cons: the logic lives in the app and there's a window of stale data.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewJuniorWhat is the cache hit rate and why does it matter?

The share of reads served by the cache; it decides how much load reaches the database.

Database load is (1 − hit rate) × reads, so going from 95% to 99% cuts database load fivefold. The hit rate is high when access is skewed (80/20). A hit rate that drops after a deploy usually means the key format changed or someone flushed the cache.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewMidWhen data changes, should you update or delete the cache key? Why?

Delete, because writing values from the writer side races between two writers, while deletes can be reordered safely.

A writes the DB, B writes the DB, B sets the cache, A sets the cache: the cache holds A's value while the DB holds B's. A delete carries no value and is idempotent; the next read reloads from the database. Deleting also avoids computing a value for a key nobody may read.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewMidWrite the database then delete the cache, or delete first? Why?

Write (commit) the database first, delete afterwards, with a TTL; "afterwards" means after commit, not after the UPDATE statement inside the transaction.

Deleting first lets any reader that misses during the write load the old value, a window as long as the whole write. Writing first only breaks if a complete database write fits in the tiny gap between a reader's database read and its cache set, which is rare because cache operations are much faster. The TTL bounds the worst case.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewMidHow do write-through, write-back and write-around differ?

They differ in what gets written first and when the call returns.

  • Write-through writes the cache and the database synchronously before returning: the cache is always fresh, writes are slower.
  • Write-back writes the cache and returns, flushing to the database later: very fast, but data is lost if the cache dies, so it suits counters.
  • Write-around writes the database and invalidates the cache: the cache only holds what's read, but data that's both written and read often keeps missing.
Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewSeniorThe database write succeeded but the cache delete failed. How do you guarantee invalidation?

There's no shared transaction, so make the delete retryable until it succeeds, and always keep a TTL as an upper bound.

  • In-app retry with backoff (lost if the process dies).
  • An outbox that records the "intent to delete" in the same transaction, and a job that performs it.
  • CDC that reads the binlog/WAL and deletes keys, catching changes made outside the app too.

On Postgres, monitor the replication slot; on MySQL, use binlog_format=ROW and keep binlogs long enough.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewSeniorYou write the DB first and delete after commit, yet stale data lingers. What do you suspect?

First a lagging replica feeding the cache, then deletes failing silently and other cache layers.

(1) The cache is filled from a lagging read replica. (2) The delete fails silently (an exception is caught and ignored). (3) Another cache layer: per-pod local caches, a CDN, the client's HTTP cache. (4) Derived keys weren't invalidated. (5) The key has no TTL. Check invalidation metrics, run TTL key, and compare the commit time with the key's last SET.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
InterviewSeniorHow do you fully close the "slow reader repopulates after the writer deleted" race?

To close it fully, use versions + tombstones or leases; a double delete only narrows the window.

  • Delayed double delete: a second delete after a delay longer than a DB read plus replication lag.
  • Versions with tombstones in Lua: accept a fill only if the version read from the DB isn't older than the invalidated version (deterministic, needs a version column).
  • Leases as in Facebook's memcache: a set is rejected if a delete happened after the lease was issued, which also stops the thundering herd.

If the data must never be stale, don't use the cache for that decision.

Read in post: Cache-aside, write-around and keeping the cache consistent with the database
Edge caseMidCaching personal responses on the CDNA response with user-specific data (cart, balance) that lacks Cache-Control: private or no-store can be stored by a CDN/proxy and served to someone else. By default, only cache publicly what is certainly the same for everyone, and set Vary correctly (for example by Accept-Language).

A response with user-specific data (cart, balance) that lacks Cache-Control: private or no-store can be stored by a CDN/proxy and served to someone else. By default, only cache publicly what is certainly the same for everyone, and set Vary correctly (for example by Accept-Language).

Read in post: Caching in system design
Trade-offSeniorA remote cache (Redis) or a replicated cache (Hazelcast) inside the serviceRemote: one shared source, large capacity, updated in one place; every read costs a network round-trip. Replicated cache (each service keeps a read-only copy, for example Hazelcast synced from the service that owns the data): extremely fast reads, keeps working when the owning service is down, clear data ownership. But
  • Remote: one shared source, large capacity, updated in one place; every read costs a network round-trip.
  • Replicated cache (each service keeps a read-only copy, for example Hazelcast synced from the service that owns the data): extremely fast reads, keeps working when the owning service is down, clear data ownership. But it doesn't fit large or frequently updated data, it's tricky to configure in containers, and service startup depends on the first sync.
  • Small reference data that rarely changes (categories, product descriptions for a wishlist service) → replicated. Everything else → remote.
Read in post: Caching in system design
Edge caseSeniorA fast counter that counts wrong because of double likesHINCRBY on every like tap means a double-click, a network retry or two devices will count twice. "Who liked which post" needs a source of truth with a unique constraint on (postid, userid); only increment the counter when the insert actually creates a new row. Views don't need to be exact: use HyperLogLog if you need "

HINCRBY on every like tap means a double-click, a network retry or two devices will count twice. "Who liked which post" needs a source of truth with a unique constraint on (post_id, user_id); only increment the counter when the insert actually creates a new row. Views don't need to be exact: use HyperLogLog if you need "unique viewers".

Read in post: Caching in system design
TILMidHyperLogLog counts billions of elements in just 12 KBHLL hashes each element and tracks the longest run of leading zero bits across 16,384 buckets; the longer the run, the more distinct elements have passed through. The result is an estimate with ~0.81% error that stores no elements, so it can't answer "has this IP visited?" PFMERGE combines several days into a week.

HLL hashes each element and tracks the longest run of leading zero bits across 16,384 buckets; the longer the run, the more distinct elements have passed through. The result is an estimate with ~0.81% error that stores no elements, so it can't answer "has this IP visited?" PFMERGE combines several days into a week.

Read in post: Caching in system design
InterviewMidWhy not count likes with UPDATE count = count + 1 on the database?

Every like on a post fights for the lock on the same row, so a viral post turns into a lock queue and a node manages only a few hundred updates/s on that row.

Alternatives: increment in Redis (atomic, in RAM) and write to the DB in batches; or batch through a queue and then write. The source of truth for "who liked" stays in the DB with a unique constraint.

Read in post: Caching in system design
InterviewMidHow do a cache and a buffer differ?

A cache holds a copy of data that already exists at the source, so if it's lost you read it again; a buffer holds data that hasn't reached its destination yet, so if it's lost it's really gone.

That's why a buffer needs durability (a queue, AOF) or an accepted, bounded loss, while a cache only needs a TTL and a refresh strategy.

Read in post: Caching in system design
InterviewMidCan single-threaded Redis have race conditions?

Each single command is atomic, but a sequence of reading on the client, computing, then writing still races between clients.

Put that sequence into a Lua script, or use WATCH/MULTI (retry when the key changes). Lua is usually simpler and faster.

Read in post: Caching in system design
InterviewSeniorDesign like/view counters for 1 billion users at 1 million QPS.

Likes: a unique post_like table as the source of truth, Redis hashes holding the counters, a batching job writing post_count. Views: only need to be approximate, count in Redis (HLL if you need unique viewers), possibly sampled.

Redis Cluster with ~15–20 masters for 1M QPS, small hashes to save RAM, cold posts on a disk tier. Hot keys: split the counter into sub-keys or batch increments in the service for 100 ms. Durability: AOF everysec + reload from the DB, and nightly reconciliation.

Read in post: Caching in system design
InterviewSeniorHow do you count unread broadcast notifications for 10 million users?

Store a last_read_id pointer per user and count the broadcasts with a larger id, instead of incrementing 10 million counters on every send.

O(1) writes when sending a broadcast, O(log n) reads with ZCOUNT. For segmented broadcasts, keep one ZSET per segment and sum over the user's segments.

Read in post: Caching in system design
InterviewSeniorWhen do you use a local JVM cache instead of Redis?

When the data is small, read extremely often, and can be a few seconds stale: config, catalogs, super-hot keys.

A local cache (Caffeine) reads in ns, costs no network, and survives Redis going down. In exchange, every instance has its own copy, invalidating all of them at once needs pub/sub or a short TTL, and it uses heap (which affects GC). The common combination: a local 5 s TTL in front of Redis.

Read in post: Caching in system design
InterviewSeniorHow do you check whether a username exists on a public API without probing traffic taking down the DB?

A Bloom filter (RedisBloom BF.EXISTS) in front of the DB: answer "not taken" right away when the filter says no; only ask the DB when the filter says "maybe".

Add per-IP rate limiting. Size: 100 million usernames at a 1% false positive rate needs ~120 MB. A Bloom filter can't delete elements; if usernames get deleted, use a Cuckoo filter or rebuild it periodically.

Read in post: Caching in system design
Trade-offSeniorDurability and availability pull against each other in min.insync.replicas and unclean electionDurability: min.insync.replicas=2 (RF=3) and unclean.leader.election.enable=false. When the ISR shrinks to 1, or only a lagging replica is left, the partition stops accepting writes or goes offline, but no acknowledged record is lost. Availability: min.insync.replicas=1 and unclean election allowed. Writes almost alway
  • Durability: min.insync.replicas=2 (RF=3) and unclean.leader.election.enable=false. When the ISR shrinks to 1, or only a lagging replica is left, the partition stops accepting writes or goes offline, but no acknowledged record is lost.
  • Availability: min.insync.replicas=1 and unclean election allowed. Writes almost always succeed, but an acknowledged record may live on one machine only and is lost when a lagging replica becomes leader.
  • There's no universally right value. Ask the business: what does losing one record cost, and what does a minute without writes cost?
Read in post: Tuning Kafka for your goal
Edge caseMiddelivery.timeout.ms must be at least linger.ms + request.timeout.msTo fail fast, people set delivery.timeout.ms=30000. With the default request.timeout.ms of 30,000 and linger.ms=10, the producer won't even start: ConfigException: delivery.timeout.ms should be equal to or larger than linger.ms + request.timeout.ms (I hit this running the lab with client 4.1). For a short timeout, lowe

To fail fast, people set delivery.timeout.ms=30000. With the default request.timeout.ms of 30,000 and linger.ms=10, the producer won't even start: ConfigException: delivery.timeout.ms should be equal to or larger than linger.ms + request.timeout.ms (I hit this running the lab with client 4.1).

For a short timeout, lower both, e.g. request.timeout.ms=10000 and delivery.timeout.ms=15000. delivery.timeout.ms bounds the send plus all of its retries.

Read in post: Tuning Kafka for your goal
TILSeniorKafka 4.0 ships a new consumer group protocol (KIP-848)Since Kafka 4.0 the new rebalance protocol is GA: set group.protocol=consumer on the client (the brokers must be 4.0+ too). Partition assignment moves to the broker, rebalances are incremental by default and there's no group-wide synchronisation barrier. The assignor is picked with group.remote.assignor, and partition.

Since Kafka 4.0 the new rebalance protocol is GA: set group.protocol=consumer on the client (the brokers must be 4.0+ too). Partition assignment moves to the broker, rebalances are incremental by default and there's no group-wide synchronisation barrier. The assignor is picked with group.remote.assignor, and partition.assignment.strategy is no longer used. With client 4.1, setting session.timeout.ms, heartbeat.interval.ms or partition.assignment.strategy together with group.protocol=consumer makes the consumer throw ConfigException at startup (verified in the consumer group post). With both cluster and clients on 4.x, try it before fine-tuning the old assignors.

Read in post: Tuning Kafka for your goal
Edge caseSeniorAuto-commit can both lose and duplicate messagesWith enable.auto.commit=true, the client commits the offsets of records already returned by poll every auto.commit.interval.ms (5 s), during a later poll or on close. Processing synchronously inside the poll loop: at-least-once, a crash reprocesses up to 5 s of data (duplicates). Handing records to a thread pool or int

With enable.auto.commit=true, the client commits the offsets of records already returned by poll every auto.commit.interval.ms (5 s), during a later poll or on close.

  • Processing synchronously inside the poll loop: at-least-once, a crash reprocesses up to 5 s of data (duplicates).
  • Handing records to a thread pool or internal queue and polling on: offsets get committed before processing finishes, and a crash loses those records.

For payments: disable auto-commit and commit after processing (with idempotent writes), or let the Spring Kafka container commit.

Read in post: Tuning Kafka for your goal
Trade-offSeniorEager vs cooperative rebalancingEager (RangeAssignor, RoundRobinAssignor, the old default): every rebalance makes every consumer revoke all its partitions and get them back. The whole group stops ("stop-the-world"), even unaffected consumers. Cooperative (CooperativeStickyAssignor): only partitions that change owner are revoked, over two rounds; the
  • Eager (RangeAssignor, RoundRobinAssignor, the old default): every rebalance makes every consumer revoke all its partitions and get them back. The whole group stops ("stop-the-world"), even unaffected consumers.
  • Cooperative (CooperativeStickyAssignor): only partitions that change owner are revoked, over two rounds; the rest keep running. Far less disruption during rolling deploys or autoscaling, at the cost of two rounds.
  • Switching a live group from eager to cooperative takes two rolling deploys (first list both assignors, then drop the old one).
Read in post: Tuning Kafka for your goal
Edge caseMidA group idle longer than offsets.retention.minutes loses its offsets and rereads or skips dataThe committed offsets of a group with no active consumers are deleted after offsets.retention.minutes (7 days by default). A monthly batch job, or a service switched off for two weeks, comes back and applies auto.offset.reset: earliest reprocesses the whole retention window, latest silently skips everything produced wh

The committed offsets of a group with no active consumers are deleted after offsets.retention.minutes (7 days by default). A monthly batch job, or a service switched off for two weeks, comes back and applies auto.offset.reset: earliest reprocesses the whole retention window, latest silently skips everything produced while it was away. Raise offsets.retention.minutes (the doc suggests about a month) and monitor inactive groups.

Read in post: Tuning Kafka for your goal
Trade-offSeniorOne partition for total ordering, or many partitions for throughput1 partition: every record has a single order, but only one consumer in the group does any work and throughput is capped by one broker. Many partitions: parallelism and high throughput, with ordering only per key. Most business flows only need per-entity order (per account, per order), so picking the right key is enough
  • 1 partition: every record has a single order, but only one consumer in the group does any work and throughput is capped by one broker.
  • Many partitions: parallelism and high throughput, with ordering only per key. Most business flows only need per-entity order (per account, per order), so picking the right key is enough.
  • Only choose 1 partition when you truly need total ordering and the load is small (say, a stream of configuration commands); don't choose it "just to be safe".
Read in post: Tuning Kafka for your goal
Edge caseMidIn Spring Kafka, enable.auto.commit defaults to false and the container commitsGeneric guides recommend enable.auto.commit=true, but Spring Kafka (since 2.3) sets it to false unless you declare it. The container commits according to AckMode (default BATCH: commit once the listener has processed the whole batch from one poll). Turning auto-commit on takes you back to time-based commits and loses t

Generic guides recommend enable.auto.commit=true, but Spring Kafka (since 2.3) sets it to false unless you declare it. The container commits according to AckMode (default BATCH: commit once the listener has processed the whole batch from one poll). Turning auto-commit on takes you back to time-based commits and loses that control.

A second trap: DefaultErrorHandler by default retries 9 times with no delay and then logs and skips the record. Without a DeadLetterPublishingRecoverer, failed messages silently disappear.

Read in post: Tuning Kafka for your goal
Edge caseMidOne configuration for every topic is the wrong configuration for at least one of themBroker defaults set for the transaction flow (min ISR 2, unclean off) make clickstream stop ingesting during an incident; defaults set for clickstream put transactions at risk. Keep safe defaults on the broker, override per topic (kafka-configs --alter --entity-type topics) for throughput-first flows, and give each flo

Broker defaults set for the transaction flow (min ISR 2, unclean off) make clickstream stop ingesting during an incident; defaults set for clickstream put transactions at risk. Keep safe defaults on the broker, override per topic (kafka-configs --alter --entity-type topics) for throughput-first flows, and give each flow its own producer config. Write down why each value was chosen in the design doc so nobody "optimises" it by mistake later.

Read in post: Tuning Kafka for your goal
InterviewJuniorWhen does auto.offset.reset apply?

Only when the group has no committed offset for a partition, or the committed offset is no longer valid.

Invalid means expired per offsets.retention.minutes, or outside the retained range. earliest reads from the oldest retained record, latest reads only new records, none throws an exception. A group with committed offsets always resumes from them.

Read in post: Tuning Kafka for your goal
InterviewJuniorWhat are the three mandatory settings of a Kafka producer?

bootstrap.servers, key.serializer and value.serializer.

Everything else has a default, but set acks, enable.idempotence, linger.ms and compression.type explicitly, because defaults change between versions.

Read in post: Tuning Kafka for your goal
InterviewJuniorWhat happens if two different services share a group.id?

They become one consumer group and split the partitions: each message reaches only one of the two services.

If each service must receive every message, each needs its own group.id.

Read in post: Tuning Kafka for your goal
InterviewMidHow would you configure a producer for financial data?

acks=all, idempotence on, and a topic with RF=3, min.insync.replicas=2 and unclean election off.

  • max.in.flight.requests.per.connection ≤ 5, delivery.timeout.ms from the SLA (and ≥ linger.ms + request.timeout.ms), a small linger.ms, lz4, and a key on the entity that needs ordering.
  • Handle send failures in the callback, and use an outbox if the event accompanies a DB write.
Read in post: Tuning Kafka for your goal
InterviewMidIs enable.auto.commit=true safe?

Only (as at-least-once) when you process synchronously inside the poll loop; with asynchronous processing it can lose messages.

It periodically commits the offsets of records already returned by poll, during a later poll. On a thread pool, offsets can be committed before processing finishes, and a crash loses those records. For important data, disable it and commit after processing, or let the Spring Kafka container commit per AckMode.

Read in post: Tuning Kafka for your goal
InterviewMidProcessing one batch takes 6 minutes. What happens and how do you fix it?

It exceeds max.poll.interval.ms (5 minutes by default), so the consumer is kicked out of the group and the batch is reprocessed.

Its partitions go to another consumer and the old consumer's commit fails. Fix it by lowering max.poll.records, raising max.poll.interval.ms to fit, or offloading the heavy work and using pause/resume on the partitions meanwhile. Patterns for long-running tasks (async, liveness tuning, pipelines) are in §5 of this post.

Read in post: Tuning Kafka for your goal
InterviewSeniorHow does cooperative rebalancing differ from eager?

Eager revokes every partition and stops the whole group; cooperative revokes only the partitions that must move, and the rest keep running.

Cooperative (CooperativeStickyAssignor) works over two rounds, so rolling deploys and autoscaling cause much less disruption. Kafka 4.0 adds the KIP-848 protocol (group.protocol=consumer), which moves assignment to the broker and makes rebalances incremental by default.

Read in post: Tuning Kafka for your goal
InterviewSeniorHow do you choose the partition count for a new topic?

Divide the target throughput by one consumer's and one producer's per-partition throughput, take the max, then add headroom for 1–2 years of growth.

You need headroom because you can't shrink, and growing remaps keys. The consumer is usually the limit. Weigh the cost of many partitions: open files, replication work, producer memory, leader election time. If you need total ordering and the load is small, use one partition.

Read in post: Tuning Kafka for your goal
InterviewSeniorWhere do durability and availability conflict in Kafka's configuration?

In min.insync.replicas, unclean.leader.election.enable, acks and session.timeout.ms.

  • Higher min.insync.replicas is more durable but stops writes sooner when nodes die.
  • Unclean election on recovers faster but loses records.
  • acks=all is slower and can be refused.
  • Lower session.timeout.ms detects failures faster but triggers false rebalances.

Choose per flow from its goal ranking, with safe broker defaults and per-topic overrides.

Read in post: Tuning Kafka for your goal
InterviewSeniorWhich metrics do you monitor on a Kafka cluster?

Consumer lag first, then replication health (UnderReplicatedPartitions, UnderMinIsrPartitionCount, OfflinePartitionsCount).

Add active controller count, produce/fetch request latency, broker disk and network, producer error and retry rates, average batch size, and rebalance counts. Alert against each flow's SLA, not a single global threshold.

Read in post: Tuning Kafka for your goal
Trade-offSeniorBlue-green or canaryBlue-green: instant rollback because the old environment is untouched, and you can test green before the switch. Cost: double resources during the switch, and every user hits the bug at once if the new version is broken. Canary: a bug only reaches a small share of users, and you get real metrics before widening. Cost:
  • Blue-green: instant rollback because the old environment is untouched, and you can test green before the switch. Cost: double resources during the switch, and every user hits the bug at once if the new version is broken.
  • Canary: a bug only reaches a small share of users, and you get real metrics before widening. Cost: a slower rollout, weighted routing and automated analysis.
  • Both share one database: "flipping back to blue" doesn't bring the old schema back.
Read in post: Deployment strategies
Edge caseSeniorShadow traffic triggers real side effectsThe shadow gets real requests. If it writes to the main database, sends emails, charges cards or publishes to Kafka, every request happens twice. A shadow must use its own storage or stub every outbound call, and if you can't isolate it, mirror only read endpoints.

The shadow gets real requests. If it writes to the main database, sends emails, charges cards or publishes to Kafka, every request happens twice. A shadow must use its own storage or stub every outbound call, and if you can't isolate it, mirror only read endpoints.

Read in post: Deployment strategies
TILMidDark launch: running new code without users knowingA dark launch runs the new code path on real requests but ignores the result: for example, call both the old and the new pricing algorithm, return the old answer, and log the difference. Unlike a shadow, it lives inside the same service and is controlled by a flag, so there is no traffic mirroring at the network layer.

A dark launch runs the new code path on real requests but ignores the result: for example, call both the old and the new pricing algorithm, return the old answer, and log the difference. Unlike a shadow, it lives inside the same service and is controlled by a flag, so there is no traffic mirroring at the network layer.

Read in post: Deployment strategies
Edge caseMidFlags that never get removedEvery flag doubles the number of code paths. After a year with 40 flags, nobody knows which combination runs in production. A release flag needs an expiry date and a removal ticket from the day it is created, and tests must cover both branches.

Every flag doubles the number of code paths. After a year with 40 flags, nobody knows which combination runs in production. A release flag needs an expiry date and a removal ticket from the day it is created, and tests must cover both branches.

Read in post: Deployment strategies
Edge caseSeniorYou can roll back code, but not a schemakubectl rollout undo brings the old image back in a minute, but once DROP COLUMN has run, the data is gone. Destructive migrations (drop, rename, type change) run only when you are sure you'll never return to a version that reads that column. The rollback plan must say "we can roll back as far as release X".

kubectl rollout undo brings the old image back in a minute, but once DROP COLUMN has run, the data is gone. Destructive migrations (drop, rename, type change) run only when you are sure you'll never return to a version that reads that column. The rollback plan must say "we can roll back as far as release X".

Read in post: Deployment strategies
TILSeniorA PodDisruptionBudget doesn't protect a Deployment's own rolling updateA PDB only covers voluntary disruptions that go through the Eviction API: kubectl drain, the cluster autoscaler removing a node. A Deployment rollout is governed by maxUnavailable, and nothing stops a node from dying. A PDB with minAvailable equal to replicas makes node drains hang forever.

A PDB only covers voluntary disruptions that go through the Eviction API: kubectl drain, the cluster autoscaler removing a node. A Deployment rollout is governed by maxUnavailable, and nothing stops a node from dying. A PDB with minAvailable equal to replicas makes node drains hang forever.

Read in post: Deployment strategies
Edge caseSeniorA liveness probe that checks the database causes cascading restartsThe database is slow for 30 seconds, every pod fails liveness, and they all restart together. The fresh pods then open connections in a burst and slow the database down further. The Spring Boot docs advise that liveness should not depend on external systems. Handle dependency failures with timeouts and circuit breakers

The database is slow for 30 seconds, every pod fails liveness, and they all restart together. The fresh pods then open connections in a burst and slow the database down further. The Spring Boot docs advise that liveness should not depend on external systems. Handle dependency failures with timeouts and circuit breakers, not restarts.

Read in post: Deployment strategies
Trade-offSeniorShould readiness check the databaseYes: a single pod that lost its database connection (a broken pool, say) is taken out of traffic instead of returning 500s. No: when the shared database goes down, every pod turns unready, and the Service refuses connections or the ingress returns 503 for every endpoint, including those that don't need the database. Th
  • Yes: a single pod that lost its database connection (a broken pool, say) is taken out of traffic instead of returning 500s.
  • No: when the shared database goes down, every pod turns unready, and the Service refuses connections or the ingress returns 503 for every endpoint, including those that don't need the database.
  • The Spring Boot docs call this a judgement call: include only dependencies without which the pod is truly useless. Leave secondary ones (recommendations, email) to circuit breakers.
Read in post: Deployment strategies
Edge caseSeniorA 1% canary sees too few requests to conclude anythingAt 20 requests per second, a 1% canary gets 0.2 per second: 120 requests in ten minutes. One error is 0.8%, and zero errors proves nothing. Work out the sample size first, raise the weight or lengthen the step, and tag metrics and traces with version so the two groups can be separated.

At 20 requests per second, a 1% canary gets 0.2 per second: 120 requests in ten minutes. One error is 0.8%, and zero errors proves nothing. Work out the sample size first, raise the weight or lengthen the step, and tag metrics and traces with version so the two groups can be separated.

Read in post: Deployment strategies
InterviewJuniorWhat is the difference between a readiness probe and a liveness probe?

A failing readiness probe removes the pod from the Service but keeps it running; a failing liveness probe restarts the container.

Readiness answers "should you send me requests?", and matters at startup, at shutdown and under temporary overload. Liveness answers "can I still recover?", and should fail only when the process is truly stuck. A startup probe shields both during a slow start.

Read in post: Deployment strategies
InterviewJuniorWhat is a rolling update, and how does Kubernetes avoid losing requests?

It replaces old pods with new ones gradually, sending traffic only to ready pods, within the maxSurge and maxUnavailable limits.

To truly lose nothing, the app must also shut down gracefully: receive SIGTERM, stop taking new requests, finish in-flight ones, plus a preStop sleep so the load balancer has time to drop the pod.

Read in post: Deployment strategies
InterviewMidYou need to rename a column that is in use. How do you deploy it with no downtime?

Expand/contract across several releases: add the new column, write both, backfill, switch reads, stop writing the old column, and only then drop it.

During a rolling deploy, old and new pods share one database, so the schema must suit both. Each migration must work with the code version right before it, and the drop happens only when you'll never roll back to a version that reads the old column.

Read in post: Deployment strategies
InterviewMidHow does blue-green differ from canary, and when do you pick each?

Blue-green switches all traffic at once to a fully prepared new environment; canary sends a small share first and grows it based on metrics.

Blue-green suits cases that need instant rollback and can afford double capacity. Canary suits risky changes on high-traffic services, because a bug only reaches some users. Both share the database, so migrations still need to be compatible.

Read in post: Deployment strategies
InterviewMidHow do feature flags help with deployments, and what do they cost?

They separate deploy from release: code ships switched off, is enabled gradually per user, and can be turned off in seconds without a redeploy.

The cost: every flag doubles the code paths, both branches need tests, and old flags become technical debt. Release flags need an expiry date; kill switches live long and should be exercised regularly.

Read in post: Deployment strategies
InterviewSeniorEvery deploy shows a few dozen 502s on the dashboard. How do you investigate?

It is almost always a pod receiving traffic before it is ready, or being closed while still routed to; check both ends of the pod lifecycle.

  • Startup: does readiness reflect true readiness (pool, caches), is minReadySeconds set?
  • Shutdown: does the JVM get SIGTERM (exec-form ENTRYPOINT), is graceful shutdown on, is there a preStop sleep so the ingress can drop the pod, is the grace period long enough?
  • Keep-alive: the proxy holds connections to old pods, so its keep-alive timeout must be shorter than the app's, or the app sends Connection: close while shutting down (see reverse proxy).
  • Line up the error timestamps with the pod's Killing and Readiness probe failed events.
Read in post: Deployment strategies
InterviewSeniorDesign an automated canary for a payment service.

A weighted canary with steps of 5%, 25% and 50%, each with automated analysis comparing canary and old version, and automatic rollback when a threshold is crossed.

  • Signals: 5xx rate, p99, SLO burn rate, payment success rate and transactions per minute, all labelled by version.
  • Enough samples: hold a step until it has enough transactions, not just enough minutes.
  • Route by user so nobody switches versions in the middle of a checkout.
  • Schema and message changes go first via expand/contract. Tooling: Argo Rollouts or Flagger with Prometheus metrics.
Read in post: Deployment strategies
InterviewSeniorWhat is a PodDisruptionBudget for, and what happens when it is misconfigured?

A PDB limits how many pods can be taken down at once during voluntary disruptions like a node drain, so the service always keeps enough pods.

It doesn't apply to a Deployment rollout or to a node dying. Setting minAvailable equal to replicas, or a PDB on a single-pod Deployment, makes kubectl drain hang and blocks cluster upgrades. Use maxUnavailable: 1 or a minAvailable below the replica count.

Read in post: Deployment strategies
Edge caseMidTreating benchmark numbers as the real ceilingpgbench or sysbench on simple statements report tens of thousands of TPS, but real transactions have 5–10 statements, secondary indexes, triggers and contention. Use the rough numbers above to estimate, then measure with real load (k6, Gatling) before you conclude you need to scale.

pgbench or sysbench on simple statements report tens of thousands of TPS, but real transactions have 5–10 statements, secondary indexes, triggers and contention. Use the rough numbers above to estimate, then measure with real load (k6, Gatling) before you conclude you need to scale.

Read in post: Choosing a database in system design
TILMidRandom and sequential I/O differ by tens to thousands of timesOn an HDD, a random read costs a disk rotation (~10 ms), while a sequential read is almost free. SSDs narrow the gap, but sequential writes are still much faster and cause less wear. That's why WAL, Kafka and LSM trees all "only append to the end".

On an HDD, a random read costs a disk rotation (~10 ms), while a sequential read is almost free. SSDs narrow the gap, but sequential writes are still much faster and cause less wear. That's why WAL, Kafka and LSM trees all "only append to the end".

Read in post: Choosing a database in system design
Trade-offSeniorDIY RDBMS sharding, NewSQL or NoSQLDIY RDBMS sharding: you keep SQL and the team already knows it, but routing, resharding and cross-shard transactions are your problem. NewSQL: cross-shard transactions out of the box, near-linear scaling at low contention; in exchange, higher latency (1–2 consensus rounds) and the team has to learn to run a new system.
  • DIY RDBMS sharding: you keep SQL and the team already knows it, but routing, resharding and cross-shard transactions are your problem.
  • NewSQL: cross-shard transactions out of the box, near-linear scaling at low contention; in exchange, higher latency (1–2 consensus rounds) and the team has to learn to run a new system.
  • NoSQL: the best throughput and availability, but you design tables around queries (query-first) and accept eventual consistency.
  • Decide with one question: "Do I need transactions across multiple records?" No → NoSQL. Yes, and the data outgrows one node → NewSQL or middleware.
Read in post: Choosing a database in system design
Edge caseSeniorUsing ClickHouse as a transactional databaseRow-by-row inserts create thousands of tiny "parts", merges can't keep up, and you get too many parts errors. UPDATE/DELETE are background mutations that rewrite whole parts. Put ClickHouse behind a queue (Kafka) or a buffer to batch writes, and keep the source of truth in OLTP.

Row-by-row inserts create thousands of tiny "parts", merges can't keep up, and you get too many parts errors. UPDATE/DELETE are background mutations that rewrite whole parts. Put ClickHouse behind a queue (Kafka) or a buffer to batch writes, and keep the source of truth in OLTP.

Read in post: Choosing a database in system design
Trade-offMidTimescaleDB or InfluxDB/PrometheusTimescaleDB: still PostgreSQL (SQL, joins with the device table, familiar backups); lower write throughput than a specialized system. InfluxDB/Prometheus: very good at writing and compressing metrics, its own query language, hard to join with business data. Infrastructure metrics → Prometheus. IoT data that must join w
  • TimescaleDB: still PostgreSQL (SQL, joins with the device table, familiar backups); lower write throughput than a specialized system.
  • InfluxDB/Prometheus: very good at writing and compressing metrics, its own query language, hard to join with business data.
  • Infrastructure metrics → Prometheus. IoT data that must join with business data → TimescaleDB.
Read in post: Choosing a database in system design
Edge caseSeniorSharding to rescue one hot rowEvery flash-sale request updates the row productid = 42. Shard by productid and that row still lives on one shard, so TPS doesn't change. You have to reduce contention at the design level: split the stock into N sub-rows, batch requests in memory, or put Redis in front as a gate.

Every flash-sale request updates the row product_id = 42. Shard by product_id and that row still lives on one shard, so TPS doesn't change. You have to reduce contention at the design level: split the stock into N sub-rows, batch requests in memory, or put Redis in front as a gate.

Read in post: Choosing a database in system design
InterviewMidWhen would you pick NoSQL over PostgreSQL?

When the main queries are known up front and go by key, when you need throughput or horizontal scale beyond one node, and when you don't need transactions or constraints across records.

Example, chat messages: always read by channel_id, very write-heavy, no joins → Cassandra/ScyllaDB. On the other hand, orders + payments need transactions and flexible reporting → PostgreSQL, scaled with replicas/partitions first.

Read in post: Choosing a database in system design
InterviewMidWhy do inserts into a MySQL table with many indexes get slower as the table grows?

Each index is a B+tree; every insert has to find the right leaf page in every tree, and once the indexes outgrow RAM, each lookup is random I/O to disk.

Random keys (UUIDv4) make it worse because they insert into the middle of the tree and cause page splits. To reduce it: fewer secondary indexes, increasing keys (UUIDv7, Snowflake), batch inserts, or an LSM-based system for write-only workloads.

Read in post: Choosing a database in system design
InterviewMidWhere is a columnar database faster than a row store, and where is it slower?

Faster when scanning many rows but few columns (it reads only the needed column files, compresses well, uses bitmaps); slower when reading or changing one full row, because that row is scattered across every column file.

That's why OLTP uses a row store, reporting uses columnar, and the two are connected with CDC or Kafka.

Read in post: Choosing a database in system design
InterviewSeniorA system needs 3,000 write TPS with strong consistency. What do you pick?

First ask about contention: 3,000 TPS spread over millions of users is a completely different problem from 3,000 TPS on a handful of rows.

  • Low contention: one node does about 1,000 TPS, so writes must be split. Shard the RDBMS by user (Vitess/Citus) if the team is strong in MySQL/PostgreSQL, or use TiDB/CockroachDB if you need cross-shard transactions and can accept consensus latency.
  • High contention: more nodes won't help; reduce contention by design (split the hot row, Redis + Lua as a gate, queueing), then write to the DB asynchronously.
Read in post: Choosing a database in system design
InterviewSeniorIs NewSQL free? What's the price?

No. Every commit needs a majority of replicas to agree (Raft), so write latency is higher than one node: a few ms, or tens of ms across regions. Contended transactions still have to retry.

On top of that: not full ANSI SQL, some PostgreSQL/MySQL features are missing, the cost of running many nodes, and OLAP needs a separate component. It's worth it when data and write load outgrow one node and you still need transactions.

Read in post: Choosing a database in system design
InterviewSeniorDesign storage for metrics from 1 million devices, one point every 10 seconds, kept for 90 days. Which database, and why?

A time-series database (TimescaleDB if you need to join with business data), because the data is append-only over time, read by device + time range, and deleted by age.

Estimate: 1M / 10 s = 100K points/s, 8.64 billion points/day; at ~20 bytes/point that's ~170 GB/day, ~15 TB for 90 days uncompressed; columnar compression (usually ×10) brings it to ~1.5 TB. Hypertable with 1-day chunks, compress chunks older than 2 days, a retention policy that drops chunks after 90 days, and continuous aggregates per minute/hour for dashboards. Write through Kafka, then batch insert.

Read in post: Choosing a database in system design
InterviewSeniorWhat does CAP say, and why is "MySQL is CA" the wrong way to put it?

CAP: when the network is partitioned, a distributed system must choose between answering (A) and answering with the latest value (C). P is not optional.

A single MySQL node isn't distributed, so it isn't on the triangle at all. With async replicas, replica reads can be stale (giving up C) and failover can lose writes. PACELC adds: even in normal operation you still trade latency for consistency.

Read in post: Choosing a database in system design
Trade-offSeniorContinuous delivery or continuous deploymentDelivery (approval button): a person picks the moment (avoiding peak hours); fits regulated domains like banking and payments. The price: changes pile up into bigger releases, each deploy riskier. Deployment (no button): every merge is a small change, easy to bisect, short lead time. The price: tests and monitoring str
  • Delivery (approval button): a person picks the moment (avoiding peak hours); fits regulated domains like banking and payments. The price: changes pile up into bigger releases, each deploy riskier.
  • Deployment (no button): every merge is a small change, easy to bisect, short lead time. The price: tests and monitoring strong enough to let the machine decide, and feature flags to separate "deploy" from "turn the feature on".
  • Common in practice: automatic to staging, production behind an approval, then fewer approvals as DORA metrics improve.
Read in post: CI/CD for a Spring Boot backend
Edge caseMidA Maven cache with stale SNAPSHOTs that grows foreverThe cache key only changes when a POM changes. Another team's -SNAPSHOT changes daily but the cache keeps restoring the old one (Maven only checks per updatePolicy): CI green, laptop red. The cache also grows over time. Mitigations: avoid SNAPSHOTs in deployable services, use -U to force updates when needed, and let on

The cache key only changes when a POM changes. Another team's -SNAPSHOT changes daily but the cache keeps restoring the old one (Maven only checks per updatePolicy): CI green, laptop red. The cache also grows over time. Mitigations: avoid SNAPSHOTs in deployable services, use -U to force updates when needed, and let only main write the cache (cache-read-only on PRs).

Read in post: CI/CD for a Spring Boot backend
TILJuniorWorkflows on pull_request from forks get no secretsFor pullrequest from a fork, GitHub passes no secrets and GITHUBTOKEN is read-only, so test jobs must not depend on secrets (Testcontainers fits well: everything runs on the runner). Don't "fix" it with pullrequesttarget: it runs with the repo's secrets, and if you check out and build the PR's code, foreign code runs a

For pull_request from a fork, GitHub passes no secrets and GITHUB_TOKEN is read-only, so test jobs must not depend on secrets (Testcontainers fits well: everything runs on the runner). Don't "fix" it with pull_request_target: it runs with the repo's secrets, and if you check out and build the PR's code, foreign code runs alongside those secrets.

Read in post: CI/CD for a Spring Boot backend
Trade-offMidShould a quality gate block or only warnBlock (red build): quality doesn't drift. The price: overly strict rules make teams disable the whole gate, or get blocked by CVEs with no fix yet. Warn: doesn't slow anyone down, but is quickly ignored. The balance: block on new code (don't demand fixing the whole legacy codebase), block CRITICAL/HIGH vulnerabilities
  • Block (red build): quality doesn't drift. The price: overly strict rules make teams disable the whole gate, or get blocked by CVEs with no fix yet.
  • Warn: doesn't slow anyone down, but is quickly ignored.
  • The balance: block on new code (don't demand fixing the whole legacy codebase), block CRITICAL/HIGH vulnerabilities that have a fix (ignore-unfixed), and schedule the rest.
Read in post: CI/CD for a Spring Boot backend
Edge caseMidRebuilding the image for each environmentThree jobs, build-dev, build-staging and build-prod, each run ./mvnw package and docker build again. Three different images (SNAPSHOTs, version ranges, a drifting base image tag), so what runs in production was never tested, and rollback has nothing to hold on to. Fix: build once, deploy by digest, environments differ

Three jobs, build-dev, build-staging and build-prod, each run ./mvnw package and docker build again. Three different images (SNAPSHOTs, version ranges, a drifting base image tag), so what runs in production was never tested, and rollback has nothing to hold on to. Fix: build once, deploy by digest, environments differ only in config.

Read in post: CI/CD for a Spring Boot backend
Edge caseSeniorUsing third-party actions by a tag that can moveuses: some-org/some-action@v3 points at a tag, and the owner (or whoever takes over the account) can move it to another commit. In March 2025, the tags of tj-actions/changed-files were moved to a malicious commit that printed secrets into the logs of a great many repos. Defences: pin third-party actions to a full commi

uses: some-org/some-action@v3 points at a tag, and the owner (or whoever takes over the account) can move it to another commit. In March 2025, the tags of tj-actions/changed-files were moved to a malicious commit that printed secrets into the logs of a great many repos. Defences: pin third-party actions to a full commit SHA, let Dependabot update the SHAs, restrict permissions, allow only approved actions. The workflow in this post uses tags for readability; a real repo should pin SHAs.

Read in post: CI/CD for a Spring Boot backend
Edge caseMidEditing a migration that already ran elsewhereV7addstatus.sql already ran on staging, then someone edits the file to make it "more correct". Flyway stores each migration's checksum in flywayschemahistory, so the next run reports Migration checksum mismatch and stops; worse, new environments end up with a different schema from old ones. Rule: a merged migration is

V7__add_status.sql already ran on staging, then someone edits the file to make it "more correct". Flyway stores each migration's checksum in flyway_schema_history, so the next run reports Migration checksum mismatch and stops; worse, new environments end up with a different schema from old ones. Rule: a merged migration is immutable; to change it, write V8__....

Read in post: CI/CD for a Spring Boot backend
InterviewJuniorHow do CI, continuous delivery and continuous deployment differ?

CI builds and tests every commit automatically; continuous delivery keeps every build deployable, with production one click away; continuous deployment goes to production with no click.

CI is the foundation of the other two. The only difference between delivery and deployment is whether a person approves the last step, but deployment demands much stronger tests, monitoring and automatic rollback.

Read in post: CI/CD for a Spring Boot backend
InterviewJuniorWhat steps should a pipeline for a Spring Boot service have?

Compile, unit tests, integration tests (Testcontainers), static analysis, image build, vulnerability scan, image push, staging deploy, smoke test, then an approved production deploy.

The order follows the rule that cheap, failure-prone steps run first for early feedback. Test results and reports are kept as artifacts to inspect when a job fails.

Read in post: CI/CD for a Spring Boot backend
InterviewMidWhy build an image once and promote it instead of building per environment?

So that what runs in production is exactly what was tested; a rebuild can produce a different image (changed dependencies or base image), and rollback loses its anchor.

The image is tagged by commit and deployed by digest; environments differ only in config injected at runtime. Promotion just adds a release tag to the existing digest.

Read in post: CI/CD for a Spring Boot backend
InterviewMidHow do you manage secrets in a pipeline?

Keep secrets in GitHub Secrets per environment, give each job minimal permissions, and use OIDC to get short-lived cloud credentials instead of storing long-lived keys.

Also: never print secrets, never pass them as command-line arguments, never run fork code with secrets (pull_request_target), pin third-party actions by SHA. Production secrets are only readable after the environment's approval step.

Read in post: CI/CD for a Spring Boot backend
InterviewMidHow does trunk-based development affect the pipeline?

Every merge to main must be deployable, so CI must be fast and trustworthy, and unfinished features must hide behind feature flags.

In return, merge conflicts are rare and feedback is fast. Git Flow allows longer-lived branches but needs pipelines for develop and release/*, and late integration means bugs surface late.

Read in post: CI/CD for a Spring Boot backend
InterviewSeniorA deploy fails after the migration has already run. How do you roll back?

Roll back the code by redeploying the previous digest; the database stays as is because the migration was written to be backward compatible. If the migration itself is wrong, fix it with a new migration.

This only holds if the team follows expand → contract: no renaming or dropping columns in the same release as the code that uses them. Flyway Community has no undo migrations, and undoing written data is almost always riskier than a forward fix. For a logic bug, turn off the feature flag first, roll back second.

Read in post: CI/CD for a Spring Boot backend
InterviewSeniorA PR pipeline takes 40 minutes. How do you speed it up?

Measure each step first, then attack the biggest: cache dependencies and layers, share Testcontainers and the Spring context, parallelise, and drop work PRs don't need.

  • Cache ~/.m2 and Docker layers (type=gha).
  • One container for the whole suite, avoid @DirtiesContext, keep the context cache.
  • No image build on PRs; don't run tests twice.
  • Static analysis and tests in parallel; cancel stale runs with concurrency.
  • Track median and p90 pipeline time as a team metric.
Read in post: CI/CD for a Spring Boot backend
InterviewSeniorHow do you keep a compromised third-party action from stealing your secrets?

Pin actions to a commit SHA, restrict GITHUB_TOKEN permissions, expose secrets only to jobs that truly need them, and allow only approved actions.

The 2025 tj-actions/changed-files incident showed that tags can be moved to malicious code. Also: use OIDC so credentials expire quickly, separate deploy jobs (with secrets) from build jobs (which run lots of external code), and let Dependabot propose SHA updates for review.

Read in post: CI/CD for a Spring Boot backend
Trade-offMidClean code, performance and time to marketvs performance: usually no conflict, because HotSpot's JIT inlines small methods. Real conflicts only appear on hot paths you have measured with a profiler: optimise locally, hide the "dirty" part behind a clear name, leave a comment with the numbers, keep a JMH benchmark. vs delivery speed: if you take on technical de
  • vs performance: usually no conflict, because HotSpot's JIT inlines small methods. Real conflicts only appear on hot paths you have measured with a profiler: optimise locally, hide the "dirty" part behind a clear name, leave a comment with the numbers, keep a JMH benchmark.
  • vs delivery speed: if you take on technical debt to hit a deadline, record it as a ticket with an owner and a due date.
  • Rule of thumb: throwaway prototypes can be quick; code that will live in production is written clean from the start.
Read in post: Clean code
Edge caseMidInconsistency breeds unknown unknownsWhen one concept is handled two ways (half the codebase uses BigDecimal for money, half double; half findBy, half getBy with different semantics), readers can't reason from one place to another; every case they forget to check is a bug. Rule: inside one codebase, consistency beats "most correct". To change a convention

When one concept is handled two ways (half the codebase uses BigDecimal for money, half double; half findBy, half getBy with different semantics), readers can't reason from one place to another; every case they forget to check is a bug. Rule: inside one codebase, consistency beats "most correct". To change a convention, change it everywhere or draw a clear boundary.

Read in post: Clean code
Edge caseMidA boolean checkX() method doesn't say what true meanscheckScope() could mean "validate and throw", "true if valid" or "true if there is a problem"; callers have to open the code. Name it after the question: boolean withinScope = isWithinTokenScope(requiredScope); or hasScope(token, "orders:write"). Keep check/validate for methods that return void and throw on violation.

checkScope() could mean "validate and throw", "true if valid" or "true if there is a problem"; callers have to open the code. Name it after the question: boolean withinScope = isWithinTokenScope(requiredScope); or hasScope(token, "orders:write"). Keep check/validate for methods that return void and throw on violation.

Read in post: Clean code
Trade-offSeniorDRY and the wrong abstractionMerge early: later the two callers need different things, the shared function grows boolean flags and if (isForAdmin) branches, and becomes a wrong abstraction nobody dares touch. Sandi Metz: duplication is far cheaper than the wrong abstraction. Rule of three: note the duplication the second time, merge on the third,
  • Merge early: later the two callers need different things, the shared function grows boolean flags and if (isForAdmin) branches, and becomes a wrong abstraction nobody dares touch. Sandi Metz: duplication is far cheaper than the wrong abstraction.
  • Rule of three: note the duplication the second time, merge on the third, when you have enough examples to see what is truly shared.
  • Always merge immediately: constants and business rules (shipping threshold, tax formula), because duplicating them is guaranteed change amplification.
Read in post: Clean code
Edge caseMidAdding a SQL statement type by subclassing the existing generatorUpdateGenerator extends SelectGenerator says "an UPDATE generator is a SELECT generator": wrong in meaning and a Liskov Substitution violation, because anything that accepts a SelectGenerator can now receive an object that emits UPDATE. The subclass also inherits SELECT-only things (columns, ORDER BY, LIMIT). The origi

UpdateGenerator extends SelectGenerator says "an UPDATE generator is a SELECT generator": wrong in meaning and a Liskov Substitution violation, because anything that accepts a SelectGenerator can now receive an object that emits UPDATE. The subclass also inherits SELECT-only things (columns, ORDER BY, LIMIT). The original example in Robert C. Martin's Clean Code is an abstract Sql base class with sibling subclasses SelectSql, UpdateSql, InsertSql: a new statement type is a new sibling, and existing classes stay untouched.

Read in post: Clean code
Trade-offSeniorSealed interface or open interface for variantsSealed + pattern-matching switch: a fixed set of variants you own (statement types, order states, payment results). Adding a variant makes the compiler point at every place to update; adding an operation (a new switch) doesn't touch the records. Open interface + polymorphism: variants extended by others (plugins, strat
  • Sealed + pattern-matching switch: a fixed set of variants you own (statement types, order states, payment results). Adding a variant makes the compiler point at every place to update; adding an operation (a new switch) doesn't touch the records.
  • Open interface + polymorphism: variants extended by others (plugins, strategies registered through Spring). Adding a variant needs no changes to old code, but adding an operation means touching every implementation.
  • This is the classic "expression problem": choose based on which axis changes more often.
Read in post: Clean code
Edge caseMidGuard clauses that throw a generic RuntimeException leave callers helplessThe slide's "after" version throws new RuntimeException("User is not active"). The flow is flat, but the caller (or a @RestControllerAdvice) can't tell a business rule violation from a bug, so it can't return 409 for "seat already booked" and 500 for a real failure. Use domain exceptions (SeatAlreadyBookedException) th

The slide's "after" version throws new RuntimeException("User is not active"). The flow is flat, but the caller (or a @RestControllerAdvice) can't tell a business rule violation from a bug, so it can't return 409 for "seat already booked" and 500 for a real failure. Use domain exceptions (SeatAlreadyBookedException) that carry structured data. Also: == false or == true on a boolean is redundant and one typo away from =; write !user.active().

Read in post: Clean code
TILMidCognitive complexity is not cyclomatic complexityCyclomatic complexity (McCabe, 1976) counts independent paths: each if, case and && adds one. It estimates how many tests you need, but scores a flat 10-branch switch the same as 10 nested ifs. Cognitive complexity (SonarSource, 2017) measures how hard code is to read: each structure adds one, plus an extra increment p

Cyclomatic complexity (McCabe, 1976) counts independent paths: each if, case and && adds one. It estimates how many tests you need, but scores a flat 10-branch switch the same as 10 nested ifs. Cognitive complexity (SonarSource, 2017) measures how hard code is to read: each structure adds one, plus an extra increment per nesting level, while else if and a run of the same boolean operator count once. Sonar's rule java:S3776 flags methods above 15 by default; putting that threshold in CI turns "don't nest deeply" into an automated check.

Read in post: Clean code
InterviewJuniorWhat is clean code, and why should a business care?

Code that is easy to understand and easy to change; a business cares because it keeps the cost per change low.

Dirty code is cheap for a few weeks, then every feature costs more, bugs multiply and time to market slips. The goal is to minimise the human effort to build and maintain the system.

Read in post: Clean code
InterviewJuniorHow do you name a boolean well?

After the question the value answers, usually with is, has or can: emailVerified, hasScope, canRefund.

Avoid neutral names like flag and negatives like notDisabled. A boolean method shouldn't be called checkX(), because it doesn't say what true means.

Read in post: Clean code
InterviewJuniorWhat is a guard clause?

A check for an edge case at the top of a function that returns or throws immediately, so the happy path sits at the end without indentation.

It replaces nested if / else if / else chains and makes the function read top to bottom.

Read in post: Clean code
InterviewMidWhat is Command Query Separation, and are there exceptions?

A method either changes state (a command) or returns information (a query), never both; atomic operations are the exception.

Calling a query any number of times is safe. Deliberate exceptions are putIfAbsent, incrementAndGet and poll: splitting them would create a race between asking and acting.

Read in post: Clean code
InterviewMidWhat are Ousterhout's three symptoms of complexity?

Change amplification, cognitive load and unknown unknowns (the worst).

Change amplification: a simple change needs edits in many places. Cognitive load: you must remember a lot to change things safely. Unknown unknowns: you don't know what you need to know. The causes are dependencies and obscurity; inconsistency is the main source of unknown unknowns.

Read in post: Clean code
InterviewMidIs DRY always right?

No. DRY is about knowledge, not characters.

Two identical snippets that change for different reasons shouldn't be merged; merging early produces wrong abstractions full of boolean flags. In practice I use the rule of three, but business rules and constants get merged immediately.

Read in post: Clean code
InterviewMidHow can you tell a class violates SRP?

Try naming it: if the most natural name is Manager or Helper, or needs an "And", it does too much.

Other signs: it changes for unrelated reasons, its tests need too many mocks, groups of methods use disjoint groups of fields.

Read in post: Clean code
InterviewSeniorThe slide adds UPDATE support by subclassing the SELECT generator. What would your review comment be?

The inheritance is wrong in meaning (an UPDATE is not a kind of SELECT) and breaks Liskov; use siblings under a common abstraction.

Code expecting a SELECT generator may receive one that emits UPDATE, and the subclass drags along fields it doesn't use. In Java 21 that is a sealed interface SqlStatement with records and a pattern-matching switch so the compiler checks exhaustiveness.

Read in post: Clean code
InterviewSeniorHow do cognitive and cyclomatic complexity differ, and how do you use them?

Cyclomatic counts independent paths (a test estimate); cognitive adds increments for nesting depth, so it tracks readability better.

Cyclomatic doesn't distinguish a flat switch from nested ifs. I set a cognitive complexity threshold (Sonar's default for Java is 15) as a quality gate on new code, without forcing a rewrite of old code.

Read in post: Clean code
InterviewSeniorHow would you bring clean code into a team with a legacy codebase?

Not with a rewrite; improve it gradually, backed by tooling and tests.

Put a few conventions into tooling (formatter, a quality gate on new code only), leave code a bit cleaner every time you touch it, refactor behind characterization tests and keep refactoring commits separate from behaviour changes. Prioritise the files that change most often according to git history, where complexity costs the most.

Read in post: Clean code
Edge caseSeniorAn exception halfway through leaves a half-updated objectThe caller catches the exception and carries on with a Cart that has the discount but no gift. Fix: do everything that can fail first and assign state once at the end, or use immutable objects (cart.withPromotion(...) returns a new one). For the database, let @Transactional roll back, and remember it cannot roll back a
void applyPromotion(Cart cart, Promotion promo) {
    cart.setDiscount(promo.amount());          // changed
    cart.setPromoCode(promo.code());           // changed
    inventory.reserveGift(promo.giftSku());    // throws
}

The caller catches the exception and carries on with a Cart that has the discount but no gift. Fix: do everything that can fail first and assign state once at the end, or use immutable objects (cart.withPromotion(...) returns a new one). For the database, let @Transactional roll back, and remember it cannot roll back an outbound HTTP call.

Read in post: Clean code
Trade-offSeniorChecked or unchecked exceptions in application codeChecked fits failures the caller routinely can recover from on the spot, in a library API that should force users to think about them (IOException when reading a user-chosen file). The cost: signatures propagate, and the methods can't be used directly in lambdas or streams. Unchecked is the default in most modern frame
  • Checked fits failures the caller routinely can recover from on the spot, in a library API that should force users to think about them (IOException when reading a user-chosen file). The cost: signatures propagate, and the methods can't be used directly in lambdas or streams.
  • Unchecked is the default in most modern frameworks: Spring translates SQLException into the unchecked DataAccessException hierarchy; JPA and Kotlin have no checked exceptions. The cost: no compiler reminder, so you need centralised handling and documentation (@throws in Javadoc).
  • In practice, for a Spring service: domain exceptions are unchecked and carry structured data; checked exceptions from libraries are wrapped at the boundary with their cause.
Read in post: Clean code
TILMidThe JDK ships UncheckedIOException for wrapping IOExceptionSince Java 8, java.io.UncheckedIOException is an unchecked exception whose constructor requires an IOException cause, and whose getCause() returns exactly IOException. The JDK uses it itself: Files.lines(...) and BufferedReader.lines() throw it when reading fails mid-stream. Using it instead of a home-made RuntimeExcep

Since Java 8, java.io.UncheckedIOException is an unchecked exception whose constructor requires an IOException cause, and whose getCause() returns exactly IOException. The JDK uses it itself: Files.lines(...) and BufferedReader.lines() throw it when reading fails mid-stream. Using it instead of a home-made RuntimeException(e) lets callers further up still recognise an I/O failure, and the original cause (say, NoSuchFileException) is not lost.

Read in post: Clean code
Edge caseMidComments aren't compiled, so they end up lyingCode gets edited, the comment doesn't: // retry 3 times sits above a line that now reads maxAttempts = 5, and readers trust the comment and misdiagnose. Push information into places that get checked: a constant name (MAXPAYMENTATTEMPTS), a type (Duration instead of long timeoutMs), a test (shouldRetryFiveTimesBeforeGiv

Code gets edited, the comment doesn't: // retry 3 times sits above a line that now reads maxAttempts = 5, and readers trust the comment and misdiagnose. Push information into places that get checked: a constant name (MAX_PAYMENT_ATTEMPTS), a type (Duration instead of long timeoutMs), a test (shouldRetryFiveTimesBeforeGivingUp).

Read in post: Clean code
Trade-offSeniorMocks, fakes or real objects in unit testsReal objects: for value objects and pure logic (PriceCalculator, Voucher). There is no reason to mock them. Fakes (simple working implementations, like a HashMap repository or Clock.fixed): for stateful dependencies. Tests assert on the end result instead of a call sequence, so they survive refactoring. Mocks: when the
  • Real objects: for value objects and pure logic (PriceCalculator, Voucher). There is no reason to mock them.
  • Fakes (simple working implementations, like a HashMap repository or Clock.fixed): for stateful dependencies. Tests assert on the end result instead of a call sequence, so they survive refactoring.
  • Mocks: when the interaction is the behaviour under test (exactly one email sent, the right event published), or for slow, hard-to-build dependencies. Needing five mocks usually means the class does too much.
  • Real integration (SQL, Kafka) is tested with Testcontainers rather than mocked JDBC. How to set up slice tests and Testcontainers in Spring Boot: testing Spring Boot.
Read in post: Clean code
Edge caseSeniorOnce vendor types leak into the domain, you can't switch vendorsWhen AcmeSmsResponse shows up in service signatures, an entity (an acmestatus column) or a Kafka event, the vendor has become part of your domain. Switching vendors or upgrading the SDK's major version turns into a multi-week project. Early warning sign: the vendor's package imported outside the adapter folder. Enforce

When AcmeSmsResponse shows up in service signatures, an entity (an acme_status column) or a Kafka event, the vendor has become part of your domain. Switching vendors or upgrading the SDK's major version turns into a multi-week project. Early warning sign: the vendor's package imported outside the adapter folder. Enforce it mechanically: an ArchUnit rule "only ..adapter.sms.. may depend on com.acme.." running in CI.

Read in post: Clean code
Trade-offSeniorRefactor incrementally or rewrite in one goIncrementally (a code-level strangler fig: wrap, replace piece by piece, delete the old): there is always a working version and each step is low-risk, but it takes discipline and there is a period where two ways coexist. Rewrite: tempting because it's "clean from day one", but you're chasing an old system that is still
  • Incrementally (a code-level strangler fig: wrap, replace piece by piece, delete the old): there is always a working version and each step is low-risk, but it takes discipline and there is a period where two ways coexist.
  • Rewrite: tempting because it's "clean from day one", but you're chasing an old system that is still changing, and you lose the tacit knowledge in odd if branches (often years of bug fixes). Rarely worth it unless the module is small and its behaviour is fully pinned by tests.
  • Prioritise code that is both complex and frequently changed (measured by commits touching the file); ugly code nobody touches can stay.
Read in post: Clean code
Edge caseSeniorRounding at an intermediate step shifts the totalOne case: 7 items at 7777.5, a GOLD customer. Subtotal 54442.5, 5% off is 2722.125, plus 30000 shipping. The old code rounds once at the end: 81720.375 becomes 81720. Rounding the discount first (2722) gives 81720.5, which becomes 81721. One dong times tens of thousands of orders is a reconciliation mismatch with the p

One case: 7 items at 7777.5, a GOLD customer. Subtotal 54442.5, 5% off is 2722.125, plus 30000 shipping. The old code rounds once at the end: 81720.375 becomes 81720. Rounding the discount first (2722) gives 81720.5, which becomes 81721. One dong times tens of thousands of orders is a reconciliation mismatch with the payment gateway and accounting. At which step to round, and HALF_UP or HALF_EVEN, is a business rule: it must be written down and tested, and the person refactoring doesn't get to decide it.

Read in post: Clean code
Edge caseSeniorA golden master only protects the inputs the generator produces20,000 green cases, yet four differences sat outside the generated input space: Double.parseDouble accepts NaN, Infinity, d/f suffixes and surrounding whitespace, while new BigDecimal(String) doesn't. Lesson: list the places where a refactor swaps a library or a type (here double to BigDecimal) and probe their edges se

20,000 green cases, yet four differences sat outside the generated input space: Double.parseDouble accepts NaN, Infinity, d/f suffixes and surrounding whitespace, while new BigDecimal(String) doesn't. Lesson: list the places where a refactor swaps a library or a type (here double to BigDecimal) and probe their edges separately; property-based testing (jqwik) gets edge values into the generator. Don't "fix" things in the same commit: record the differences as deliberate decisions.

Read in post: Clean code
InterviewJuniorWhy not just catch (Exception e) {} and move on?

Because the error vanishes without a trace and the program carries on with bad data.

For example a NaN price becomes a 0-dong order, with no logs to investigate. Catch only what you can handle, actually handle it, or let it bubble up to the shared handler.

Read in post: Clean code
InterviewJuniorWhat makes a good error message?

What failed, for which entity, why, and the original exception kept as the cause.

The type of failure; the order id or file name; the return code or bad value. No sensitive data such as card numbers or tokens.

Read in post: Clean code
InterviewJuniorWhen should you write a comment?

When you need to explain why, not what the code does.

That means a non-obvious decision, a complex algorithm, and the contract of public interfaces in Javadoc. To explain what code does, rename or extract a method instead.

Read in post: Clean code
InterviewMidChecked or unchecked exceptions for business errors in a Spring service?

Usually unchecked, carrying structured data and handled centrally with @RestControllerAdvice.

Checked exceptions spread through every signature, don't work in lambdas, and Spring itself goes unchecked (DataAccessException). Checked exceptions from libraries get wrapped at the boundary with their cause.

Read in post: Clean code
InterviewMidWhat's wrong with heavy mocking in unit tests?

Tests get coupled to the implementation: internal refactoring turns them red even though behaviour is unchanged, so people stop refactoring.

Use real value objects and pure logic, fakes for stateful dependencies, and keep mocks for interactions that are the behaviour under test. Needing many mocks usually means the class does too much.

Read in post: Clean code
InterviewMidWhat is a learning test?

A test that checks your understanding of a third-party library, not your own code.

For example: what it throws on bad input, whether it retries, its default timeout. Rerun them on upgrades to catch semantic changes before production does.

Read in post: Clean code
InterviewSeniorHow do you refactor a legacy function that has no tests?

Golden master first, then small steps with the IDE's refactoring tools, comparing after each one.

Generate many inputs including bad ones and record the old code's output; keep refactoring commits apart from behaviour changes. Add probes wherever a type or library is swapped, because a golden master only protects what the generator produces.

Read in post: Clean code
InterviewSeniorHow do you wrap a vendor SDK, and why?

A port in your own types and an adapter that is the only place importing the SDK, so switching vendors only touches the adapter.

Define an SmsSender interface and an SmsResult; the adapter translates their exceptions and error codes into your semantics and keeps the cause. Switching vendors or upgrading a major version only touches the adapter, and service tests use a fake. An ArchUnit rule in CI stops the leak.

Read in post: Clean code
InterviewSeniorA refactor shifted the total by one dong on 338 of 20,000 orders. What do you do?

Treat it as a behaviour change, not a detail: revert that step.

When and how to round is a business rule, so ask the business owner or accounting and write it down as a tested specification. If the decision is to change it, do it in its own commit, with communication and a reconciliation plan for existing orders.

Read in post: Clean code
InterviewSeniorWhen do you not refactor?

When code is ugly but stable and rarely changed.

Also not when there's no way to verify behaviour and writing the tests costs more than the benefit, or right before a risky release. Clean code is a way to lower the cost of change; where nothing changes, the benefit is close to zero.

Read in post: Clean code
Trade-offSeniorWhen the fraud check times out: fail open or fail closedFail open (treat a timeout as clean and approve): customers aren't blocked when a secondary service is slow, and no revenue is lost. But a fraudster only has to slow the fraud service down (or wait until it's overloaded) to get through. Fail closed (don't approve on timeout; move to PENDINGREVIEW or reject): safe for t
  • Fail open (treat a timeout as clean and approve): customers aren't blocked when a secondary service is slow, and no revenue is lost. But a fraudster only has to slow the fraud service down (or wait until it's overloaded) to get through.
  • Fail closed (don't approve on timeout; move to PENDING_REVIEW or reject): safe for the money, but genuine customers wait or get wrongly declined when the service is slow, so you need a follow-up path (approve asynchronously when the result arrives, or manual review).

Financial transactions usually fail closed; secondary features (recommendations, personalisation) usually fail open. What matters most is that the choice is deliberate and written down, not code that defaults to returning null and leaves callers to guess.

Read in post: Code review
Edge caseSeniorA business timeout borrowed from an infrastructure timeoutUsing spring.redis.timeout (how long to wait for one Redis command) as the wait for a business result mixes two different things: one protects a connection, the other is a promise to the user. Someone who raises the Redis timeout because the network is flaky unknowingly makes payment requests hold threads hundreds of t

Using spring.redis.timeout (how long to wait for one Redis command) as the wait for a business result mixes two different things: one protects a connection, the other is a promise to the user.

Someone who raises the Redis timeout because the network is flaky unknowingly makes payment requests hold threads hundreds of times longer. Every waiting call needs its own business timeout, set from the endpoint's SLA, with an explicit name (payment.fraud-check.timeout=2s), and the behaviour on expiry (fail-open or fail-closed) has to be decided and written down, not left to default to null.

Read in post: Code review
Edge caseMidLocalDate.now() uses the JVM's time zone, not the business'sLocalDate.now() without arguments uses ZoneId.systemDefault(), the JVM's zone: usually UTC in a container, but it can differ between dev machines, CI and production. For business rules tied to a place (check-in dates, delivery dates, payment deadlines), "today" must be computed in that place's zone: LocalDate.now(clock

LocalDate.now() without arguments uses ZoneId.systemDefault(), the JVM's zone: usually UTC in a container, but it can differ between dev machines, CI and production. For business rules tied to a place (check-in dates, delivery dates, payment deadlines), "today" must be computed in that place's zone: LocalDate.now(clock.withZone(homestay.zone())).

Injecting a Clock (a Clock.systemUTC() bean in production, Clock.fixed(...) in tests) also lets you test the cases around midnight without depending on when the tests run.

Read in post: Code review
Edge caseSeniorSending emails and publishing events inside the transactionExternal side effects (email, SMS, Kafka, webhooks) inside a @Transactional method run before you know whether the transaction will commit. If the commit fails (a deadlock, a constraint violation, a timeout), the outside world has been told about data that doesn't exist, and you can't take it back. Work you can lose: m

External side effects (email, SMS, Kafka, webhooks) inside a @Transactional method run before you know whether the transaction will commit. If the commit fails (a deadlock, a constraint violation, a timeout), the outside world has been told about data that doesn't exist, and you can't take it back.

Work you can lose: move it after the commit (@TransactionalEventListener(AFTER_COMMIT)). Work you can't: use a transactional outbox (write the event to a table in the same transaction, a relay publishes it later).

Read in post: Code review
InterviewJuniorWhat does disagree and commit mean?

Once a decision has been made through a proper process, the people who disagreed still execute it fully instead of half-heartedly or continuing the argument.

A "proper process" means all sides were heard and the options weighed. The disagreement is recorded (usually in an ADR) along with the conditions for revisiting it, so if an assumption turns out wrong there's a basis for reopening the decision.

Read in post: Code review
InterviewMidYou find a serious bug outside the scope of the PR you're reviewing. What do you do?

Leave an FYI on the PR so the author knows, but don't require the fix in that PR (unless the PR makes it worse).

Open a separate prioritised issue, or raise it immediately if it's causing an incident. Expanding a PR's scope makes the review harder and delays a change that needs to land.

Read in post: Code review
InterviewMidYou're reviewing code that compares a check-in date with LocalDate.now(). What do you comment?

LocalDate.now() uses the JVM's time zone, so I'd ask for an injected Clock and computing the date in the business location's zone.

The JVM usually runs on UTC in a container, so between midnight and 7 a.m. Vietnam time the server's "today" is still yesterday. Fix it with LocalDate.now(clock.withZone(zone)), plus tests with a fixed clock around midnight.

Read in post: Code review
InterviewMidAn anagram-grouping solution uses the sum of character codes as the key. How do you review it?

It's wrong: two strings with different letters can share a sum ("ad" and "bc" are both 197) and get grouped together.

A sum is just a hash, a necessary condition. The map key has to be a canonical form that uniquely identifies the group, like the sorted string (O(k log k)) or a 26-letter count array (O(k)). Add a test with that pair so the bug can't come back.

Read in post: Code review
InterviewSeniorYou and the author disagree about a design in a PR. How do you handle it?

Make sure we understand each other, move the argument to context and evidence, then decide, disagree and commit, and record an ADR.

  • Summarise each other's argument until both agree it's been understood; write down the pros and cons of each option.
  • Establish the context and which qualities are being prioritised; if an assumption is measurable, build a PoC or measure.
  • After two rounds of comments, talk in person. Still no agreement: take it to the group or the tech lead.
  • Once decided: disagree and commit, and record an ADR with conditions for revisiting it.
Read in post: Code review
InterviewSeniorHow do you write a comment about a serious mistake by a new colleague so it actually helps?

Label it TODO, state the concrete consequence, the cause and the fix; write about the code, not the person.

Concrete consequences look like "the first request will NPE" or "the customer gets charged twice". Offer a fix or a code suggestion, link to docs, and mention what's good in the PR too. If several issues share a root cause (say, misunderstanding @RequiredArgsConstructor), a 10-minute conversation beats 10 comments.

Read in post: Code review
InterviewSeniorA review reveals a synchronous endpoint that waits up to 5 minutes for a Kafka reply. How do you argue it?

With Little's law: busy threads = request rate × wait time, so a 5-minute wait exhausts the threads at under one request per second.

Tomcat's 200 worker threads with each request waiting 5 seconds only sustain 40 requests per second; with a 5-minute wait the whole service stops answering. I'd ask for a separate business timeout from the SLA, an explicit behaviour on expiry (fail-closed for financial transactions), and an asynchronous API in the longer term.

Read in post: Code review
Trade-offSeniorReview before merge, after merge, or pair programmingBefore merge (the GitHub/GitLab default): stops problems before they reach main and leaves a written discussion. The price: waiting time, and an easy bottleneck. After merge (for small changes in high-trust teams with feature flags and fast rollback): never blocks, but problems are already on main, possibly in producti
  • Before merge (the GitHub/GitLab default): stops problems before they reach main and leaves a written discussion. The price: waiting time, and an easy bottleneck.
  • After merge (for small changes in high-trust teams with feature flags and fast rollback): never blocks, but problems are already on main, possibly in production.
  • Pair/mob programming: continuous review while writing, instant feedback, but two people for one task and no written record.

Many teams mix them: pairing for hard parts or new joiners; review before merge for anything touching money, security or schemas; "merge then review" for docs and small config changes.

Read in post: Code review
Edge caseMidReading only the diff misses bugs in the code that didn't changeA diff doesn't show the places that should have changed with it: changing what a method returns without looking at its callers; adding an enum value without checking every switch on that enum; adding a column with no migration; changing an entity without updating the DTO and API docs. When a change touches a public met

A diff doesn't show the places that should have changed with it:

  • changing what a method returns without looking at its callers;
  • adding an enum value without checking every switch on that enum;
  • adding a column with no migration; changing an entity without updating the DTO and API docs.

When a change touches a public method or a shared type, open the IDE (or the review tool's "find usages") and check the call sites.

Read in post: Code review
Edge caseMidThe "Google 250 lines" figure is misattributedGoogle (eng-practices, "small CLs"): about 100 lines is usually reasonable, 1,000 lines usually too large, at the reviewer's discretion. 200–400 lines comes from a SmartBear study at Cisco: defect detection drops noticeably once a review goes beyond ~400 lines, an inspection rate of ~500 lines per hour, or 60–90 minute
  • Google (eng-practices, "small CLs"): about 100 lines is usually reasonable, 1,000 lines usually too large, at the reviewer's discretion.
  • 200–400 lines comes from a SmartBear study at Cisco: defect detection drops noticeably once a review goes beyond ~400 lines, an inspection rate of ~500 lines per hour, or 60–90 minutes.

Both reach the same conclusion: smaller is better. When you quote them in team docs, cite the right source.

Read in post: Code review
Trade-offMidOne big PR or a stack of small onesOne big PR: the whole picture at once, no branches to juggle. But reviews get slow and shallow, risk lands in one merge, and partial rollback is hard. Many small PRs: each gets a careful 15–30 minute review, merges early, conflicts stay small. The cost: rebasing the stack when the first PR changes, and reviewers can lo
  • One big PR: the whole picture at once, no branches to juggle. But reviews get slow and shallow, risk lands in one merge, and partial rollback is hard.
  • Many small PRs: each gets a careful 15–30 minute review, merges early, conflicts stay small. The cost: rebasing the stack when the first PR changes, and reviewers can lose the big picture.

Middle ground: one design doc or issue stating where it's heading, then a stack of small PRs pointing back to it.

Read in post: Code review
TILMidConventional Comments: label, decoration and subject on one lineConventional Comments is a public convention for review comments in the form label (decoration): subject, e.g. issue (blocking): field isn't final so it's never injected, suggestion (non-blocking): ..., nitpick: ..., question: ..., praise: .... The decoration separates "what kind of feedback" from "does it block the me

Conventional Comments is a public convention for review comments in the form label (decoration): subject, e.g. issue (blocking): field isn't final so it's never injected, suggestion (non-blocking): ..., nitpick: ..., question: ..., praise: .... The decoration separates "what kind of feedback" from "does it block the merge".

The course's labels map roughly: TODO → issue (blocking), NIT → nitpick, OPTIONAL → suggestion (non-blocking), FYI → note. Either set works, as long as the whole team uses the same one and it's written in the contributing guide.

Read in post: Code review
Edge caseMidUnlabelled comments turn every suggestion into a merge conditionWithout labels, authors (especially new ones) assume every comment must be addressed, including matters of taste. PRs get held for extra rounds over things that don't matter, and reviewers can't tell whether an ignored comment was rejected or missed. The fix: label every comment; approve with "LGTM, a few NITs up to yo

Without labels, authors (especially new ones) assume every comment must be addressed, including matters of taste. PRs get held for extra rounds over things that don't matter, and reviewers can't tell whether an ignored comment was rejected or missed.

The fix: label every comment; approve with "LGTM, a few NITs up to you" when only non-blocking ones remain; the author replies to each comment (done, or why not).

Read in post: Code review
Trade-offSeniorHow much should machines block a merge?Block a lot (formatting, lint, tests, minimum coverage, a quality gate): nobody nags about trivia. But slow or flaky checks make people hate CI and look for ways around it; a hard coverage threshold (say 90%) breeds empty tests just to hit the number. Block little, warn a lot: flexible, but warnings that don't block ge
  • Block a lot (formatting, lint, tests, minimum coverage, a quality gate): nobody nags about trivia. But slow or flaky checks make people hate CI and look for ways around it; a hard coverage threshold (say 90%) breeds empty tests just to hit the number.
  • Block little, warn a lot: flexible, but warnings that don't block get ignored over time.

In practice: block what's fast and certain (build, tests, formatting, secrets), warn on what needs judgement (code smells, diff coverage), and fix flaky checks immediately instead of rerunning until green.

Read in post: Code review
InterviewJuniorWhat is code review for?

Quality control and growing people.

Quality covers bugs, security, design and maintainability of the codebase. People: reviewer and author learn from each other, and practise presenting and listening. Knowledge spreading through the team comes with it. Review doesn't replace tests and isn't the place to impose personal taste.

Read in post: Code review
InterviewJuniorWhat do you do before sending a PR for review?

Self-review the diff, make sure CI is green, and write a description with enough context.

Remove debug code and run the tests. The description covers why, what changed, how it was tested, risks and rollback. Keep the PR small and focused on one thing; refactoring and formatting go in separate PRs.

Read in post: Code review
InterviewJuniorWhat do the TODO, NIT, OPTIONAL and FYI labels mean in review comments?

TODO must be fixed before merging; NIT is a small non-blocking detail; OPTIONAL is a suggestion the author decides on; FYI is information only.

Labels tell the author which comments are merge conditions, and keep reviewers from accidentally blocking a PR over taste.

Read in post: Code review
InterviewMidReviewing a backend PR, what do you look at beyond "does it work"?

What happy-path tests don't catch: concurrency, dependency failures, security, performance, compatibility and observability.

  • Concurrency and transaction scope (two requests at once, side effects inside transactions).
  • Failures and timeouts of dependencies.
  • Security: input, authorisation, sensitive data in logs.
  • Performance: N+1, missing indexes, no pagination.
  • Compatibility: migrations on large tables, API changes.
  • Logs and metrics; and whether the tests cover failure cases.
Read in post: Code review
InterviewMidHow big should a PR be, and why?

As small as practical: Google's guide considers ~100 lines reasonable and 1,000 usually too large.

A SmartBear study at Cisco found defect detection drops once a review exceeds ~400 lines or 60–90 minutes. The exact number matters less than the principle: small PRs get careful, fast reviews; big PRs get skimmed.

Read in post: Code review
InterviewMidA reviewer leaves 30 comments about naming and formatting. How do you fix that at team level?

Move whatever a machine can check into CI, and agree on labels so taste is a non-blocking NIT.

A formatter, Checkstyle, naming conventions in the contributing guide, all run in CI. Talk to the reviewer privately about focusing on design and behaviour. Formatting comments on PRs should all but disappear.

Read in post: Code review
InterviewSeniorHow do you keep code review from becoming the team's bottleneck?

Small PRs, a measured response-time target, and automating whatever machines can do.

  • A response target of a few hours, at most a business day, and track it.
  • CODEOWNERS to auto-assign and spread load; allow approving with NITs.
  • Pair with new joiners instead of many review rounds.
  • For low-risk changes, allow merge-then-review.
  • Measure PR cycle time so you see the problem instead of guessing.
Read in post: Code review
InterviewSeniorWhich rules do you put in CI to reduce reviewers' work on a Spring Boot codebase?

A formatter, lint and static analysis, tests with diff coverage, dependency and secret scanning, and architecture rules in ArchUnit.

Concretely: Spotless, Checkstyle, Error Prone or SpotBugs. ArchUnit rules: controllers don't call repositories, fields in @Service classes are final, the domain package doesn't depend on web. Block on checks that are fast and certain; warn on ones that need judgement; fix flaky checks immediately.

Read in post: Code review
Edge caseSeniormaxLifetime longer than the database or network timeoutHikariCP recommends a maxLifetime a few seconds shorter than any limit the DB or infrastructure puts on connections: MySQL waittimeout (8 hours by default, often lowered to minutes), PgBouncer serveridletimeout, firewalls, AWS NAT Gateway and NLB (350 idle seconds). If a box in the middle drops the connection first, th

HikariCP recommends a maxLifetime a few seconds shorter than any limit the DB or infrastructure puts on connections: MySQL wait_timeout (8 hours by default, often lowered to minutes), PgBouncer server_idle_timeout, firewalls, AWS NAT Gateway and NLB (350 idle seconds).

If a box in the middle drops the connection first, the pool hands out a dead one: Connection reset, or a hang until TCP gives up. keepaliveTime (say 60 seconds) stops idle connections from looking idle; maxLifetime replaces them before the lifetime limit.

Read in post: Connection pooling and HikariCP
TILMidLeak detection only reports, it doesn't reclaim the connectionWith leakDetectionThreshold=2000, borrowing a connection and holding it for 2.5 seconds made HikariCP log: WARN ProxyLeakTask - Connection leak detection triggered for conn262: url=jdbc:h2:mem:lab user=SA on thread main, stack trace follows followed by the stack trace of the getConnection() call. The connection isn't t

With leakDetectionThreshold=2000, borrowing a connection and holding it for 2.5 seconds made HikariCP log:

WARN ProxyLeakTask - Connection leak detection triggered for conn262: url=jdbc:h2:mem:lab user=SA on thread main, stack trace follows

followed by the stack trace of the getConnection() call. The connection isn't taken back; when it is finally returned, HikariCP logs unleaked at INFO. Set the threshold above your longest legitimate transaction (e.g. 30–60 seconds). How a leak keeps a transaction open for hours is in Harmful transactions.

Read in post: Connection pooling and HikariCP
Trade-offSeniorA big pool or a small poolA big pool cuts waiting in the app while the DB still has spare capacity; once the DB is saturated, more connections only add CPU, lock and memory contention: every query slows down. A small pool keeps the DB in its efficient zone and pushes the queue back to the app, where connectionTimeout can cut it and the pending

A big pool cuts waiting in the app while the DB still has spare capacity; once the DB is saturated, more connections only add CPU, lock and memory contention: every query slows down. A small pool keeps the DB in its efficient zone and pushes the queue back to the app, where connectionTimeout can cut it and the pending metric can see it.

Start small, load test, and grow only when pending is high and the DB has spare CPU. If too many instances hit max_connections, use PgBouncer.

Read in post: Connection pooling and HikariCP
Edge caseSeniorPrepared statements through PgBouncer transaction modeTwo fixes: PgBouncer 1.21+ with maxpreparedstatements above 0 (the current docs list a default of 200) so PgBouncer tracks protocol-level prepared statements; or prepareThreshold=0 in the JDBC URL. SQL-level PREPARE/EXECUTE still breaks. The application still keeps HikariCP in front of PgBouncer; then maxLifetime and k

Two fixes: PgBouncer 1.21+ with max_prepared_statements above 0 (the current docs list a default of 200) so PgBouncer tracks protocol-level prepared statements; or prepareThreshold=0 in the JDBC URL. SQL-level PREPARE/EXECUTE still breaks.

The application still keeps HikariCP in front of PgBouncer; then maxLifetime and keepalive must fit PgBouncer's client_idle_timeout.

Read in post: Connection pooling and HikariCP
Edge caseMidopen-in-view holds the connection until the request endsSpring Boot enables spring.jpa.open-in-view=true by default (and logs a warning at startup). The EntityManager stays open for the whole request so lazy loading works in the controller, so after the first DB access the connection can be held until the response is written, HTTP calls included. For APIs, set it to false a

Spring Boot enables spring.jpa.open-in-view=true by default (and logs a warning at startup). The EntityManager stays open for the whole request so lazy loading works in the controller, so after the first DB access the connection can be held until the response is written, HTTP calls included. For APIs, set it to false and load everything you need in the service (fetch joins, DTO projections).

Read in post: Connection pooling and HikariCP
InterviewJuniorWhy does an application need a connection pool?

Because opening a DB connection is expensive (TCP, TLS, authentication, a server process), while reusing an existing one is almost free.

A pool also caps connections to the DB, so under rising load the app queues instead of knocking the database over. Measured on loopback with H2: about 1.1 ms to open a new one, about 0.045 ms to borrow from the pool.

Read in post: Connection pooling and HikariCP
InterviewJuniorThe app logs "Connection is not available, request timed out after 30000ms". What does it mean?

The pool had no free connection and the thread waited the full connectionTimeout (30 seconds by default) without anyone returning one.

Compare active with total in the message, then look for long holds: long transactions, remote calls inside transactions, connection leaks, or a slow DB.

Read in post: Connection pooling and HikariCP
InterviewMidWhat are maxLifetime and keepaliveTime for?

maxLifetime replaces a connection before the DB or a network device closes it; keepaliveTime periodically touches idle connections so they don't look idle.

maxLifetime must be a few seconds shorter than every limit on the path (MySQL wait_timeout, firewalls, NAT). HikariCP subtracts up to 25% at random so connections don't all expire together.

Read in post: Connection pooling and HikariCP
InterviewMidWhy is calling HTTP inside @Transactional dangerous?

The connection is held for the whole HTTP call, so hold time grows with the other side's latency and the pool runs dry fast.

Experiment: holding 50 ms longer slowed 200 tasks from 55 ms to 1,100 ms; with a 500 ms timeout, half of them failed. Make the remote call first, then open a short transaction to write.

Read in post: Connection pooling and HikariCP
InterviewMidWhat does PgBouncer transaction mode break?

Anything tied to the session: session-level SET, session advisory locks, LISTEN/NOTIFY, temp tables, WITH HOLD cursors, and server-side prepared statements unless configured.

Use SET LOCAL, PgBouncer 1.21+ with max_prepared_statements, or prepareThreshold=0 in pgjdbc.

Read in post: Connection pooling and HikariCP
InterviewSeniorHow do you size a connection pool?

Start from Little's Law (throughput × hold time) and the DB's (cores × 2) + disks formula, divide by the number of instances, and check the total stays below max_connections.

Then load test, watching pending, usage and DB CPU. Grow only when threads wait and the DB has headroom; if the DB is saturated, shorten hold times. With too many instances, use PgBouncer.

Read in post: Connection pooling and HikariCP
InterviewSeniorDoes pool configuration change when you move to virtual threads?

The pool size doesn't need to grow, but connectionTimeout must be short and concurrency explicitly bounded, because the pool becomes the main back-pressure point.

Previously Tomcat's 200 threads limited how many could wait; with virtual threads thousands may wait for a connection. On JDK 21–23, also watch for pinning when a driver wraps I/O in synchronized.

Read in post: Connection pooling and HikariCP
InterviewSeniorAfter a slow-DB incident the pool doesn't recover: pending stays high even though the DB is fine. What do you suspect?

A backlog and retries keeping load high, connections that died silently behind NAT and are slow to validate, or a leak holding connections.

Look at usage p99 (abnormally long holds), timeout, leak detection logs, and pg_stat_activity (idle in transaction). Cut retries, use a short connectionTimeout to drain the queue, and a maxLifetime shorter than the network timeouts so dead connections get replaced.

Read in post: Connection pooling and HikariCP
Trade-offSeniorAn AWAY/RETURN direction column or a leg numberdirection 0/1 as in v2: matches the "one-way or round trip" product, UNIQUE (bookingid, direction) blocks a booking with two outbound directions, and "the return leg" is a trivial query. legno 1..n: stretches to multi-city itineraries (Hanoi → Da Nang → Saigon → Hanoi) with no schema change, but loses the meaning "this
  • direction 0/1 as in v2: matches the "one-way or round trip" product, UNIQUE (booking_id, direction) blocks a booking with two outbound directions, and "the return leg" is a trivial query.
  • leg_no 1..n: stretches to multi-city itineraries (Hanoi → Da Nang → Saigon → Hanoi) with no schema change, but loses the meaning "this is the return" (inferred from airports), and round-trip fare rules have to be redefined.
  • Connecting flights are another matter: one direction made of several segments, which needs a booking_segment table under booking_direction.

Choose direction when you sell only one-way and round trips; choose leg_no + segments if multi-city is coming. Changing later is expensive because reports and refund rules depend on it, so ask product before you commit.

Read in post: Airline booking
Edge caseSeniorThe sum of rounded VAT lines differs from the VAT of the total10% VAT on three lines of 333,333 VND: rounding each line gives 33,333 × 3 = 99,999, while rounding the VAT of the 999,999 total gives 100,000. That one dong makes total = ticket + fee + vat disagree with the sum of the lines, and reconciliation against the gateway and the e-invoice reports a mismatch every day. The fi

10% VAT on three lines of 333,333 VND: rounding each line gives 33,333 × 3 = 99,999, while rounding the VAT of the 999,999 total gives 100,000. That one dong makes total = ticket + fee + vat disagree with the sum of the lines, and reconciliation against the gateway and the e-invoice reports a mismatch every day.

The fix: settle one rule (VAT per line or on the total, which rounding mode, which line absorbs the difference), implement it in one place, and store the rounded results in booking_line. The lines are the source of truth; the header is just their sum, guarded by a CHECK and a reconciliation query.

Read in post: Airline booking
Edge caseSeniorPassengers' identity documents sitting in plain textNational ID and passport numbers and dates of birth are sensitive personal data (Decree 13/2023 in Vietnam, GDPR in Europe). Stored as plain text, they end up in every backup, reporting replica and slow-query log. At minimum: encrypt the column with keys in a KMS, mask it in logs, restrict read access, delete or anonym

National ID and passport numbers and dates of birth are sensitive personal data (Decree 13/2023 in Vietnam, GDPR in Europe). Stored as plain text, they end up in every backup, reporting replica and slow-query log. At minimum: encrypt the column with keys in a KMS, mask it in logs, restrict read access, delete or anonymize it after a retention period; if you need lookups, add a salted hash column.

Read in post: Airline booking
TILSeniorA DEFERRABLE constraint trigger can check a multi-row invariant at COMMITA CHECK constraint only sees one row, so it can't express "a transaction's entries sum to zero". PostgreSQL has CREATE CONSTRAINT TRIGGER ... DEFERRABLE INITIALLY DEFERRED: the trigger only runs at COMMIT, once all entries are in; if the sum isn't zero, COMMIT fails and the whole transaction rolls back. MySQL has no de

A CHECK constraint only sees one row, so it can't express "a transaction's entries sum to zero". PostgreSQL has CREATE CONSTRAINT TRIGGER ... DEFERRABLE INITIALLY DEFERRED: the trigger only runs at COMMIT, once all entries are in; if the sum isn't zero, COMMIT fails and the whole transaction rolls back.

MySQL has no deferred constraints or triggers. On MySQL you check in code before committing (insert all entries in one multi-row INSERT) and periodically run a reconciliation query GROUP BY txn_id HAVING sum(amount) <> 0.

Read in post: Airline booking
Trade-offSeniorDebit/credit columns on the transaction or a separate entries tabledebitacc, creditacc, amount on one row (v2's transaction table): simple, balanced by construction; good enough for a wallet moving money between two people. A multi-row entry table (v2's "Entry: double-entry" note): expresses multi-legged transactions (payouts net of fees, revenue shares with partners, taxes), and a ba
  • debit_acc, credit_acc, amount on one row (v2's transaction table): simple, balanced by construction; good enough for a wallet moving money between two people.
  • A multi-row entry table (v2's "Entry: double-entry" note): expresses multi-legged transactions (payouts net of fees, revenue shares with partners, taxes), and a balance is sum(amount) over one table; but you have to guarantee balance yourself.
  • Stored balances on account: fast reads, but busy accounts (like GATEWAY_CLEARING) become a hot row just like the seat counter. Usually you store balances only for user accounts and compute system accounts per period.

With fees, partial refunds or revenue splits, use an entries table from day one; switching later means rewriting every report.

Read in post: Airline booking
Edge caseSeniorBulk UPDATEs in JPQL or SQL don't bump the version or write history@Version only works when the entity goes through the persistence context. An expiry job's @Modifying @Query("update Booking b set b.status = 'EXPIRED' where ..."), or a hand-written SQL fix-up script, updates rows without bumping the version (unless you write version = version + 1 yourself) and bypasses the code that w

@Version only works when the entity goes through the persistence context. An expiry job's @Modifying @Query("update Booking b set b.status = 'EXPIRED' where ..."), or a hand-written SQL fix-up script, updates rows without bumping the version (unless you write version = version + 1 yourself) and bypasses the code that writes booking_history.

The result: a request holding the old version can still overwrite the status the job just set, and the history has holes. Every bulk UPDATE on a versioned table must bump the version and write history itself, or history must come from a database trigger so no write path slips through.

Read in post: Airline booking
Edge caseMidOptimistic locking on the seat counter creates a retry stormOptimistic locking suits bookings because two people editing the same booking is rare. Apply WHERE version = ? to the seat counter of a flight that's selling out and you get the opposite: hundreds of requests read version 57, one wins, the rest retry, and again only one wins. Retries grow with the square of the number

Optimistic locking suits bookings because two people editing the same booking is rare. Apply WHERE version = ? to the seat counter of a flight that's selling out and you get the opposite: hundreds of requests read version 57, one wins, the rest retry, and again only one wins. Retries grow with the square of the number of contenders, and CPU and the connection pool run out before the seats do. For highly contended rows, use a conditional UPDATE on the value (booked + q <= sell_limit), not a version (see part 2).

Read in post: Airline booking
Trade-offSeniorWhere to write history: application code, a trigger, Envers, CDC or event sourcingFor bookings, the pragmatic choices are a trigger (tested: the expiry job sets SET LOCAL app.actor = 'job:expire-bookings' and the trigger records exactly that actor in the history) or application code with mandatory tests for every write path. History tables grow fast, so partition them by month and set a retention po
Approach Pros Cons
Application code (the v2 pattern) Explicit, carries business context (changed_by, reason) Any write path that forgets to call it loses history; bulk UPDATEs and manual scripts bypass it
Database trigger No write path slips through, even manual SQL; the actor is passed via SET LOCAL app.actor Logic hidden in the DB, hard to test; adds time to every write
Hibernate Envers Almost no code to write Only sees changes made through JPA; audit tables in Envers's format
CDC (Debezium reading the WAL/binlog) Doesn't touch the write path, captures every change, ships it to a separate store More infrastructure; loses the "who and why" unless written alongside
Event sourcing History is the source of truth; rebuild any past state Changes the whole programming model, complex queries; far too heavy for one booking table

For bookings, the pragmatic choices are a trigger (tested: the expiry job sets SET LOCAL app.actor = 'job:expire-bookings' and the trigger records exactly that actor in the history) or application code with mandatory tests for every write path. History tables grow fast, so partition them by month and set a retention policy.

Read in post: Airline booking
InterviewJuniorWhy not store money as a double?

Because a double is binary floating point: it can't represent many decimal values exactly (0.1 + 0.2 ≠ 0.3), and errors accumulate.

Store an integer in the currency's minor unit (bigint, long) plus a currency code, or numeric/BigDecimal when you need rates, and settle the rounding rule in one place.

Read in post: Airline booking
InterviewJuniorWhy split a booking into booking_direction and booking_line?

Because a booking can have two directions, each with its own fare, fees and VAT, and each can be cancelled or refunded separately.

Keeping outbound and return as two columns is a repeating group. Splitting them into rows gives each direction its own tickets, money and status, and reporting by money type becomes a sum over lines.

Read in post: Airline booking
InterviewMidHow does optimistic locking with a version column work?

Read the row with its version; on write, add WHERE version = :readVersion and increment it; zero rows updated means someone else wrote first.

Then re-read and decide again, or return 409. No lock is held while the user thinks. It suits low contention; on heavily contended rows it causes retry storms. JPA does it automatically with @Version.

Read in post: Airline booking
InterviewMidDoes storing total_amount on the booking break normalization, and why store it anyway?

Yes, because it can be derived from the lines; store it anyway because it's the figure locked in at checkout and sent to the payment gateway.

It must not change when prices change, and it keeps booking lists fast. Control the drift risk with a single code path that creates bookings, an internal CHECK, and a periodic reconciliation query.

Read in post: Airline booking
InterviewSeniorHow would you design a double-entry ledger for a booking system?

Three tables — accounts, transactions, entries — with two invariants: each transaction's entries sum to zero, and entries are append-only.

  • Transactions: type, booking, external reference with a unique constraint. Entries: transaction, account, signed amount.
  • Balance: a deferred constraint trigger on PostgreSQL; a check in code plus a reconciliation query on MySQL. Mistakes are fixed with reversing transactions.
  • Accounts: money held by the gateway, the bank, customer prepayments (a liability), fees, and revenue recognized once the flight has flown.
  • Balances are sums of entries; only store them when measurements show you need to, because they create hot rows.
Read in post: Airline booking
InterviewSeniorWhy not just use debit_account and credit_account columns on the transaction?

Because many real transactions have more than two legs: a gateway payout net of fees has three (bank, fee, money held by the gateway).

Revenue shares with partners and tax splits are the same. Two columns force you to invent fake transactions or lose information. An entries table expresses every case, at the cost of guaranteeing balance yourself.

Read in post: Airline booking
InterviewSeniorA job bulk-updates bookings to EXPIRED. What can go wrong with optimistic locking and history?

A bulk UPDATE bypasses JPA, so it doesn't bump the version or write history: a request holding an old version can still overwrite the row, and the history has gaps.

Fix: the job sets version = version + 1 itself with a status condition (WHERE status = 'PENDING_PAYMENT'), writes history through a trigger or in the same statement with a CTE, and never expires a booking with a payment in progress (ask the gateway first).

Read in post: Airline booking
Edge caseMidCheck-then-act inside @Transactional still oversellsAt READ COMMITTED (PostgreSQL's default) and REPEATABLE READ (MySQL's default), a plain SELECT takes no row lock. Two transactions both read booked = 175, both pass the check, both write 176: you oversell and lose an update. Fix: put the condition into the write (... WHERE ... AND booked + :q <= selllimit, then check t

At READ COMMITTED (PostgreSQL's default) and REPEATABLE READ (MySQL's default), a plain SELECT takes no row lock. Two transactions both read booked = 175, both pass the check, both write 176: you oversell and lose an update. Fix: put the condition into the write (... WHERE ... AND booked + :q <= sell_limit, then check the row count), or lock first with SELECT ... FOR UPDATE.

Read in post: Airline booking
Edge caseSeniorDoing slow work inside the transaction that holds the counter's row lockHold the lock for 200 ms because the transaction calls the pricing service, the payment gateway or sends an email, and that flight is down to ~5 bookings a second, with the lock queue draining the connection pool. Rule: compute and call external systems before the transaction; the transaction contains only the conditio

Hold the lock for 200 ms because the transaction calls the pricing service, the payment gateway or sends an email, and that flight is down to ~5 bookings a second, with the lock queue draining the connection pool. Rule: compute and call external systems before the transaction; the transaction contains only the conditional UPDATE and related INSERTs; side effects go through an outbox (a table of events written in the same transaction and sent after commit). Set a lock_timeout (the maximum time to wait for a lock) so a request that waits too long fails fast instead of hanging.

Read in post: Airline booking
Edge caseSeniorSKIP LOCKED can report sold out while seats are still freeSKIP LOCKED also skips rows locked by a transaction that may still commit or roll back. A flight has exactly 2 seats left, A locks both and then rolls back (payment error, timeout): B, running at that moment, sees nothing and says "sold out", even though a second later both seats are free. Verified on PostgreSQL 16: B

SKIP LOCKED also skips rows locked by a transaction that may still commit or roll back. A flight has exactly 2 seats left, A locks both and then rolls back (payment error, timeout): B, running at that moment, sees nothing and says "sold out", even though a second later both seats are free. Verified on PostgreSQL 16: B got an empty result, and C, running after A's rollback, got both seats. The fix: when it comes back short, run a non-locking count (AVAILABLE seats and HELD seats not yet expired) to tell "truly sold out" from "temporarily held", then say "someone is holding these seats, try again in a few seconds".

Read in post: Airline booking
TILSeniorA FOR UPDATE over a partial index still re-filters the status conditionThe partial index WHERE status = 'AVAILABLE' (an index that only contains rows matching the condition) holds only free seats, yet EXPLAIN still shows Filter: (status = 'AVAILABLE'). The reason: the index can point at a stale row version. Once the row is locked (the LockRows node), PostgreSQL re-checks the condition aga

The partial index WHERE status = 'AVAILABLE' (an index that only contains rows matching the condition) holds only free seats, yet EXPLAIN still shows Filter: (status = 'AVAILABLE'). The reason: the index can point at a stale row version. Once the row is locked (the LockRows node), PostgreSQL re-checks the condition against the latest version (EvalPlanQual), because someone may have just flipped the seat to HELD and committed. That's why seat picking never returns a seat that was just grabbed, even when the index hasn't caught up.

Read in post: Airline booking
Edge caseSeniorLocking seats one by one in click order causes deadlocksPostgreSQL detects the deadlock after deadlocktimeout (1 second by default) and aborts one transaction; MySQL InnoDB detects it almost immediately and rolls back the smaller transaction. The fix: lock all the seats in one SELECT ... WHERE seatcode = ANY(:seats) ORDER BY seatcode FOR UPDATE, then do a conditional UPDATE

PostgreSQL detects the deadlock after deadlock_timeout (1 second by default) and aborts one transaction; MySQL InnoDB detects it almost immediately and rolls back the smaller transaction. The fix: lock all the seats in one SELECT ... WHERE seat_code = ANY(:seats) ORDER BY seat_code FOR UPDATE, then do a conditional UPDATE on status = 'AVAILABLE' and compare the row count. Keep a retry for deadlock errors anyway (SQLSTATE 40P01 on PostgreSQL, error 1213 on MySQL), because other code paths may lock in a different order.

Read in post: Airline booking
Trade-offMidRelease expired holds with a periodic job or treat them as free at read timePeriodic job: reads and indexes stay simple (just status = 'AVAILABLE'), but an expired seat stays "held" until the next run (up to a minute). The job must be safe with several instances running (a conditional update like the one above is enough; see Cron jobs). Lazy expiry at read time: the seat frees up the second it
  • Periodic job: reads and indexes stay simple (just status = 'AVAILABLE'), but an expired seat stays "held" until the next run (up to a minute). The job must be safe with several instances running (a conditional update like the one above is enough; see Cron jobs).
  • Lazy expiry at read time: the seat frees up the second it expires, with no dependency on a job; but every read and hold statement must remember the double condition, the partial index no longer covers everything, and it's easy for one code path to forget.
  • In practice, use both: the lazy condition in the hold statement so nobody is turned away wrongly, and the cleanup job so the table stays tidy and reports are correct. Before releasing the seats of a booking waiting for payment, make sure no payment is in flight (see the payment gateway integration post).
Read in post: Airline booking
Trade-offSeniorHolding inventory with a conditional update, a pessimistic lock, an optimistic lock or RedisConditional update (WHERE booked + q <= selllimit or WHERE status = 'AVAILABLE', then count rows): one statement, no prior read, shortest lock hold. The default for both counters and chosen seats. Pessimistic lock (SELECT ... FOR UPDATE, then decide in Java): when the check is too complex for a WHERE; remember ORDER BY
  • Conditional update (WHERE booked + q <= sell_limit or WHERE status = 'AVAILABLE', then count rows): one statement, no prior read, shortest lock hold. The default for both counters and chosen seats.
  • Pessimistic lock (SELECT ... FOR UPDATE, then decide in Java): when the check is too complex for a WHERE; remember ORDER BY to lock in a fixed order, and keep the transaction short.
  • SKIP LOCKED: only fits "any row will do" (auto-assignment, job queues); pointless for "this exact seat".
  • Optimistic locking with version: good under low contention (editing booking details); bad for a hot counter, because hundreds of requests retry at once.
  • Hold in Redis first (DECR or a Lua script with a TTL), write to the DB afterwards: survives flash sales at tens of thousands of requests a second, at the price of two sources of truth to reconcile. Only worth it once you've measured the DB as the bottleneck.
Read in post: Airline booking
InterviewJuniorWhat is check-then-act and why is it wrong under concurrency?

Reading state, checking a condition in code, then writing based on the value you read; between the read and the write another request may have changed the data.

Two requests both pass the check and both write: you oversell and lose an update. Fix it by moving the condition into the write and checking the row count, or by locking the row before reading.

Read in post: Airline booking
InterviewMidWrite the SQL that holds inventory on a counter correctly under concurrency

UPDATE flight_inventory SET booked = booked + :q WHERE flight_id = :f AND fare_class = :c AND booked + :q <= sell_limit, then check the row count: 1 means held, 0 means sold out.

Don't SELECT first and UPDATE afterwards (check-then-act). It's correct because PostgreSQL re-evaluates the WHERE on the new version after waiting for the lock, and a MySQL UPDATE is a current read.

Read in post: Airline booking
InterviewMidWhen do you use SKIP LOCKED, and what's the trap?

When "any row will do": auto-assigning seats, job queues with many workers. The trap: it can report sold out when seats will be free a moment later.

Each transaction skips locked rows instead of waiting, so they don't queue on the first few rows. But it also skips rows locked by transactions that are about to roll back; double-check with a non-locking count. Don't use it for "exactly seat 12A".

Read in post: Airline booking
InterviewMidTwo customers pick the same two seats. How do you avoid a deadlock?

Lock all the seats you need in one statement in a fixed order (ORDER BY seat_code FOR UPDATE), then do a conditional UPDATE on status = 'AVAILABLE' and compare row counts.

Locking one by one in click order locks crosswise. Keep a retry for deadlock errors, because other code paths may lock in a different order.

Read in post: Airline booking
InterviewSeniorA few hundred people book the same Tết holiday flight at once. How does your design cope?

The load concentrates on one flight, so the problem is contention, not total throughput: keep the hold transaction tiny and set a lock_timeout.

  • The transaction holds only the conditional UPDATE and INSERTs; pricing and external calls happen before it, side effects go via an outbox.
  • Per-seat rows: contention spreads over seats; auto-assignment uses SKIP LOCKED.
  • Counter: the ceiling is about one over the lock hold time; if measurements show that's not enough, hold in Redis with a TTL first and write to the DB afterwards, or put a virtual waiting room in front of the booking page.
  • Measure with a load test aimed at one flight, not spread evenly.
Read in post: Airline booking
InterviewSeniorWhich layers do you use to guarantee a seat is never sold to two people?

Three layers: application (conditional UPDATE, row-count check), schema (constraints), operations (reconciliation and alerts). Never trust a single one.

  • Schema: the primary key (flight_id, seat_code) on seat inventory, a CHECK tying status to booking_id, and a partial unique index on (flight_id, seat_code) for active tickets.
  • Operations: periodic reconciliation queries looking for seats with two tickets or tickets that disagree with seat status.
  • Why: some batch job or manual script will bypass the code.
Read in post: Airline booking
InterviewSeniorWhen is a periodic job good enough for hold expiry, and when do you need second-level precision?

A job every minute is fine when a seat being "held" for up to an extra minute doesn't matter; when a flight is selling out or holds are short, add a lazy condition to the hold statement.

The job is simple and keeps indexes tidy. The lazy "HELD but held_until < now() counts as free" condition stops anyone being turned away wrongly. Either way, before releasing a booking that's waiting for payment, check that no payment is in flight, or a customer will pay for a seat that's already been sold to someone else.

Read in post: Airline booking
InterviewSeniorWhy is a conditional UPDATE correct at READ COMMITTED without taking a lock first?

Because the UPDATE locks the row it modifies, and the check and the write happen in one statement against the latest version, so there's no gap between reading and writing.

  • PostgreSQL: if another transaction is modifying the row, the UPDATE waits, then re-evaluates the WHERE against the new version (EvalPlanQual); if the condition no longer holds, the row is skipped and the count is 0.
  • MySQL InnoDB: an UPDATE always reads the latest committed version (a current read) and locks it.
  • At PostgreSQL's SERIALIZABLE or REPEATABLE READ, instead of re-evaluating, the transaction gets a serialization error and must retry.
Read in post: Airline booking
Trade-offSeniorA JSON translation column or a separate translation tableJSON column (the slides' suggestion): no JOIN, a new language needs no schema change. Fits when few fields are translated, they are mostly displayed, and search happens in one or two languages. You can't tell which translation is stale. Translation table (entityid, locale, field, value): full constraints, per-translati
  • JSON column (the slides' suggestion): no JOIN, a new language needs no schema change. Fits when few fields are translated, they are mostly displayed, and search happens in one or two languages. You can't tell which translation is stale.
  • Translation table (entity_id, locale, field, value): full constraints, per-translation metadata (source version, review status), one index for every language. The price is a JOIN and a longer fallback query. Fits when there is a real translation workflow.
  • One column per language: only for a small, fixed set of languages.
  • Real multilingual full-text search (tokenizing, accent folding) belongs in a search engine.
Read in post: Data modeling case studies
Edge caseSeniorSwitching positions to floating point does not fix running out of roomMoving to FLOAT/DOUBLE buys only about 40–50 more halvings (lab: 43 between 1000 and 1001) before two tasks share a position, and the order then breaks without any error. The real fixes: detect the collision and renumber the whole list in one transaction, or use string keys with a rebalancing job once keys pass a lengt

Moving to FLOAT/DOUBLE buys only about 40–50 more halvings (lab: 43 between 1000 and 1001) before two tasks share a position, and the order then breaks without any error. The real fixes: detect the collision and renumber the whole list in one transaction, or use string keys with a rebalancing job once keys pass a length threshold.

Read in post: Data modeling case studies
Edge caseMidString ordering keys must be compared with the "C" collationFractional indexing relies on byte order ('0' < '9' < 'a' < 'z'), the same as String.compareTo in Java. Linguistic collations (language-aware sort rules) have their own rules for case, so the database and the application can end up with two different orders. Declare rank text COLLATE "C" (PostgreSQL) or asciibin (MySQL

Fractional indexing relies on byte order ('0' < '9' < 'a' < 'z'), the same as String.compareTo in Java. Linguistic collations (language-aware sort rules) have their own rules for case, so the database and the application can end up with two different orders. Declare rank text COLLATE "C" (PostgreSQL) or ascii_bin (MySQL), and use only lowercase letters and digits in the keys.

Read in post: Data modeling case studies
Edge caseMidBooking several nights without checking the updated row count leaves partial bookingsA conditional UPDATE with status = 'OPEN' is safe under concurrency (a later transaction waits on the row locks and re-checks the condition), but if one night is already taken the statement still succeeds, just with fewer rows. If you don't compare the row count with the number of nights, the booking holds 2 of 3 night

A conditional UPDATE with status = 'OPEN' is safe under concurrency (a later transaction waits on the row locks and re-checks the condition), but if one night is already taken the statement still succeeds, just with fewer rows. If you don't compare the row count with the number of nights, the booking holds 2 of 3 nights. Always check that the row count equals the number of nights and roll back otherwise.

Read in post: Data modeling case studies
Trade-offSeniorPer-day availability rows or date ranges with an exclusion constraintOne row per day (the slides): repricing a day is easy, and double booking is blocked by the conditional UPDATE. Costs rows, needs a job to extend the window and clean up old days; a 30-night booking locks 30 rows. Bookings stored as a daterange plus EXCLUDE USING gist (homestayid WITH =, stay WITH &&) on PostgreSQL: th
  • One row per day (the slides): repricing a day is easy, and double booking is blocked by the conditional UPDATE. Costs rows, needs a job to extend the window and clean up old days; a 30-night booking locks 30 rows.
  • Bookings stored as a daterange plus EXCLUDE USING gist (homestay_id WITH =, stay WITH &&) on PostgreSQL: the database itself rejects overlapping bookings, nothing is pre-generated, and special prices live as sparse override ranges. The price is that "which days are free" has to be derived from ranges, and MySQL has no such feature.
  • Choose per-day rows when price and status change day by day and you need a month view; choose ranges when the main job is preventing overlaps (meeting rooms, car rentals).
Read in post: Data modeling case studies
Edge caseSeniorGenerating recurring events by adding 7 days to a UTC instant drifts across DSTA recurring schedule is defined in local time ("9 a.m. on Mondays in Berlin"), so adding interval '7 days' to a UTC timestamptz shifts the meeting to 10:00 after the summer-time switch. Store a timestamp without offset together with an IANA time zone id (not a fixed +07:00 offset), generate each occurrence in local tim

A recurring schedule is defined in local time ("9 a.m. on Mondays in Berlin"), so adding interval '7 days' to a UTC timestamptz shifts the meeting to 10 after the summer-time switch. Store a timestamp without offset together with an IANA time zone id (not a fixed +07:00 offset), generate each occurrence in local time and only then apply AT TIME ZONE tz. Test with a zone that has DST; tests run in Vietnam always pass. Background in Dates and times in the backend.

Read in post: Data modeling case studies
Trade-offSeniorAn N–M table or an array column with GIN for tagsN–M table posttag(postid, tagid): foreign keys, renaming a tag touches one row, per-tag counts come from a (tagid, postid) index, and it works on any database. The cost is a JOIN and a large link table. Array column + GIN (PostgreSQL): reading tags is reading one row, multi-tag filters use @/&&, and the index is small.
  • N–M table post_tag(post_id, tag_id): foreign keys, renaming a tag touches one row, per-tag counts come from a (tag_id, post_id) index, and it works on any database. The cost is a JOIN and a large link table.
  • Array column + GIN (PostgreSQL): reading tags is reading one row, multi-tag filters use @>/&&, and the index is small. The cost: no foreign key (typos get in), renaming a tag rewrites every post that has it, and GIN slows writes.
  • The "(1) more than (2)" priority favours the array if tags are nearly immutable, or if you store tag_id int[] instead of names. When tags have a lifecycle (renames, merges, moderation), the N–M table is the source of truth and the array is just a denormalized read copy.
Read in post: Data modeling case studies
TILMidThe planner already knows roughly how many rows there are, for freeSELECT reltuples FROM pgclass WHERE relname = 'click' returned 6,000,048 for a 6-million-row table; EXPLAIN on the 24-hour filter estimated rows=1998926 against an actual 2,000,000 (0.05% off). The catch: statistics must be fresh (before ANALYZE, the planner guessed 30,000 rows). InnoDB's TABLEROWS is far less accurate

SELECT reltuples FROM pg_class WHERE relname = 'click' returned 6,000,048 for a 6-million-row table; EXPLAIN on the 24-hour filter estimated rows=1998926 against an actual 2,000,000 (0.05% off). The catch: statistics must be fresh (before ANALYZE, the planner guessed 30,000 rows). InnoDB's TABLE_ROWS is far less accurate.

Read in post: Data modeling case studies
Edge caseMidHyperLogLog counts distinct values, not total clicksThe slides list HyperLogLog among the estimation options for total clicks, but HLL solves a different problem: counting distinct values (how many different people clicked) in a few KB of memory with about 1% error. Total clicks is an additive counter, and summing exact per-minute counts is already cheap. Distinct count

The slides list HyperLogLog among the estimation options for total clicks, but HLL solves a different problem: counting distinct values (how many different people clicked) in a few KB of memory with about 1% error. Total clicks is an additive counter, and summing exact per-minute counts is already cheap. Distinct counts are the expensive part: in the lab, count(DISTINCT user_id) over 2 million clicks took 384 ms and can't be summed across minutes; HLL sketches (Redis PFADD/PFCOUNT, the hll extension) can be merged.

Read in post: Data modeling case studies
InterviewJuniorHow do you store multilingual content?

Either a JSON column of translations in the same table or a translation table (entity_id, locale, value); either way, always have a fallback language.

JSON column: no JOIN, no schema change for a new language. Translation table: full constraints, one index for every language.

Read in post: Data modeling case studies
InterviewJuniorWhy number positions with gaps (1000, 2000) instead of 1, 2, 3?

So inserting in the middle updates a single row (the midpoint) instead of shifting every row after it.

When the gap runs out, renumber or switch to string keys.

Read in post: Data modeling case studies
InterviewJuniorWhy not compute total clicks with count(*) every time the dashboard opens?

Because the cost grows with traffic (about 200 ms for 2 million clicks in the lab) and the dashboard is opened constantly.

With per-minute pre-aggregation each read sums only 1,440 rows, at the price of up to a minute of delay.

Read in post: Data modeling case studies
InterviewMidHow do you book 3 homestay nights without double booking?

One conditional UPDATE with status = 'OPEN' over the three dates inside a transaction, then check that exactly 3 rows were updated, and roll back otherwise.

A competing transaction waits on the row locks, re-evaluates the condition and updates nothing.

Read in post: Data modeling case studies
InterviewMidHow do you store the times of a recurring event?

Store the local time, an IANA time zone id and the RRULE; generate occurrences for a time window as rows with start_at timestamptz for querying.

Don't store a fixed offset, because DST changes the offset between occurrences.

Read in post: Data modeling case studies
InterviewMidWhat are the downsides of a tag array with GIN compared with an N–M table?

No foreign key, renaming a tag rewrites every row that has it (297 ms versus 2 ms in the lab), GIN slows writes, and it ties you to PostgreSQL.

It fits when tags are nearly immutable and reads dominate.

Read in post: Data modeling case studies
InterviewSeniorThe slides switch the position column to float when integers run out. How would you review that?

A float adds only about 40–50 halvings at the same spot (52 mantissa bits), after which the order breaks silently.

I'd propose detecting the collision and renumbering in a transaction, or string keys in the "C" collation with a unique constraint and a rebalancing job.

Read in post: Data modeling case studies
InterviewSeniorHomestay availability: one row per day or date ranges?

One row per day when price and status vary by day and you need a month view; ranges with an exclusion constraint when the main job is preventing overlaps.

Per-day rows cost rows and need a job to extend the window. Ranges (PostgreSQL) pre-generate nothing, but working out free days is harder.

Read in post: Data modeling case studies
InterviewSeniorHow would you count distinct users who clicked in the last 30 days with billions of clicks?

HyperLogLog: one sketch of a few KB per day, and merging 30 sketches gives an estimate within about 1%.

Exact distinct counts can't be added across days and need memory proportional to the number of users. If exactness is required, run a batch job.

Read in post: Data modeling case studies
InterviewSeniorWhen do you choose a JSON column instead of adding a table or columns?

When the data is read together, lightly constrained and changes shape often.

Any field that starts showing up in WHERE, JOINs, constraints or separate updates gets promoted to a column or a table; a generated column or expression index is the stopgap.

Read in post: Data modeling case studies
Edge caseJuniorEpoch seconds and epoch milliseconds get mixed upReading milliseconds as seconds gives the year 55705; reading seconds as milliseconds gives 20 January 1970. The most common version: setting a JWT exp (exp, iat, nbf are in seconds) to System.currentTimeMillis() + 3600000, so the token "expires" tens of thousands of years from now. Put the unit in the field name: expi

Reading milliseconds as seconds gives the year 55705; reading seconds as milliseconds gives 20 January 1970. The most common version: setting a JWT exp (exp, iat, nbf are in seconds) to System.currentTimeMillis() + 3600_000, so the token "expires" tens of thousands of years from now.

  • Put the unit in the field name: expiresAtEpochSeconds, createdAtMs.
  • Use Instant in code rather than long; prefer ISO 8601 strings in APIs.
  • If you must accept both, check the magnitude: below 10^11 is seconds (10^11 seconds is the year 5138, while 10^11 ms is only 1973).
Read in post: Dates and times in the backend
TILLeap seconds will be dropped by 2035In 2022 the General Conference on Weights and Measures (CGPM) decided to stop adding leap seconds to UTC by 2035 at the latest, because they keep breaking systems (in 2012 a leap second hung many Linux servers, Reddit's among them). For ordinary backends: treat every day as 86,400 seconds, and never add or subtract lea

In 2022 the General Conference on Weights and Measures (CGPM) decided to stop adding leap seconds to UTC by 2035 at the latest, because they keep breaking systems (in 2012 a leap second hung many Linux servers, Reddit's among them). For ordinary backends: treat every day as 86,400 seconds, and never add or subtract leap seconds yourself.

Read in post: Dates and times in the backend
Edge caseMidEtc/GMT+7 is UTC−7, not UTC+7The Etc/GMT±N zones follow the POSIX convention, so the sign is inverted: ZoneId.of("Etc/GMT+7") has offset -07:00 (JDK 21). PostgreSQL is even trickier: a time zone name given as a string is read POSIX-style. So SET TIME ZONE '+07:00', AT TIME ZONE '+07:00' and even AT TIME ZONE 'UTC+7' all mean UTC−7 (PostgreSQL 17:

The Etc/GMT±N zones follow the POSIX convention, so the sign is inverted: ZoneId.of("Etc/GMT+7") has offset -07:00 (JDK 21).

PostgreSQL is even trickier: a time zone name given as a string is read POSIX-style. So SET TIME ZONE '+07:00', AT TIME ZONE '+07:00' and even AT TIME ZONE 'UTC+7' all mean UTC−7 (PostgreSQL 17: timezone('+07:00', '2024-01-01 00:00Z') returns 2023-12-31 17:00). An offset inside a literal such as '2024-06-10 00:30+07' follows ISO, so it really is UTC+7.

For Vietnam time use Asia/Ho_Chi_Minh. For a fixed offset use ZoneOffset.ofHours(7) (Java) or INTERVAL '+07:00' HOUR TO MINUTE (PostgreSQL), and always check with a known value.

Read in post: Dates and times in the backend
TILAsia/Ho_Chi_Minh used to be UTC+8According to tzdata, southern Vietnam used UTC+8 until mid-1975: ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("Asia/HoChiMinh")).getOffset() is +08:00 (JDK 21). A 1970 birth date stored as "midnight Saigon time" and converted to UTC is off by eight hours, not seven, and can land on the previous day if someone sub

According to tzdata, southern Vietnam used UTC+8 until mid-1975: ZonedDateTime.of(1970, 1, 1, 0, 0, 0, 0, ZoneId.of("Asia/Ho_Chi_Minh")).getOffset() is +08:00 (JDK 21). A 1970 birth date stored as "midnight Saigon time" and converted to UTC is off by eight hours, not seven, and can land on the previous day if someone subtracts a hard-coded seven hours. A birth date is a LocalDate; don't store it as a moment.

Read in post: Dates and times in the backend
Trade-offMidAdd "one day" or add "24 hours"plusDays(1) / Period: keeps the local clock time (09:00 the next day is still 09:00). Right for appointments, daily reminders, opening hours, "expires at the end of tomorrow". plus(Duration.ofHours(24)) / Duration: exactly 86,400 seconds pass. Right for TTLs, timeouts, tokens that expire after 24 hours, time-window rat
  • plusDays(1) / Period: keeps the local clock time (09 the next day is still 09). Right for appointments, daily reminders, opening hours, "expires at the end of tomorrow".
  • plus(Duration.ofHours(24)) / Duration: exactly 86,400 seconds pass. Right for TTLs, timeouts, tokens that expire after 24 hours, time-window rate limits.

Rule of thumb: anything people think about in calendar terms uses Period on LocalDate/ZonedDateTime; anything a machine measures as a duration uses Duration on Instant. Instant has no calendar day, so Instant.plus(1, DAYS) is always 24 hours. Vietnam has no DST, so this bug only shows up once you have users or assets in other countries.

Read in post: Dates and times in the backend
Edge caseMidTimeZone.getTimeZone silently returns GMT for an unknown idTimeZone.getTimeZone("Asia/Hanoi") (not a tzdata id; the right one is Asia/HoChiMinh) silently returns GMT, so every time is off by seven hours with no exception. ZoneId.of("Asia/Hanoi") throws ZoneRulesException: Unknown time-zone ID straight away (JDK 21). ZoneId.of("CST") also throws because the abbreviation is ambi

TimeZone.getTimeZone("Asia/Hanoi") (not a tzdata id; the right one is Asia/Ho_Chi_Minh) silently returns GMT, so every time is off by seven hours with no exception. ZoneId.of("Asia/Hanoi") throws ZoneRulesException: Unknown time-zone ID straight away (JDK 21).

ZoneId.of("CST") also throws because the abbreviation is ambiguous; it only works if you pass ZoneId.SHORT_IDS, and then CST becomes America/Chicago, which may not be what you meant. Always use a full IANA id, validate zone ids from clients against ZoneId.getAvailableZoneIds(), and never parse abbreviations.

Read in post: Dates and times in the backend
Trade-offMidRun the JVM in UTC or in local timeJVM in UTC (-Duser.timezone=UTC or TZ=UTC in the container; eclipse-temurin images already default to UTC): logs, Instants and default conversions are consistent across environments, and "works on my machine" bugs show up early if developers run in UTC too. The cost: logs are seven hours off from Vietnam time, and code
  • JVM in UTC (-Duser.timezone=UTC or TZ=UTC in the container; eclipse-temurin images already default to UTC): logs, Instants and default conversions are consistent across environments, and "works on my machine" bugs show up early if developers run in UTC too. The cost: logs are seven hours off from Vietnam time, and code that uses argument-less now() for the user's "today" is wrong between midnight and 7 a.m. Vietnam time.
  • JVM in local time (Asia/Ho_Chi_Minh): readable logs, and "today" matches Vietnamese users. But it's only right while every user is in one zone; it breaks when you expand abroad, and services configured differently drift apart in ways that are hard to track down.

Recommendation: JVM, database session and container all in UTC; calendar calculations pass the user's or asset's ZoneId; logs use ISO 8601 with Z. Don't call TimeZone.setDefault: it's global state, and changing it at runtime affects other threads.

Read in post: Dates and times in the backend
Edge caseMidLocalDate.now() gives "today" in the server's time zoneWith the server in UTC, its "today" is wrong for Vietnamese users for seven hours every day (midnight to 7 a.m. Vietnam time). The result: it accepts bookings for nights that have passed, rejects valid bookings in zones further west, and closes the daily report on the wrong date. The fix: decide whose "today" it is (th

With the server in UTC, its "today" is wrong for Vietnamese users for seven hours every day (midnight to 7 a.m. Vietnam time). The result: it accepts bookings for nights that have passed, rejects valid bookings in zones further west, and closes the daily report on the wrong date.

The fix: decide whose "today" it is (the user's, the shop's, the homestay's), store that entity's ZoneId, and call LocalDate.now(clock.withZone(zone)) with an injected Clock. Test with Clock.fixed at 00 and 23 local time.

Read in post: Dates and times in the backend
Edge caseJuniorA fixed offset for a city is wrong half the yearZoneOffset.ofHours(1) for Paris or -08:00 for California is only right in winter; during summer time (roughly March to October/November) it's an hour off. Convert with IANA zone ids (Europe/Paris, America/LosAngeles) through ZonedDateTime and let java.time apply the DST rules and any historical rule changes. Use a fixe

ZoneOffset.ofHours(1) for Paris or -08:00 for California is only right in winter; during summer time (roughly March to October/November) it's an hour off. Convert with IANA zone ids (Europe/Paris, America/Los_Angeles) through ZonedDateTime and let java.time apply the DST rules and any historical rule changes. Use a fixed offset only when the data really is an offset (an ISO string from a client, say), not when you know the city's name.

Read in post: Dates and times in the backend
InterviewJuniorWhat is a Unix timestamp? Does it depend on the time zone?

It's the number of seconds (or milliseconds) since 1970-01-01T00:00, and it doesn't depend on the time zone.

The same number is the same moment everywhere; the time zone only matters when you display it as a local date and time. Always be explicit about the unit, because JavaScript uses milliseconds while JWT and Unix use seconds.

Read in post: Dates and times in the backend
InterviewJuniorAre 2023-09-25T16:20:52+07:00 and 2023-09-25T09:20:52Z equal?

They're the same moment, because Z means an offset of +00:00.

In Java, OffsetDateTime#isEqual returns true but equals returns false because the offsets differ. To compare moments, use isEqual, compareTo on Instant, or convert both to Instant first.

Read in post: Dates and times in the backend
InterviewJuniorWhen do you use LocalDate and when Instant?

Instant is for a point on the global timeline; LocalDate is for a calendar date that isn't tied to a specific moment.

Instant: creation time, payment time, events. LocalDate: birth date, check-in date, public holiday. A quick test: should the value change if the time zone changes? Your birthday doesn't change when you fly to the US, but it isn't a moment either.

Read in post: Dates and times in the backend
InterviewMidHow does an offset differ from a zone id? Why store the zone id?

An offset is the difference from UTC at one moment; a zone id is the rule set for every moment. Store the zone id when you need future calendar calculations.

You can't derive the rules from an offset (+02:00), so you can't compute times at other moments (a weekly event across a DST change, for example). A zone id (Europe/Paris) says which offset applies when, including DST and historical changes. An offset is only enough to pin down a moment you already know.

Read in post: Dates and times in the backend
InterviewMidHow does plusDays(1) differ from plus(Duration.ofHours(24))?

On a ZonedDateTime, plusDays(1) keeps the local clock time, while adding 24 hours means exactly 86,400 seconds pass.

On a DST change day they differ by an hour: in Paris at 09 on 30 March 2024, plusDays(1) gives 09 the next day and adding 24 hours gives 10. Use Period/plusDays for calendar things (appointments) and Duration for durations (TTLs, timeouts).

Read in post: Dates and times in the backend
InterviewMidWhy can the JVM's time zone differ from the server's?

Because the JVM picks its own default zone at startup and uses the tzdata bundled inside the JDK.

It reads -Duser.timezone, the TZ variable, then /etc/localtime; a container can have a different TZ from its host. So date in the shell and ZoneId.systemDefault() can disagree, and the JVM's rules can be older than the OS's. The safe approach: pin the JVM and container to UTC, pass a ZoneId explicitly for all calendar calculations, and keep the JDK updated for fresh tzdata.

Read in post: Dates and times in the backend
InterviewMidHow do you test code that depends on the current time?

Inject a java.time.Clock and use Clock.fixed in tests.

In production use a Clock.systemUTC() bean and call Instant.now(clock) or LocalDate.now(clock.withZone(zone)). In tests pick the edge cases: just after local midnight, DST change days, 31 December, 29 February. Avoid argument-less now() and Thread.sleep in tests.

Read in post: Dates and times in the backend
InterviewSeniorA booking system computes "today" wrongly for guests abroad. How do you analyse and fix it?

"Today" belongs to the asset's (the homestay's) time zone, not the server's or the guest's; the bug usually comes from LocalDate.now() using the JVM zone.

  • Add a zone id column to the homestay, inject a Clock, compute LocalDate.now(clock.withZone(homestay.zone())).
  • Compute nights with ChronoUnit.DAYS.between on LocalDate, never from a Duration.
  • Test at 00 and 23 local time and on DST change days.
  • Hunt for the same pattern elsewhere (daily reports, period closing, date-based promotions) and add a static analysis rule that bans argument-less now().
Read in post: Dates and times in the backend
InterviewSeniorWhat happens to your system when time zone rules change?

Past data stored as instants stays correct; future data stored as instants computed with the old rules displays at the wrong local time.

For example, a 9 appointment becomes 8 after the change. That's why future appointments should be stored as local time plus zone id and converted to an instant only when needed. Also, tzdata must be updated everywhere: the JDK (a patch release or TZUpdater), the database, the OS, frontend libraries; three components on three versions of the rules is a hard-to-find source of drift.

Read in post: Dates and times in the backend
InterviewSeniorWhat time conventions would you set for a multi-service system?

Store and transmit moments in UTC, use RFC 3339 with an offset in APIs, run everything in UTC, and pass an explicit ZoneId to calendar calculations.

  • Store Instant / timestamptz; never use zone abbreviations.
  • Every service, database session and container runs in UTC.
  • Pure dates (birth dates, check-in dates) are LocalDate / date; future appointments are local time plus zone id.
  • Inject a Clock for testing.
  • Write it down in an ADR and enforce it through code review and static rules.
Read in post: Dates and times in the backend
Trade-offMidPackages by layer, by feature, or a hybridBy layer: small apps, new teams, CRUD. The price: no encapsulation, and changes spread across many places. By feature, layers inside: lots of business logic, many people working in parallel; hide details with package-private, easy to split into services. The price: you have to choose feature boundaries (DDD helps), and
  • By layer: small apps, new teams, CRUD. The price: no encapsulation, and changes spread across many places.
  • By feature, layers inside: lots of business logic, many people working in parallel; hide details with package-private, easy to split into services. The price: you have to choose feature boundaries (DDD helps), and truly shared code needs its own home.
  • Layers outside, features inside (domain.booking, infrastructure.repository): a common compromise that keeps the dependency direction between layers, but every feature's adapters sit together, so feature boundaries are only clear in the domain.
  • My default for a backend with real business logic: features (bounded contexts) at the top level, layers inside.
Read in post: DDD and package structure
Edge caseSeniorOne model shared by every context turns into a "God class"The symptoms: a Booking with 50+ fields, half of them null depending on who uses it, every team editing the same file, every migration touching this table. Each context needs its own model: Sales has a Booking with passengers and prices, Flight Ops has a SeatHold, Accounting has a Receivable, linked by ID (bookingId) a

The symptoms: a Booking with 50+ fields, half of them null depending on who uses it, every team editing the same file, every migration touching this table.

Each context needs its own model: Sales has a Booking with passengers and prices, Flight Ops has a SeatHold, Accounting has a Receivable, linked by ID (bookingId) and events. Duplicating a little data is an acceptable price for independence.

Read in post: DDD and package structure
Trade-offMidValue objects or primitive types (primitive obsession)String seat, BigDecimal price, long bookingId: fewer classes, maps straight to JPA/JSON. The price: passing parameters in the wrong order (book(flightId, bookingId)) still compiles, format checks are scattered everywhere, and nothing stops you adding amounts in different currencies. SeatNo, Money, BookingId: validated
  • String seat, BigDecimal price, long bookingId: fewer classes, maps straight to JPA/JSON. The price: passing parameters in the wrong order (book(flightId, bookingId)) still compiles, format checks are scattered everywhere, and nothing stops you adding amounts in different currencies.
  • SeatNo, Money, BookingId: validated once in the constructor and trusted everywhere after that; the compiler catches type mix-ups; behaviour (plus, convert) has a home. The price: more classes, plus converters for JPA (@Embeddable or AttributeConverter) and Jackson.
  • Apply it to concepts with rules (money, seat numbers, email, date ranges) and to aggregate IDs; you don't need to wrap every string.
Read in post: DDD and package structure
Edge caseSeniorAn aggregate that is too big causes lock contention and slow loadingMaking Flight the root that holds all 180 seats and every booking sounds "right" (it protects the no-double-selling rule). But every seat hold then has to lock and save the whole flight: two customers booking two different seats fight over one lock (or one version), and loading the aggregate drags in thousands of rows.

Making Flight the root that holds all 180 seats and every booking sounds "right" (it protects the no-double-selling rule). But every seat hold then has to lock and save the whole flight: two customers booking two different seats fight over one lock (or one version), and loading the aggregate drags in thousands of rows.

Vaughn Vernon's rules: keep aggregates small, reference other aggregates by ID, one aggregate per transaction, and keep aggregates consistent with each other through events (eventual consistency). Put the "no double-selling" rule at the smallest level that can protect it: a seat row with a unique constraint or a conditional statement.

Read in post: DDD and package structure
Edge caseMidThe "dependency flow" pyramid from UI down to infrastructure is easy to misreadThe slides draw four stacked layers with dependency arrows going from UI down to Infrastructure, like classic layered architecture. Following those arrows literally, the domain depends on infrastructure, the opposite of part 1. The correct reading: the domain depends on nothing; application depends on the domain; infra

The slides draw four stacked layers with dependency arrows going from UI down to Infrastructure, like classic layered architecture. Following those arrows literally, the domain depends on infrastructure, the opposite of part 1.

The correct reading: the domain depends on nothing; application depends on the domain; infrastructure depends on the domain (to implement the repository interfaces) and on application; UI depends on application. Infrastructure is "below" in the runtime call flow, but "outside" in source-code dependencies. Evans wrote his book in 2003, before hexagonal and onion became popular; later books (Vernon 2013) put the domain at the centre.

Read in post: DDD and package structure
Edge caseSeniorHolding seats in another context and then failing to save the booking leaves orphaned seat holdsinventory.holdAll(...) succeeds, then bookings.save(...) throws (the DB is down, a constraint is violated): the seats are now held for a booking that doesn't exist. In a monolith with one database, @Transactional on the application service wrapping both is enough. Once Flight is a separate service, there is no shared t

inventory.holdAll(...) succeeds, then bookings.save(...) throws (the DB is down, a constraint is violated): the seats are now held for a booking that doesn't exist. In a monolith with one database, @Transactional on the application service wrapping both is enough.

Once Flight is a separate service, there is no shared transaction. The options: time-limited holds (they expire after 10 minutes and clean themselves up), calling release on the failure path, or reversing the order (save the booking as PENDING first, hold the seats, then update) together with an outbox. This is a miniature saga: the ordering and compensation must be part of the design.

Read in post: DDD and package structure
InterviewMidHow does an entity differ from a value object? Give examples.

An entity has an identity and a lifecycle and is compared by ID; a value object is just a value, immutable, compared by all its attributes.

Two bookings are different even with the same data, and a booking is still the same booking when its status changes. Two Money(100000, VND) instances are interchangeable. Entity examples: User, Flight, Booking; value object examples: Money, Address, SeatNo, DateRange. In Java 21, value objects fit naturally as records.

Read in post: DDD and package structure
InterviewMidWhat is a bounded context? Why do you need one?

An area of the system with its own model and language, inside which each word has exactly one meaning.

The same word ("Booking", "credit") means different things in different departments; one shared model for all of them grows bloated and contradictory. Each context has its own model, communicates through APIs or events and runs independently. Context boundaries become top-level packages in a monolith and candidates for separate services.

Read in post: DDD and package structure
InterviewMidWhat does package-by-feature give you over package-by-layer?

A feature change stays inside one package, and internal classes can be package-private so the compiler blocks cross-access.

The folder structure tells you about the business, and it's easy to hand a package to one team and split it into a service later. Package-by-layer forces everything to be public and spreads a single change across many packages.

Read in post: DDD and package structure
InterviewMidHow does an application service differ from a domain service?

A domain service holds business rules; an application service orchestrates a use case and holds no rules.

A domain service covers rules that don't belong to a specific entity (pricing policies, flight eligibility checks); it is stateless and ideally pure. An application service loads aggregates, calls the domain, saves, publishes events and manages transactions and security.

Read in post: DDD and package structure
InterviewSeniorWhat is an aggregate, and how do you design aggregate boundaries?

A cluster of entities and value objects treated as one consistency unit, accessed through the aggregate root, with one transaction modifying one aggregate.

Design it as small as possible while still protecting the invariants that must be consistent immediately; reference other aggregates by ID; keep aggregates consistent with each other through events. A big aggregate (a Flight containing every seat and booking) causes lock contention and slow loading.

Read in post: DDD and package structure
InterviewSeniorWhere does the repository interface live, and why?

In the domain layer (or next to the use case), with the implementation in infrastructure: that's dependency inversion.

The domain defines what it needs in its own language, and infrastructure depends on the domain to implement it. So the domain can be tested with an in-memory version, and switching storage technology doesn't touch the domain. One repository per aggregate root, none for inner entities.

Read in post: DDD and package structure
InterviewSeniorHow do two bounded contexts talk to each other without becoming tightly coupled?

Through the called context's public API, never by reading each other's tables or internal classes, with an anti-corruption layer on the calling side.

The API can be an interface in a monolith, REST/gRPC, or events. The anti-corruption layer translates the other model into the caller's language. Prefer events for things that can be eventually consistent, and synchronous calls for things that need an immediate answer (holding seats), with error handling and compensation, because there is no shared transaction.

Read in post: DDD and package structure
InterviewSeniorWould you apply DDD to every project?

No. DDD is worth it when the business logic is complex and a competitive advantage, when there are domain experts to model with, and when the project will live a long time.

Good fits: pricing, booking, payments. For CRUD, internal tools or "generic" subdomains (sending email, authentication), use off-the-shelf solutions and a lean architecture. The strategic part (bounded contexts, a shared language) is useful far more widely than the tactical part.

Read in post: DDD and package structure
Edge caseMidApplying a pattern before there's a smell is over-engineeringAn interface with one implementation, a factory that only returns one type, a strategy with two branches that never change: each adds a file and a layer of indirection and buys nothing. Wait for the second or third change of the same kind (the rule of three) before extracting. In review, ask "where will the third varia

An interface with one implementation, a factory that only returns one type, a strategy with two branches that never change: each adds a file and a layer of indirection and buys nothing. Wait for the second or third change of the same kind (the rule of three) before extracting. In review, ask "where will the third variant come from, and when?", not "is this the correct pattern?".

Read in post: Design patterns through refactoring
Trade-offMidPicking the strategy at startup, per request, or on state changeAt startup, from configuration (@ConditionalOnProperty, profiles): simplest, no runtime cost, but changing the behaviour needs a deploy or restart. From request data: a registry looked up by key (listing type, carrier, promo code), see section 2.5 and part 4. Flexible, but you must handle unknown keys and check the con
  • At startup, from configuration (@ConditionalOnProperty, profiles): simplest, no runtime cost, but changing the behaviour needs a deploy or restart.
  • From request data: a registry looked up by key (listing type, carrier, promo code), see section 2.5 and part 4. Flexible, but you must handle unknown keys and check the configuration is complete at startup.
  • When system state changes (network, a feature flag): the object owning the state notifies whoever cares, i.e. Observer; the sample repo goes that way in part 3. Reacts immediately, but you need thread safety when the strategy is swapped mid-flight.

What to avoid: repeating the decision at every call site; the old smell has just moved.

Read in post: Design patterns through refactoring
Trade-offMidStrategy, if/else, or an enum with behaviourif/else / switch: two or three short branches that rarely change and live in one place. You read one spot and understand all of it. An enum with an abstract method (each constant implements its own behaviour): a closed set in the same module, like order states. The compiler forces you to implement every constant. Strat
  • if/else / switch: two or three short branches that rarely change and live in one place. You read one spot and understand all of it.
  • An enum with an abstract method (each constant implements its own behaviour): a closed set in the same module, like order states. The compiler forces you to implement every constant.
  • Strategy (interface + classes): an open set (other modules, plugins, configuration), variants with their own dependencies (calls an API, reads the DB), a choice that changes at runtime, or something you need to mock in tests.

Strategy's price is indirection: don't pay it for two branches that will never change.

Read in post: Design patterns through refactoring
Edge caseMidA stateful strategy can't be a shared singletonLocalSync holds a pending list. If it's a Spring bean (singleton by default) used for every user, users' data gets mixed and an ArrayList gets written by several threads at once. Shared strategies should be stateless (data only comes in through parameters). If state is unavoidable, create an instance per use (a factory

LocalSync holds a pending list. If it's a Spring bean (singleton by default) used for every user, users' data gets mixed and an ArrayList gets written by several threads at once.

Shared strategies should be stateless (data only comes in through parameters). If state is unavoidable, create an instance per use (a factory, prototype scope) and make it thread-safe. The field holding the strategy in the context also needs volatile (or synchronisation) if another thread can swap it.

Read in post: Design patterns through refactoring
Edge caseMidA negative discount and no rounding are two hidden conventions that breed bugsThe original code returns the discount as a negative number (subtotal × -0.05) and computes total = subtotal + discount. Anyone skimming it will write subtotal - discount and charge more than the base price. BigDecimal multiplication doesn't round either: 100.00 × -0.05 gives -5.0000 (scale 4), and odd prices give more

The original code returns the discount as a negative number (subtotal × -0.05) and computes total = subtotal + discount. Anyone skimming it will write subtotal - discount and charge more than the base price. BigDecimal multiplication doesn't round either: 100.00 × -0.05 gives -5.0000 (scale 4), and odd prices give more digits than the currency allows.

Fix: make the discount always non-negative and say so in the Javadoc; round once, in one place, to the currency's digits (Currency.getDefaultFractionDigits()), with a RoundingMode the business has signed off on.

Read in post: Design patterns through refactoring
TILMidCollectors.toMap and toUnmodifiableMap throw on duplicate keysWhen two elements share a key, toMap(keyFn, valueFn) / toUnmodifiableMap throw IllegalStateException: Duplicate key ... instead of silently overwriting like HashMap.put. For a strategy registry that's exactly what you want: two beans with the same code is a configuration error, so it should surface at startup. Only pas

When two elements share a key, toMap(keyFn, valueFn) / toUnmodifiableMap throw IllegalStateException: Duplicate key ... instead of silently overwriting like HashMap.put. For a strategy registry that's exactly what you want: two beans with the same code is a configuration error, so it should surface at startup. Only pass a merge function (a, b) -> ... when duplicate keys are genuinely expected.

Read in post: Design patterns through refactoring
InterviewJuniorWhat is the Strategy pattern? Give a backend example.

Strategy pulls a behaviour with several implementations out into an interface, one implementation per variant; the object using it only holds a reference to the interface.

Examples: discount rules (long stay, early bird, voucher), shipping fees by carrier, where to store files (S3 or local disk). A new variant is a new class, with no edits to the code that uses it.

Read in post: Design patterns through refactoring
InterviewJuniorWhat does the Open/Closed Principle mean?

Code should be "open for extension, closed for modification": add behaviour by adding code (a new class, a new bean), not by editing code that already works.

Strategy and Template Method are two common ways to get there. It isn't absolute: apply it where things actually change often.

Read in post: Design patterns through refactoring
InterviewMidIn Spring, how do you pick a strategy based on request data?

Each strategy is a bean that declares its own key; the service receives List<Strategy> through its constructor, builds a Map/EnumMap from key to bean, and at runtime it's just map.get(key).

Check for duplicates and gaps right in the constructor, so configuration mistakes surface at startup. That avoids a switch you'd edit for every new type.

Read in post: Design patterns through refactoring
InterviewMidWhat goes wrong with a stateful strategy as a Spring bean?

Beans are singletons by default, shared by every request and thread, so state inside a strategy mixes data between requests and hits race conditions.

Strategies should be stateless. If you need per-use state, create a new instance (a factory or prototype scope) or pass the state as parameters.

Read in post: Design patterns through refactoring
InterviewMidWhen do you use an enum with behaviour instead of Strategy?

When the set of variants is closed, lives in the same module and has no dependencies of its own, like order states or fixed fee types.

Each enum constant implements the method and the compiler makes sure all of them do. Once a variant needs injected beans (a repository, a client), has to be added from another module, or changes at runtime, switch to an interface and Strategy beans.

Read in post: Design patterns through refactoring
InterviewSeniorHow would you refactor a 300-line method full of type checks into a pattern without breaking production?

Pin the current behaviour down with characterization tests first, then move the branches out in many small PRs with green tests, and never mix the refactor with a business change.

  • Characterization tests record behaviour over many inputs, including "wrong" behaviour the system relies on.
  • Split the method into small steps without changing behaviour, then move each type branch into its own implementation.
  • You can run old and new code side by side and compare results (shadowing) before deleting the old code.
Read in post: Design patterns through refactoring
InterviewSeniorStrategy moves the "which way?" decision somewhere. Where do you put it?

Strategy removes the if/else from the context, but the decision still has to live in exactly one place.

  • The whole application uses one way: startup configuration (@ConditionalOnProperty, profiles).
  • Each request differs: a registry looked up by request data.
  • The choice follows system state (network, a feature flag): an Observer.

What I avoid is repeating the decision at every call site, because then the old smell has just moved.

Read in post: Design patterns through refactoring
Edge caseMidSpan names need low cardinality: use the route template, not the real URLSpan names like GET /bookings/123 and GET /bookings/124 produce millions of distinct names (high cardinality): the backend can't group them to compute p99 per endpoint, index memory balloons, and storage costs climb. Use the template: GET /bookings/{id} (the Spring MVC instrumentation takes http.route from the mapping)

Span names like GET /bookings/123 and GET /bookings/124 produce millions of distinct names (high cardinality): the backend can't group them to compute p99 per endpoint, index memory balloons, and storage costs climb. Use the template: GET /bookings/{id} (the Spring MVC instrumentation takes http.route from the mapping). Put the order id in an attribute. Same for metric labels: no user ids, order ids or full URLs.

Read in post: Distributed tracing with OpenTelemetry
Edge caseMidA traceparent with only the trace id and span id is malformed and gets ignoredA valid header has four parts, for example 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01, all lowercase. If hand-written code sends traceparent: <trace-<span (as in the simplified diagram) or uppercase hex, a standards-compliant receiver treats it as invalid and starts a new trace: the trace silently splits i

A valid header has four parts, for example 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01, all lowercase. If hand-written code sends traceparent: <trace>-<span> (as in the simplified diagram) or uppercase hex, a standards-compliant receiver treats it as invalid and starts a new trace: the trace silently splits in two. Use OTel's propagator instead of concatenating strings.

Read in post: Distributed tracing with OpenTelemetry
Edge caseSeniorbaggage is sent to every downstream service, third parties includedBaggage is an ordinary HTTP header, and the propagator adds it to every outgoing request, including calls to partner APIs and payment gateways. Putting an email, a phone number or a token in baggage leaks personal data, and it makes every request heavier. Keep only short, non-sensitive values (tenant id, A/B experiment

Baggage is an ordinary HTTP header, and the propagator adds it to every outgoing request, including calls to partner APIs and payment gateways. Putting an email, a phone number or a token in baggage leaks personal data, and it makes every request heavier. Keep only short, non-sensitive values (tenant id, A/B experiment name), and consider stripping baggage and traceparent on calls that leave your system.

Read in post: Distributed tracing with OpenTelemetry
Trade-offSeniorThe Java agent, the OTel Spring Boot starter, or Micrometer TracingThe Java agent (zero-code): no code changes, the widest library coverage, upgraded independently of the app. Downsides: a few seconds of extra startup (which matters for serverless), bytecode instrumentation is hard to debug, no GraalVM native image. The OpenTelemetry Spring Boot starter: a build dependency configured
  • The Java agent (zero-code): no code changes, the widest library coverage, upgraded independently of the app. Downsides: a few seconds of extra startup (which matters for serverless), bytecode instrumentation is hard to debug, no GraalVM native image.
  • The OpenTelemetry Spring Boot starter: a build dependency configured through application.yml, works with native images. Downsides: covers fewer libraries, and its version is tied to the app.
  • Micrometer Tracing (Spring Boot 3's default via Actuator, bridging to OTel or Brave): aligned with Micrometer metrics and Spring's Observation API, exemplars included. Downside: coverage depends on whether each library supports Observation.
  • Pick one. Running the agent together with the starter (or with the Micrometer bridge) easily produces duplicate spans and two trace ids for one request.
Read in post: Distributed tracing with OpenTelemetry
Edge caseMidThe otelcol-contrib image reads its config from /etc/otelcol-contrib/config.yamlDuring my test I mounted the file at /etc/otelcol/config.yaml. The Collector ran and accepted data, but tail sampling "did nothing": every trace was exported. It was actually running the image's bundled default config (Jaeger and Zipkin receivers, no sampling), because the contrib image reads /etc/otelcol-contrib/confi

During my test I mounted the file at /etc/otelcol/config.yaml. The Collector ran and accepted data, but tail sampling "did nothing": every trace was exported. It was actually running the image's bundled default config (Jaeger and Zipkin receivers, no sampling), because the contrib image reads /etc/otelcol-contrib/config.yaml. Always check the startup log to confirm the pipeline has the processors you declared, or pass --config explicitly.

Read in post: Distributed tracing with OpenTelemetry
Trade-offSeniorHead sampling vs tail samplingHead (parentbasedtraceidratio in the SDK): almost free, and traces are always complete. But it's blind to outcomes: at 10%, 90% of failing traces are lost, and rare errors may never be recorded. Tail (the tailsampling processor in the Collector): keeps errors, slow requests and important endpoints. The cost: every span
  • Head (parentbased_traceidratio in the SDK): almost free, and traces are always complete. But it's blind to outcomes: at 10%, 90% of failing traces are lost, and rare errors may never be recorded.
  • Tail (the tail_sampling processor in the Collector): keeps errors, slow requests and important endpoints. The cost: every span still goes to the Collector (network and CPU in the service), the Collector needs memory for num_traces × spans per trace during decision_wait, and you need two Collector tiers with a loadbalancing exporter routing by trace id.
  • They're often combined: generous head sampling (say 50%) to protect the pipeline, then tail sampling to pick what matters. Below a few hundred requests per second, keeping 100% with short retention is cheaper than operating tail sampling.
Read in post: Distributed tracing with OpenTelemetry
Edge caseSeniorPer-service sampling ratios leave holes in tracesService A uses traceidratio at 10%, service B at 50%, without parentbased: each decides independently. A trace A keeps may be dropped by B and vice versa, so the UI shows a parent without its children, or orphan spans. Use parentbased everywhere so the root's decision (in the sampled flag of traceparent) is respected a

Service A uses traceidratio at 10%, service B at 50%, without parentbased: each decides independently. A trace A keeps may be dropped by B and vice versa, so the UI shows a parent without its children, or orphan spans. Use parentbased_* everywhere so the root's decision (in the sampled flag of traceparent) is respected all the way down, and set the ratio only at the entry point (the gateway or the first service).

Read in post: Distributed tracing with OpenTelemetry
TILSeniorSpans are exported in batches, and dropped when the queue is fullThe SDK doesn't send each span as it ends; it hands it to the BatchSpanProcessor: a queue of 2,048 spans by default, exported in batches of 512 or every 5 seconds. When the Collector is slow or down, the queue fills and new spans are silently dropped so the application isn't slowed down. Watch the SDK's dropped-span me

The SDK doesn't send each span as it ends; it hands it to the BatchSpanProcessor: a queue of 2,048 spans by default, exported in batches of 512 or every 5 seconds. When the Collector is slow or down, the queue fills and new spans are silently dropped so the application isn't slowed down. Watch the SDK's dropped-span metric. Let the SDK flush on shutdown (the agent does it with a shutdown hook; with a hand-configured SDK, call close()), or the last spans, often those of the request that was failing during shutdown, are lost.

Read in post: Distributed tracing with OpenTelemetry
InterviewJuniorWhat's the difference between a trace and a span?

A trace is a request's whole journey (one trace id); a span is one piece of work inside it.

A span (an HTTP call, a query, a message send) has a start, an end, attributes and a parent span. Spans sharing a trace id form a tree that shows where the time went.

Read in post: Distributed tracing with OpenTelemetry
InterviewJuniorWhat are logs, metrics and traces each for?

Metrics say whether the system is healthy, traces show where one request was slow, logs give the details at one point.

Metrics (p99, error rate) are cheap to keep for a long time. You typically go from a metric alert to a trace to narrow things down, then to the logs of that span; the trace id ties the three together.

Read in post: Distributed tracing with OpenTelemetry
InterviewMidHow is context passed between services?

Through W3C Trace Context headers: traceparent in the form version-traceid-parentid-flags, plus tracestate for vendor data.

For example 00-<32 hex>-<16 hex>-01. The caller puts its own span id in parent-id, and the receiver creates a child span with the same trace id. With message brokers, the context goes in the message headers. Within a process it lives in a ThreadLocal, so it has to be carried along when work moves to another thread.

Read in post: Distributed tracing with OpenTelemetry
InterviewMidWhat does the OpenTelemetry Java agent do?

It injects bytecode at class-load time to create spans for common libraries automatically, with no code changes.

It covers Spring MVC, JDBC, Kafka and HTTP clients; propagates context through headers and executors, puts the trace id into the logging MDC, and exports traces, metrics and logs over OTLP. It's configured with OTEL_* environment variables. The price is slower startup and no native-image support.

Read in post: Distributed tracing with OpenTelemetry
InterviewMidWhy run an OTel Collector instead of exporting straight to the backend?

So services only have to push data quickly, while batching, retries, filtering, sampling and routing happen in the Collector.

The Collector also enforces memory limits, scrubs sensitive data, runs tail sampling and sends to one or several backends. Switching backends doesn't require redeploying services. For small systems or development, exporting directly is fine.

Read in post: Distributed tracing with OpenTelemetry
InterviewMidA child span starts before its parent in the waterfall. Why?

The two machines' clocks are skewed.

Each span's duration is still right because it's measured on one machine, but their relative positions are off by the skew. Run NTP/chrony everywhere and don't draw conclusions from a few milliseconds of offset between services.

Read in post: Distributed tracing with OpenTelemetry
InterviewSeniorHow do head and tail sampling differ, and which do you pick?

Head decides at the start of the trace from the trace id, cheap but blind to errors; tail decides in the Collector after seeing the trace, keeps errors but is costly and stateful.

  • Head: the decision travels with the sampled flag so traces stay complete, but it can't know whether the request will fail or be slow.
  • Tail: every span must reach the Collector, the Collector needs memory, and you must route by trace id so all spans of a trace reach the same instance.
  • Low volume: keep 100% with short retention. High volume: tail sampling keeps errors, slow and critical flows and a small share of the rest, with head sampling in front for protection if needed.
Read in post: Distributed tracing with OpenTelemetry
InterviewSeniorHow do you keep a trace intact across Kafka and an outbox?

Carry traceparent in the message headers; with an outbox, store it in the outbox row so the relay can set it back.

The producer puts traceparent in the headers (the agent does this for the Kafka client), and the consumer reads it and creates a child span or a span link. With an outbox, the original request only writes to the DB and a relay sends the message later on another thread without the context, so the relay must take traceparent from the row. Batch consumers use span links because one span can't have several parents.

Read in post: Distributed tracing with OpenTelemetry
InterviewSeniorWhere does tracing cost you performance or money, and how do you control it?

CPU, heap and startup time in the service, plus network and storage per span; control it with measurement, sampling, low cardinality and TTLs.

  • In the service: CPU and heap for instrumentation, agent startup time, the export queue. In the network and storage: spans times requests.
  • Controls: measure before and after enabling, disable instrumentations that produce tiny spans, sample, use templated span names, set TTLs in storage, and monitor dropped spans.
  • Export is asynchronous and batched, so a dead Collector doesn't slow requests down; the trade-off is that spans get lost.
Read in post: Distributed tracing with OpenTelemetry
InterviewSeniorA user reports a failed request. How do you get from the report to the cause?

Take the traceId from the error response, open the trace to find the Error span, then read that span's logs via the trace_id in the MDC.

The error response includes a traceId (ProblemDetail), and the user or support sends it to us. In the trace, I look for the span with Error status and the spans taking the time. That's why the tail-sampling policy must always keep failing traces. Even without a trace, the trace id still filters logs across every service, because logs carry it whether or not the span was sampled.

Read in post: Distributed tracing with OpenTelemetry
Trade-offSeniorChoosing orchestration or choreographyThe case for choreography: it scales better (no dependence on the orchestrator's scalability), decouples teams better, makes fewer calls, and is more durable because events sit in a broker with retention. And if the flow is so complex that it needs an orchestrator, maybe the service boundaries are wrong. The case for o

The case for choreography: it scales better (no dependence on the orchestrator's scalability), decouples teams better, makes fewer calls, and is more durable because events sit in a broker with retention. And if the flow is so complex that it needs an orchestrator, maybe the service boundaries are wrong.

The case for orchestration: from about 4–5 steps, with branches, timeouts or human approval, choreography turns into an "event spider web" nobody fully understands. Workflow engines (Temporal, Camunda) give you durable state, retries, timeouts, and a screen to inspect each saga.

How I choose: 2–3 linear steps → choreography; many steps, branches, or money that needs an audit trail → orchestration. Either way, put a saga_id on every event and trace so you can debug.

Read in post: Distributed transactions
Edge caseSeniorA compensation is not a "rollback"A compensation is a new business transaction. It doesn't erase history: a refund is a refund transaction, not the deletion of the charge. It can fail (the card is closed), it can arrive after the user has already seen the old state, and it must be idempotent. Design the compensation together with the forward step, not

A compensation is a new business transaction. It doesn't erase history: a refund is a refund transaction, not the deletion of the charge. It can fail (the card is closed), it can arrive after the user has already seen the old state, and it must be idempotent. Design the compensation together with the forward step, not later.

Read in post: Distributed transactions
InterviewMidHow does 2PC work, and what are its downsides?

The coordinator sends prepare to every participant; if all say yes it sends commit, and if any says no it rolls back. The downsides: locks are held through both phases, and everything gets stuck if the coordinator dies after prepare.

Also: not every system supports XA (Kafka, partner REST APIs), and latency is set by the slowest participant.

Read in post: Distributed transactions
InterviewMidWhat problem does the transactional outbox solve?

Dual write: writing to the DB and sending a message touch two systems, and a crash in between loses one of them. The outbox writes the message to a table in the same transaction as the data, then a relay pushes it to the broker.

The result is at-least-once delivery, so the receiver must be idempotent. The outbox does not make several services commit together.

Read in post: Distributed transactions
InterviewMidHow does a saga compensation differ from a rollback?

A rollback erases the change as if it never happened, inside one database; a compensation is a new business transaction that reverses the effect, like a refund.

Others may have seen the state before the compensation, and the compensation can fail, so it must be idempotent.

Read in post: Distributed transactions
InterviewSeniorSaga orchestration or choreography? How do you choose?

A few linear steps → choreography (fewer moving parts, independent teams); many steps, branches, timeouts or audit needs → orchestration with a workflow engine.

Choreography makes the overall flow hard to see and debug; orchestration concentrates logic in one place and depends on the orchestrator's scalability. A very complex flow can be a sign that the service boundaries are wrong.

Read in post: Distributed transactions
InterviewSeniorWhat is a pivot transaction, and how does it shape saga design?

It's the go/no-go step: once it succeeds, the saga must run to the end. Every step before it must be compensatable, and every step after it must be retriable.

So: make the step most likely to fail (payment) the pivot, and push steps that can't be undone (partner calls, emails) and value-increasing steps (adding points) after it.

Read in post: Distributed transactions
InterviewSeniorA saga has no isolation. How do you prevent lost updates?

A semantic lock: the first step sets a *_PENDING status, and another saga that sees it fails fast so the client retries, or waits.

On top of that: check the version on update, design commutative operations (add/subtract instead of overwrite), and reorder steps to reduce dirty reads.

Read in post: Distributed transactions
InterviewSeniorA colleague suggests distributed transactions to raise TPS. How do you respond?

Distributed transactions are for correctness (atomicity), not speed; they only raise TPS when the data is already split and lock contention is low.

If transactions fight over the same resources, more nodes just add network round trips and lock hold time. Ask what the real bottleneck is (contention, I/O, CPU) before choosing sharding, caching, or a redesign.

Read in post: Distributed transactions
InterviewSeniorWhen would you use TCC instead of a saga?

When the resource can be reserved (money, stock, seats) and you don't want others to see a "charged, then refunded" state: Try reserves, Confirm uses, Cancel releases.

The price is three APIs per service, plus handling empty rollback, suspension and idempotency. A saga is easier when a step can't be reserved, or when exposing intermediate states is acceptable.

Read in post: Distributed transactions
Trade-offMidContainer or virtual machineContainer: light, fast to start, many per host. The price is weaker isolation: a kernel bug or loose config (--privileged, mounting docker.sock) can lead to escaping to the host. VM: its own kernel, a strong security boundary. The price is RAM and slow startup. In practice you use both: Kubernetes runs containers on VM
  • Container: light, fast to start, many per host. The price is weaker isolation: a kernel bug or loose config (--privileged, mounting docker.sock) can lead to escaping to the host.
  • VM: its own kernel, a strong security boundary. The price is RAM and slow startup.
  • In practice you use both: Kubernetes runs containers on VMs; for strong isolation use a sandbox like gVisor or Kata Containers.
Read in post: Docker for Spring Boot
TILJuniorDocker on macOS and Windows runs inside a Linux VMNamespaces and cgroups are Linux kernel features, so Docker Desktop starts a small Linux VM to run containers. Consequences: bind mounts from a Mac are slower, and an image built on an ARM Mac is arm64 and won't run on an amd64 server unless you build multi-platform (docker buildx build --platform linux/amd64,linux/arm

Namespaces and cgroups are Linux kernel features, so Docker Desktop starts a small Linux VM to run containers. Consequences: bind mounts from a Mac are slower, and an image built on an ARM Mac is arm64 and won't run on an amd64 server unless you build multi-platform (docker buildx build --platform linux/amd64,linux/arm64).

Read in post: Docker for Spring Boot
Edge caseMidCopying all the source before downloading dependenciesChange one Java line and COPY . . changes, every later layer reruns, and Maven downloads every dependency on every build. Split it: COPY pom.xml and .mvn/, then RUN ./mvnw dependency:go-offline, and only then COPY src. With BuildKit, add RUN --mount=type=cache,target=/root/.m2 so the Maven repository survives across bu
COPY . .
RUN ./mvnw package

Change one Java line and COPY . . changes, every later layer reruns, and Maven downloads every dependency on every build. Split it: COPY pom.xml and .mvn/, then RUN ./mvnw dependency:go-offline, and only then COPY src. With BuildKit, add RUN --mount=type=cache,target=/root/.m2 so the Maven repository survives across builds without ending up in the image.

Read in post: Docker for Spring Boot
Trade-offSeniorHand-written Dockerfile, buildpacks or JibHand-written Dockerfile: full control, readable by everyone. The price: the team maintains best practices and patches the base image itself. Buildpacks (./mvnw spring-boot:build-image, using Paketo): no Dockerfile, layering done for you, non-root, and a memory calculator that derives -Xmx from the limit. The price: nee
  • Hand-written Dockerfile: full control, readable by everyone. The price: the team maintains best practices and patches the base image itself.
  • Buildpacks (./mvnw spring-boot:build-image, using Paketo): no Dockerfile, layering done for you, non-root, and a memory calculator that derives -Xmx from the limit. The price: needs a Docker daemon, harder to customise.
  • Jib (Google's Maven plugin): builds and pushes without a Docker daemon, great for CI. The price: no arbitrary RUN.
  • Need control: Dockerfile. Want the least to maintain: buildpacks or Jib.
Read in post: Docker for Spring Boot
Edge caseSeniorAlpine uses musl, not glibcAlpine is small because it uses musl libc instead of glibc. The JDK has musl builds, so pure Java runs, but: Java libraries with native parts (some versions of snappy-java, zstd-jni, RocksDB, Netty tcnative) may only ship .so files built for glibc and fail with UnsatisfiedLinkError at runtime. musl's DNS resolver diffe

Alpine is small because it uses musl libc instead of glibc. The JDK has musl builds, so pure Java runs, but:

  • Java libraries with native parts (some versions of snappy-java, zstd-jni, RocksDB, Netty tcnative) may only ship .so files built for glibc and fail with UnsatisfiedLinkError at runtime.
  • musl's DNS resolver differs from glibc (handling of search/ndots; older musl versions don't retry over TCP for large DNS answers), causing odd resolution failures in Kubernetes.
  • musl's memory allocator can be slower under heavily threaded load.

The few dozen MB saved are rarely worth it. For small and few CVEs, choose distroless (still glibc).

Read in post: Docker for Spring Boot
TILMidDistroless has no shell, so everything must be exec formA distroless image holds only the JRE, CA certificates and a few system files: no sh, no curl, no package manager. So ENTRYPOINT ["sh", "-c", ...] and HEALTHCHECK CMD curl ... can't run. The java21 image already sets ENTRYPOINT ["/usr/bin/java", "-jar"], so you only add CMD ["app.jar"]. Debug with the :debug tag (it ha

A distroless image holds only the JRE, CA certificates and a few system files: no sh, no curl, no package manager. So ENTRYPOINT ["sh", "-c", ...] and HEALTHCHECK CMD curl ... can't run. The java21 image already sets ENTRYPOINT ["/usr/bin/java", "-jar"], so you only add CMD ["app.jar"]. Debug with the :debug tag (it has busybox) or with kubectl debug, which attaches a temporary container with tools to the pod.

Read in post: Docker for Spring Boot
Edge caseMidSetting -Xmx equal to the memory limit-Xmx1g with memory: 1Gi sounds reasonable, but the JVM needs a few hundred MB outside the heap. As the heap fills, RSS crosses the limit and the kernel kills the container (137) before any OutOfMemoryError: the pod restarts periodically and the log just stops. Fix: use MaxRAMPercentage, or keep -Xmx below the limit by

-Xmx1g with memory: 1Gi sounds reasonable, but the JVM needs a few hundred MB outside the heap. As the heap fills, RSS crosses the limit and the kernel kills the container (137) before any OutOfMemoryError: the pod restarts periodically and the log just stops. Fix: use MaxRAMPercentage, or keep -Xmx below the limit by a margin measured with NMT.

Read in post: Docker for Spring Boot
Edge caseJuniorA HEALTHCHECK that calls curl in an image without curlHEALTHCHECK CMD curl -f http://localhost:8080/actuator/health fails silently if the image has no curl (distroless certainly doesn't): the container is unhealthy while the app works fine. Check with docker inspect --format '{{json .State.Health}}'. Without tools, leave it to Kubernetes probes.

HEALTHCHECK CMD curl -f http://localhost:8080/actuator/health fails silently if the image has no curl (distroless certainly doesn't): the container is unhealthy while the app works fine. Check with docker inspect --format '{{json .State.Health}}'. Without tools, leave it to Kubernetes probes.

Read in post: Docker for Spring Boot
InterviewJuniorHow is a container different from a virtual machine?

A container is a process sharing the host kernel, isolated by namespaces and limited by cgroups; a VM has its own kernel running on a hypervisor.

Since no kernel boots, a container starts in milliseconds and is much lighter. The price is a weaker security boundary than a VM, and Linux containers need a Linux kernel (on Mac/Windows, Docker runs inside a Linux VM).

Read in post: Docker for Spring Boot
InterviewJuniorWhat's the difference between CMD and ENTRYPOINT?

ENTRYPOINT is the program that always runs; CMD is the default arguments, replaced by whatever follows the image name in docker run.

A common combination: ENTRYPOINT ["java", "-jar", "app.jar"] and CMD ["--spring.profiles.active=prod"]. Both should be in exec form (a JSON array) so the process is PID 1 and receives signals; shell form runs through /bin/sh -c.

Read in post: Docker for Spring Boot
InterviewJuniorWhat's the difference between COPY and ADD? Which should you use?

Use COPY. ADD does two extra implicit things: downloads from URLs and auto-extracts local tar files.

Implicit behaviour makes a Dockerfile hard to predict (a .tar.gz gets unpacked when the reader doesn't expect it), and URL downloads via ADD are hard to checksum and cache. If you need a download, use RUN curl with a checksum check in the build stage.

Read in post: Docker for Spring Boot
InterviewMidWhy shouldn't you deploy images tagged latest?

Because latest is a label that can be overwritten: you can't tell what code production runs, two nodes may pull different images, and rollback is undefined.

latest is only the default tag name, not "the newest build". Tag by version or commit SHA and deploy by digest (@sha256:...) so the content can't change. Immutable tags also give traceability: an error in an image maps to a commit.

Read in post: Docker for Spring Boot
InterviewMidWhy shouldn't a container run as root?

Because if the app is exploited, the attacker has root inside the container, one step closer to the host given a kernel bug or loose configuration.

Create a system user in the Dockerfile and USER app; on Kubernetes add runAsNonRoot: true and readOnlyRootFilesystem: true with an emptyDir for /tmp. Spring Boot doesn't need root, since port 8080 isn't privileged.

Read in post: Docker for Spring Boot
InterviewSeniorA Spring Boot pod keeps restarting with exit code 137 and nothing in the logs. How do you investigate?

137 means death by SIGKILL: usually the kernel OOM killer because RSS crossed the memory limit, or a kill after the grace period because the app didn't stop in time on SIGTERM.

  • kubectl describe pod: Last State: Terminated, Reason: OOMKilled means memory. Compare -Xmx or MaxRAMPercentage with the limit; measure RSS and NMT to see the non-heap part (metaspace, threads, direct buffers).
  • Not OOMKilled but restarts during deploys: check for a shell-form ENTRYPOINT and shutdown time versus terminationGracePeriodSeconds.
  • An aggressive liveness probe also causes restarts (the pod is killed during a long GC pause).
  • Fix: a sensible heap percentage, ExitOnOutOfMemoryError, limit = measured usage plus 20–30% headroom.
Read in post: Docker for Spring Boot
InterviewSeniorA Spring Boot image is 900 MB and each build takes 8 minutes. How do you optimise it?

Split build and runtime stages, use a JRE, order layers by change frequency, split the jar into layers, and cache Maven dependencies.

  • Multi-stage: the runtime image has only the JRE and the app, no JDK, Maven or source.
  • COPY pom.xml and fetch dependencies before COPY src; cache-mount /root/.m2 with BuildKit; add .dockerignore.
  • extract --layers: a code change only touches the few-KB application layer.
  • In CI: BuildKit layer cache (cache-from/cache-to), and don't run tests twice (test in the CI step, the Dockerfile only packages).
  • Measure before and after with docker history and build times, don't guess.
Read in post: Docker for Spring Boot
InterviewSeniorWould you pick Alpine or distroless for a production Java service?

Usually distroless or a JRE on Debian/Ubuntu, not Alpine, because Alpine trades glibc for musl to save only a few dozen MB.

musl can break native libraries built for glibc and resolves DNS differently. Distroless keeps glibc and has very few packages, so few CVEs, but no shell: exec form only, debugging via kubectl debug or the :debug tag. If the team needs a shell for operations, a JRE on Ubuntu is a reasonable compromise.

Read in post: Docker for Spring Boot
Edge caseJuniorBuilding a 404 ResponseEntity in every controller methodThe course prompt asks each method to do if (user == null) return ResponseEntity.status(NOTFOUND).body(ApiResponse.notFound(...)). That repeats in every endpoint, one gets forgotten, and the error format drifts. Simpler: the service throws ResourceNotFoundException, and one @RestControllerAdvice turns it into 404 for t

The course prompt asks each method to do if (user == null) return ResponseEntity.status(NOT_FOUND).body(ApiResponse.notFound(...)). That repeats in every endpoint, one gets forgotten, and the error format drifts.

Simpler: the service throws ResourceNotFoundException, and one @RestControllerAdvice turns it into 404 for the whole app (centralized error handling). The controller only keeps the happy path.

Read in post: DTOs, responses and validation for a Spring Boot REST API
Trade-offMidEnvelope or bare body for success responsesBare body ({"id":42,...}): true to HTTP, fewer bytes, easy to cache, OpenAPI generates clean clients. Pagination metadata goes into headers (Link, X-Total-Count) or a dedicated page DTO. Envelope ({"data":...,"meta":...}): one fixed place for meta, message, deprecation warnings; the frontend writes one shared unwrap fu
  • Bare body ({"id":42,...}): true to HTTP, fewer bytes, easy to cache, OpenAPI generates clean clients. Pagination metadata goes into headers (Link, X-Total-Count) or a dedicated page DTO.
  • Envelope ({"data":...,"meta":...}): one fixed place for meta, message, deprecation warnings; the frontend writes one shared unwrap function. The cost is an extra nesting level and fiddlier generics in OpenAPI.
  • Either is fine as long as the whole system uses one style and errors are always ProblemDetail. Don't put statusCode in the body.
Read in post: DTOs, responses and validation for a Spring Boot REST API
Edge caseMidPutting validation annotations on the entityThe source puts @NotBlank, @Email and @Size(min = 6) for the password directly on the User entity. That is wrong in three ways: The entity stores the hash, not the raw password. A length rule on the hash field checks the wrong thing. Hibernate also validates entities before writing, so a rule from the sign-up form now

The source puts @NotBlank, @Email and @Size(min = 6) for the password directly on the User entity. That is wrong in three ways:

  • The entity stores the hash, not the raw password. A length rule on the hash field checks the wrong thing.
  • Hibernate also validates entities before writing, so a rule from the sign-up form now blocks other flows (imports, password change).
  • Create and update need different rules; one set of annotations on the entity can't express that.

Input validation goes on the request DTO. The entity keeps data constraints (nullable = false, unique, column length), and the database is the last line.

Read in post: DTOs, responses and validation for a Spring Boot REST API
Trade-offMidMapStruct or a hand-written mapperMapStruct: less boilerplate with hundreds of fields; with unmappedTargetPolicy = ERROR the compiler fails when a new field is forgotten. The cost: another annotation processor, logic hidden in annotations, mapping errors that confuse newcomers, and an easy accidental mapping of password when names match. Hand-written:
  • MapStruct: less boilerplate with hundreds of fields; with unmappedTargetPolicy = ERROR the compiler fails when a new field is forgotten. The cost: another annotation processor, logic hidden in annotations, mapping errors that confuse newcomers, and an easy accidental mapping of password when names match.
  • Hand-written: explicit, debuggable, a reviewer sees exactly which fields go out. The cost: easy to forget a new field, so mappings need tests.
  • Suggestion: hand-write in small and medium projects; when mapping becomes repetitive work that eats review time, switch to MapStruct with the error policy.
Read in post: DTOs, responses and validation for a Spring Boot REST API
Edge caseMidfindAllById doesn't fail on missing idsfindAllById(List.of(1L, 999L)) returns one element and throws nothing. If you just assign the result to the role, a client sending a wrong id gets 200 and silently loses permissions. Compare the counts and return 404 (or 400) naming the missing id. Take the ids as a Set<Long, not a List<Long: a list like [1, 1] makes t

findAllById(List.of(1L, 999L)) returns one element and throws nothing. If you just assign the result to the role, a client sending a wrong id gets 200 and silently loses permissions. Compare the counts and return 404 (or 400) naming the missing id.

Take the ids as a Set<Long>, not a List<Long>: a list like [1, 1] makes the count comparison report a false miss.

Read in post: DTOs, responses and validation for a Spring Boot REST API
Edge caseSenior@Size(max = 72) counts characters, BCrypt counts bytesBCrypt only uses the first 72 bytes of the password and ignores the rest. @Size(max = 72) counts UTF-16 characters. Vietnamese letters with diacritics take 2–3 bytes each, so 26 characters "ừ…1" (76 bytes) pass @Size but exceed BCrypt's limit: two passwords differing only at the end would match the same hash. In the ex

BCrypt only uses the first 72 bytes of the password and ignores the rest. @Size(max = 72) counts UTF-16 characters. Vietnamese letters with diacritics take 2–3 bytes each, so 26 characters "ừ…1" (76 bytes) pass @Size but exceed BCrypt's limit: two passwords differing only at the end would match the same hash.

In the experiment, that string was rejected by @StrongPassword (counting bytes). The lab uses @Size(max = 72), so it still has this gap for non-ASCII passwords. Another way out: switch to Argon2 (storing passwords).

Read in post: DTOs, responses and validation for a Spring Boot REST API
TILMidPage numbers from 1 without manual arithmeticThe source converts page - 1 when calling the repository and + 1 when responding. Spring Boot already has spring.data.web.pageable.one-indexed-parameters=true: ?page=1 is the first page. Pair it with spring.data.web.pageable.max-page-size (default 2000) to stop ?size=1000000. Don't serialize Page<T directly: the PageIm

The source converts page - 1 when calling the repository and + 1 when responding. Spring Boot already has spring.data.web.pageable.one-indexed-parameters=true: ?page=1 is the first page. Pair it with spring.data.web.pageable.max-page-size (default 2000) to stop ?size=1000000.

Don't serialize Page<T> directly: the PageImpl shape is not a stable contract, and Spring Data 3.3+ even logs a warning. Build your own page DTO, or enable @EnableSpringDataWebSupport(pageSerializationMode = VIA_DTO).

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewJuniorWhy not return JPA entities directly from a controller?

Because they leak sensitive data, cause lazy-loading and JSON recursion errors, and lock the database schema into the API contract.

A response DTO holds only the fields allowed out and is built inside the transaction. A request DTO blocks mass assignment: the client can't sneak in id or roles.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewJuniorWhat should a POST that creates a resource return?

201 Created, a Location header pointing to the new resource, and usually the created resource as the body.

In Spring: ResponseEntity.created(uri).body(dto), with uri built from ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}"). A successful DELETE returns 204 with no body.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewMidDo you put a statusCode in the response body?

No. The HTTP status is already in the status line; repeating it in the body creates two sources of truth that can disagree.

Errors use ProblemDetail (which has a standard status field per RFC 9457). Success uses a bare body or a data/meta envelope, as long as it's consistent across the system.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewMidHow do PUT and PATCH differ when designing DTOs?

PUT sends the whole resource, so the DTO looks like the create DTO; PATCH sends only changed fields, so it must tell "not sent" from "sent as null".

A record with all-nullable fields can't. Use JSON Merge Patch read as a JsonNode, or JsonNullable, or move specific actions (password change) to their own endpoints.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewMidYou update a role with permissionIds and one id doesn't exist. What happens?

If you just call findAllById and assign, the bad id is silently dropped and the client gets 200. Compare the counts and return 404 naming the missing id.

Take the ids as a Set so duplicates don't break the count, and replace the whole permission set (PUT semantics) with clear() + addAll() on a Set collection.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewMidValidation groups or two DTOs for create and update?

Usually two separate records: easier to read, no groups to remember, one contract per DTO.

Groups need @Validated(OnCreate.class) because @Valid doesn't take groups, and field annotations get crowded. They're only worth it when both DTOs are almost identical.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewSeniorYou already check existsByEmail in the service. Why do you still need UNIQUE?

Because check-then-write isn't atomic: two parallel requests both see "not there" and both insert. Only a database constraint stops that.

Keep the exists check for a friendly error; map the DataIntegrityViolationException from UNIQUE to 409 as well. Normalize the email (trim, lowercase) before both steps because UNIQUE compares bytes.

Read in post: DTOs, responses and validation for a Spring Boot REST API
InterviewSeniorHow should you limit password length with BCrypt?

Limit it in bytes, at most 72, because BCrypt ignores every byte after 72; @Size counts characters, which isn't enough for Unicode strings.

Write a constraint that counts UTF-8 bytes, or use an algorithm without this limit such as Argon2. Keep a sane upper bound anyway to block DoS with huge passwords.

Read in post: DTOs, responses and validation for a Spring Boot REST API
Trade-offMidSearch in PostgreSQL vs adding ElasticsearchPostgreSQL (tsvector + GIN, pgtrgm, PostGIS): no extra system, data stays consistent within one transaction, good enough for a few million rows with simple queries. Weak at: relevance scoring (BM25, per-field boosts), analyzers for many languages, search-as-you-type, spelling correction, multi-dimensional aggregations
  • PostgreSQL (tsvector + GIN, pg_trgm, PostGIS): no extra system, data stays consistent within one transaction, good enough for a few million rows with simple queries. Weak at: relevance scoring (BM25, per-field boosts), analyzers for many languages, search-as-you-type, spelling correction, multi-dimensional aggregations for filters (facets) on large data.
  • Elasticsearch: built for full-text, facets and geo, and scales read load with replicas. The cost: a cluster to run (heap, shards, upgrades), data that is a lagging copy of the DB (usually a few seconds), and a sync pipeline you write and repair yourself.
  • My rule: start with PostgreSQL and move when you hit the weaknesses above. ES is never the source of truth for data that must be consistent, like room availability or money.
Read in post: Elasticsearch
Edge caseMidCalling ?refresh=true after every write to "see it immediately" wrecks indexing performanceEach refresh creates a small segment; refreshing after every document creates thousands of them, merging never stops, and write throughput collapses. If a request really must read back what it just wrote (an admin page after saving), use ?refresh=waitfor to wait for the next scheduled refresh. Better still: return the

Each refresh creates a small segment; refreshing after every document creates thousands of them, merging never stops, and write throughput collapses. If a request really must read back what it just wrote (an admin page after saving), use ?refresh=wait_for to wait for the next scheduled refresh. Better still: return the fresh data from the DB or from the response itself.

Read in post: Elasticsearch
Edge caseMidFolding away all diacritics makes different Vietnamese words collideWith asciifolding, "bàn" (table), "bán" (sell) and "bạn" (friend) all become ban; "Đà Lạt" and "da lát" collide too. The usual fix: a multi-field with one accented subfield (standard) and one folded (vifolded), queried with multimatch and a higher boost on the accented one. The standard tokenizer also splits by syllabl

With asciifolding, "bàn" (table), "bán" (sell) and "bạn" (friend) all become ban; "Đà Lạt" and "da lát" collide too. The usual fix: a multi-field with one accented subfield (standard) and one folded (vi_folded), queried with multi_match and a higher boost on the accented one.

The standard tokenizer also splits by syllable and doesn't understand compound words ("Đà Lạt" is two tokens), so use match_phrase or shingle when order matters. Vietnamese word-segmentation plugins are community plugins, not Elastic's, so weigh that before version upgrades.

Read in post: Elasticsearch
Edge caseMidUsing float_range for a single value breaks sorting and aggregationsStore an "average price" as floatrange and you can't sort on it. On Elasticsearch 8.15, sorting on a range field returned internal byte strings as sort values, in an order unrelated to price; the current docs say sorting on range fields is rejected with a 400. Aggregations are limited to histogram and cardinality. A si

Store an "average price" as float_range and you can't sort on it. On Elasticsearch 8.15, sorting on a range field returned internal byte strings as sort values, in an order unrelated to price; the current docs say sorting on range fields is rejected with a 400. Aggregations are limited to histogram and cardinality.

A single price belongs in long (VND) or scaled_float; if you also need the price range, add a separate range field next to it.

Read in post: Elasticsearch
Edge caseMidAn array of objects mapped as object gives wrong results when you filter several fields of one elementobject flattens the array into one value array per field, so "bed = double and guests = 1" matches across two different elements. Use nested when you query several fields of the same element. The cost: each nested element is a hidden Lucene document (a homestay with 100 rooms becomes 101 documents), queries are slower,

object flattens the array into one value array per field, so "bed = double and guests = 1" matches across two different elements. Use nested when you query several fields of the same element.

The cost: each nested element is a hidden Lucene document (a homestay with 100 rooms becomes 101 documents), queries are slower, and the defaults cap you at 10,000 nested objects per document and 100 nested fields per index. A single object like host stays object.

Read in post: Elasticsearch
Trade-offSeniorNested, denormalised flags, or a separate index for child datanested: correct per element, child data travels with the parent. But updating one element reindexes the parent and all its hidden documents; a poor fit for child data that changes often or is large (reviews, daily prices). Denormalised flat fields: precompute what you filter on (hasdoublebedfortwo: true, maxroomguests:
  • nested: correct per element, child data travels with the parent. But updating one element reindexes the parent and all its hidden documents; a poor fit for child data that changes often or is large (reviews, daily prices).
  • Denormalised flat fields: precompute what you filter on (has_double_bed_for_two: true, max_room_guests: 2). Fastest, but every new filter is a new field, recomputed when logic changes.
  • Separate index (a reviews index with homestay_id): independent updates, no size limit; the cost is two queries or a join field (parent-child, slower still).
  • For homestays: few rooms, rarely changed → nested or precomputed fields. Many reviews, added constantly → separate index, with the homestay keeping only rating and review_count.
Read in post: Elasticsearch
Edge caseJuniorSorting or aggregating on a text field is rejectedSorting by name fails with "Fielddata is disabled on [name]... Please use a keyword field instead". Turning on fielddata: true builds columnar data from the inverted index on the heap, which is memory-hungry, and sorts by individual tokens rather than the whole string. The right fix: sort on the name.raw keyword multi-

Sorting by name fails with "Fielddata is disabled on [name]... Please use a keyword field instead". Turning on fielddata: true builds columnar data from the inverted index on the heap, which is memory-hungry, and sorts by individual tokens rather than the whole string. The right fix: sort on the name.raw keyword multi-field.

Read in post: Elasticsearch
Edge caseMidfrom + size can't page deeper than 10,000 hitsTo serve from=9990, size=10, every shard sends its top 10,000 hits to the coordinating node, which merges them and throws away 9,990. That's why index.maxresultwindow defaults to 10,000 and deeper requests are rejected. For "load more" or iterating over many hits, use searchafter with a unique sort value (add homestayi

To serve from=9990, size=10, every shard sends its top 10,000 hits to the coordinating node, which merges them and throws away 9,990. That's why index.max_result_window defaults to 10,000 and deeper requests are rejected.

For "load more" or iterating over many hits, use search_after with a unique sort value (add homestay_id as a tie-breaker) plus a point-in-time (PIT, a frozen view of the index) so results don't shift between pages. It's the same idea as keyset pagination in SQL.

Read in post: Elasticsearch
Trade-offMidChanging a mapping: reindex into a new index behind an alias instead of editing in placeYou can't change an existing field's type (object to nested, a different analyzer), and the primary shard count is fixed. Always have the application read and write through an alias (homestays → homestaysv1). To change the mapping: create homestaysv2, reindex (reindex or re-run the load from the DB), have the sync pipe

You can't change an existing field's type (object to nested, a different analyzer), and the primary shard count is fixed. Always have the application read and write through an alias (homestays → homestays_v1).

To change the mapping: create homestays_v2, reindex (_reindex or re-run the load from the DB), have the sync pipeline write to both during the switch, move the alias to v2 in one atomic _aliases call, and drop v1 once you're sure. Without an alias, renaming the index means changing code everywhere, with downtime.

Read in post: Elasticsearch
InterviewJuniorWhat is an inverted index?

A structure that maps each term to the list of documents containing it (with positions), like the index at the back of a book.

Searching a word means looking up the term and reading its list instead of scanning every document, which is why full-text search is fast. It's a poor fit for "what value does this document have" (that's what doc values are for).

Read in post: Elasticsearch
InterviewJuniorHow do text and keyword differ?

text goes through an analyzer for full-text search; keyword keeps the whole string for exact filters, sorting and aggregations.

text is split into tokens and queried with match. keyword can pass through a normalizer and is queried with term. When a field needs both, use a multi-field: name as text and name.raw as keyword.

Read in post: Elasticsearch
InterviewMidWhat's inside an analyzer? How do you support Vietnamese search without diacritics?

Character filters (0+) rewrite the string, a tokenizer (exactly 1) splits tokens, token filters (0+) change tokens. For diacritic-free search, use lowercase + asciifolding at both index and search time.

asciifolding also maps đ to d. Keep an extra accented subfield and boost it so correctly accented matches rank first, because folding makes many different words collide.

Read in post: Elasticsearch
InterviewMidWhen do you use nested instead of object?

When the field is an array of objects and you filter several conditions on the same element.

object flattens the array, so conditions match across elements. nested stores each element as its own hidden document, which is correct but costlier: more documents, slower queries, updating one element reindexes the whole parent, and there are size limits.

Read in post: Elasticsearch
InterviewMidHow do must and filter differ in a bool query?

Both must match, but only must contributes to the relevance score; filter doesn't score and is cached per segment.

Yes/no conditions (city, price range, radius) belong in filter; only the text that needs ranking goes in must.

Read in post: Elasticsearch
InterviewMidWhy can't I find a document right after indexing it?

Because ES is near real-time: a new document is searchable only after the next refresh (every second by default for indices being searched).

Don't force a refresh after every write, since it creates lots of tiny segments. If you must, use refresh=wait_for on that one request, or read the fresh data from the DB.

Read in post: Elasticsearch
InterviewSeniorHow do you keep Elasticsearch correctly in sync with PostgreSQL?

No dual writes; use an outbox or CDC, write idempotently with _id = primary key plus version_type=external, and reconcile periodically.

  • Dual writes: the DB commits but ES fails and they drift forever, and concurrent requests can write out of order.
  • An outbox in the same transaction, or CDC (Debezium reading the WAL through Kafka).
  • The row version as an external version, so late, stale events are rejected.
  • A reconciliation job comparing counts or checksums, and a full reindex from the DB when needed.
Read in post: Elasticsearch
InterviewSeniorYou need to change a field's analyzer on a production index. How?

You can't change it in place: create a new index, reindex, then swap the alias atomically.

The application must read and write through an alias. Create a new index version with the new mapping and reindex from the old index or reload from the DB; meanwhile the sync pipeline writes to both (or replays changes since the reindex started). Check counts and search quality, swap the alias with _aliases, and keep the old index for a while so you can roll back.

Read in post: Elasticsearch
InterviewSeniorHow do you choose the number of shards for an index?

By expected size: 10–50 GB and under roughly 200 million documents per shard; a small index gets 1 primary shard.

Many small shards make every query fan out further and cost heap for metadata. The primary count is fixed at creation and only changes via split, shrink or reindex, so for data that grows over time (logs, events) use time-based indices or data streams with rollover. Scale read load with replicas, not more primaries.

Read in post: Elasticsearch
InterviewSeniorShould daily room availability go into Elasticsearch?

Not as the deciding source: ES filters candidates, PostgreSQL checks daily availability and locks at booking time.

Availability changes with every booking, each change means reindexing the document, and ES lags the DB by seconds, so it can show rooms that are already taken. You can put coarse data in ES to prune, but the final check must happen in the database.

Read in post: Elasticsearch
Trade-offMidHash index or B-tree in PostgreSQLHash: slightly cheaper equality lookups (3 pages vs 4, cost 8.02 vs 8.45). It stores only a 4-byte hash code, so it can be smaller for long keys, but not for short keys like char(13) (97 MB vs 93 MB). No ranges, ordering, UNIQUE, multiple columns or index-only scans. Only safe since PostgreSQL 10, when hash indexes bec
  • Hash: slightly cheaper equality lookups (3 pages vs 4, cost 8.02 vs 8.45). It stores only a 4-byte hash code, so it can be smaller for long keys, but not for short keys like char(13) (97 MB vs 93 MB). No ranges, ordering, UNIQUE, multiple columns or index-only scans. Only safe since PostgreSQL 10, when hash indexes became WAL-logged (before that they weren't crash-safe and didn't replicate).
  • B-tree: handles =, ranges, ORDER BY, prefix LIKE, uniqueness and multiple columns.
  • Default to B-tree. Consider hash only for columns compared purely for equality, with long keys (URLs, tokens), on very large tables, and only after measuring.
Read in post: A PostgreSQL index lab on an airline dataset
Edge caseMidA plain B-tree doesn't serve LIKE 'abc%' when the database collation isn't CWith enUS.UTF-8 (the default of many installers), CREATE INDEX ON t (col) serves col = ? but not col LIKE 'abc%'; the plan silently falls back to a Seq Scan. You need a separate index with COLLATE "C" or textpatternops. That index in turn can't serve ORDER BY col in the linguistic collation. No B-tree helps with '%abc'

With en_US.UTF-8 (the default of many installers), CREATE INDEX ON t (col) serves col = ? but not col LIKE 'abc%'; the plan silently falls back to a Seq Scan.

  • You need a separate index with COLLATE "C" or text_pattern_ops. That index in turn can't serve ORDER BY col in the linguistic collation.
  • No B-tree helps with '%abc': use pg_trgm with GIN (fast reads, slower writes) or GiST, or an expression index on reverse(col) for suffix-only search.
  • MySQL InnoDB, by contrast, can use an index for LIKE 'abc%' with ordinary collations.
Read in post: A PostgreSQL index lab on an airline dataset
Edge caseMidAn index only pays off when you fetch a small fraction of the tableOne year: Seq Scan 122 ms, forced index 922 ms. The switch-over point depends on correlation, row width, randompagecost and how much is cached. It's typically a few percent of the table for scattered data and can be much higher when data is written in order. Reports that scan most of a table need a different tool: a su

One year: Seq Scan 122 ms, forced index 922 ms. The switch-over point depends on correlation, row width, random_page_cost and how much is cached. It's typically a few percent of the table for scattered data and can be much higher when data is written in order. Reports that scan most of a table need a different tool: a summary table, time-based partitioning, or running on a replica.

Read in post: A PostgreSQL index lab on an airline dataset
TILSeniorBRIN: a few hundred KB of index for a time column written in orderData inserted in time order (logs, events, transactions) has a time-column correlation close to 1. A BRIN index (CREATE INDEX ... USING brin (createdat)) then stores only the min/max of each 128-page block: a few hundred KB for hundreds of millions of rows instead of several GB for a B-tree, and time-range scans stay e

Data inserted in time order (logs, events, transactions) has a time-column correlation close to 1. A BRIN index (CREATE INDEX ... USING brin (created_at)) then stores only the min/max of each 128-page block: a few hundred KB for hundreds of millions of rows instead of several GB for a B-tree, and time-range scans stay efficient. The catch: BRIN is useless on scattered data (like the random book_date here) and can't serve single-row lookups.

Read in post: A PostgreSQL index lab on an airline dataset
Edge caseSenior"High-cardinality column first" is the wrong rule for composite indexesThe correct rule: 1. Equality columns first. 2. The range or sort column last. After a range on column k, columns k+1 onwards only filter inside the region already read; they no longer bound it. 3. With several ranges, put the one narrowest on real data first. Cardinality is only a hint about the selectivity (the share

The correct rule:

  1. Equality columns first.
  2. The range or sort column last. After a range on column k, columns k+1 onwards only filter inside the region already read; they no longer bound it.
  3. With several ranges, put the one narrowest on real data first.

Cardinality is only a hint about the selectivity (the share of rows a predicate keeps) of an equality; the selectivity of the actual predicate is what you measure. Don't trust Index Cond listing every column: look at Buffers.

Read in post: A PostgreSQL index lab on an airline dataset
Edge caseSeniorA range on the leading column destroys the ordering of the second columnAn index on (bookdate, bookref) does not remove the Sort from WHERE bookdate BETWEEN ... ORDER BY bookref. An index gives you the order of column k+1 only when columns 1..k are all equalities, e.g. (customerid, createdat) for WHERE customerid = ? ORDER BY createdat DESC LIMIT 20. For a range plus a sort on another colu

An index on (book_date, book_ref) does not remove the Sort from WHERE book_date BETWEEN ... ORDER BY book_ref. An index gives you the order of column k+1 only when columns 1..k are all equalities, e.g. (customer_id, created_at) for WHERE customer_id = ? ORDER BY created_at DESC LIMIT 20.

For a range plus a sort on another column, pick: an index for the range plus a sort (cheap for small results, like 881 rows), or an index on the sort column plus filtering (only good with a small LIMIT and a predicate that isn't too rare). Two separate indexes can't be combined to both filter and keep order: a BitmapAnd loses the order.

Read in post: A PostgreSQL index lab on an airline dataset
Trade-offSeniorINCLUDE vs adding the column to the index keyINCLUDE (col) (PostgreSQL 11+, long available in SQL Server): the column lives only in the leaves and takes no part in ordering. It keeps the key's UNIQUE semantics (adding fareconditions to the key would make uniqueness span three columns, which is wrong). Inner levels stay smaller. You can't search or sort by that co
  • INCLUDE (col) (PostgreSQL 11+, long available in SQL Server): the column lives only in the leaves and takes no part in ordering. It keeps the key's UNIQUE semantics (adding fare_conditions to the key would make uniqueness span three columns, which is wrong). Inner levels stay smaller. You can't search or sort by that column.
  • Adding it to the key (a, b, c): serves both filtering and ORDER BY c when a and b are equalities, but changes uniqueness and grows every level.
  • Both make the index bigger and must be updated whenever the column changes (losing HOT updates, the kind of update that doesn't touch indexes, if it changes often). Only cover the hottest queries. InnoDB has no INCLUDE, but the PK is always in every secondary index, so there you add columns to the key.
Read in post: A PostgreSQL index lab on an airline dataset
Edge caseMidPostgreSQL doesn't create indexes for foreign keysREFERENCES bookings only creates the constraint; the automatic index exists only on the referenced side (the PK of bookings). Without an index on tickets.bookref, "tickets of a booking" is a seq scan. Worse, every delete or key change on a bookings row makes PostgreSQL scan tickets to check the constraint. MySQL InnoDB

REFERENCES bookings only creates the constraint; the automatic index exists only on the referenced side (the PK of bookings). Without an index on tickets.book_ref, "tickets of a booking" is a seq scan. Worse, every delete or key change on a bookings row makes PostgreSQL scan tickets to check the constraint.

MySQL InnoDB, on the other hand, creates an index on the FK column if none exists. A good habit: every FK column gets an index, unless the table is tiny or you never join or delete by that column.

Read in post: A PostgreSQL index lab on an airline dataset
Trade-offSeniorEvery extra index is one more write for every INSERTBenefit: one specific read query gets many times faster. Cost: every INSERT, and every UPDATE touching an indexed column, also writes into that tree and generates WAL. Indexes occupy sharedbuffers and push other data out of cache; changing an indexed column rules out a HOT update; VACUUM has more work. How to decide: t
  • Benefit: one specific read query gets many times faster.
  • Cost: every INSERT, and every UPDATE touching an indexed column, also writes into that tree and generates WAL. Indexes occupy shared_buffers and push other data out of cache; changing an indexed column rules out a HOT update; VACUUM has more work.
  • How to decide: tie each index to a query and its frequency; prefer one composite index serving several queries over many single-column ones; periodically drop indexes with idx_scan = 0 (once you're sure they don't enforce uniqueness or serve a rare job). Use CREATE INDEX CONCURRENTLY to add indexes in production without blocking writes.
Read in post: A PostgreSQL index lab on an airline dataset
InterviewJuniorWhy does a query still do a Seq Scan when there's an index?

Usually because it fetches most of the table, so reading sequentially is cheaper.

Other reasons: the predicate can't use the index (column wrapped in a function, an implicit cast, LIKE '%x', a mismatched collation); stale statistics led to a bad estimate; or the table is tiny.

Read in post: A PostgreSQL index lab on an airline dataset
InterviewJuniorHow does a hash index differ from a B-tree?

A hash index only serves equality, and is only slightly cheaper than a B-tree there.

A B-tree serves equality, ranges, ordering, prefix LIKE, uniqueness and multiple columns. Default to B-tree.

Read in post: A PostgreSQL index lab on an airline dataset
InterviewMidHow should you order the columns of a composite index?

Equality columns first, the range or sort column last.

After a range, the remaining columns only filter inside the region already read; they don't bound it. With several ranges, put the narrowest one on real data first. "High cardinality first" isn't the right rule; measure with Buffers.

Read in post: A PostgreSQL index lab on an airline dataset
InterviewMidHow do you make an index serve LIKE 'abc%' and LIKE '%abc' in PostgreSQL?

Prefix: a B-tree with COLLATE "C" or text_pattern_ops. Leading wildcard: a pg_trgm trigram index.

For a prefix, the planner turns LIKE into a range when the index is in byte order (needed when the database uses a linguistic collation). For a leading wildcard, use pg_trgm with GIN or GiST; for suffix-only search, an expression index on reverse(col).

Read in post: A PostgreSQL index lab on an airline dataset
InterviewMidWhat is a covering index, and how is INCLUDE different from adding the column to the key?

A covering index contains every column the query needs, enabling an Index Only Scan.

INCLUDE keeps the column in the leaves only, outside the ordering and without changing uniqueness. Adding it to the key lets you filter and sort on it, but changes uniqueness and makes the tree bigger.

Read in post: A PostgreSQL index lab on an airline dataset
InterviewSeniorDoes an index on (a, b) remove the Sort from WHERE a BETWEEN x AND y ORDER BY b?

No. Across a range of many a values, the output is ordered by a first and only then by b.

The order of b is preserved only when a is an equality. The options: sort a small result, or use an index on b and filter when there's a small LIMIT.

Read in post: A PostgreSQL index lab on an airline dataset
InterviewSeniorHow do you decide to add an index in production?

Tie it to a specific query with numbers, measure the plan before and after, then create it with CREATE INDEX CONCURRENTLY.

  • Get frequency and total time from pg_stat_statements.
  • Check whether an existing index could be extended instead.
  • Measure the plan before and after on production-sized data; estimate the write and storage cost.
  • After creating it, watch idx_scan and write latency.
Read in post: A PostgreSQL index lab on an airline dataset
TILMidA typeMismatch error is a binding error, not a validation errorA @NotNull on role never sees the word BOSS; it only sees an empty field because the binder already rejected the value. The default typeMismatch message is a long exception sentence you don't want users to read. Define your own in messages.properties by error code, for example typeMismatch.form.role=Invalid role.

A @NotNull on role never sees the word BOSS; it only sees an empty field because the binder already rejected the value. The default typeMismatch message is a long exception sentence you don't want users to read. Define your own in messages.properties by error code, for example typeMismatch.form.role=Invalid role.

Read in post: Form binding and validation in Spring MVC
Edge caseMidBinding the entity directly invites mass assignment@ModelAttribute User user followed by userRepository.save(user) lets a client send role=ADMIN, id=1 (overwrite someone else), or passwordHash=.... It falls under OWASP's Broken Access Control (web attacks post). The fix: a separate form DTO per screen, and the controller or service copies each field onto the entity. A

@ModelAttribute User user followed by userRepository.save(user) lets a client send role=ADMIN, id=1 (overwrite someone else), or passwordHash=.... It falls under OWASP's Broken Access Control (web attacks post).

The fix: a separate form DTO per screen, and the controller or service copies each field onto the entity. A few more lines of code, and the entity never receives raw request data.

Read in post: Form binding and validation in Spring MVC
Edge caseSeniorsetAllowedFields doesn't stop constructor bindingA common "patch" is to keep the entity and call binder.setAllowedFields("fullName", "phone"). I tried it on Spring Boot 3.5.9 with an AppUser entity that has exactly one public constructor (email, passwordHash, fullName, role): sending role=ADMIN&passwordHash=x still put both into the object, because Spring 6.1+ passes

A common "patch" is to keep the entity and call binder.setAllowedFields("fullName", "phone"). I tried it on Spring Boot 3.5.9 with an AppUser entity that has exactly one public constructor (email, passwordHash, fullName, role): sending role=ADMIN&passwordHash=x still put both into the object, because Spring 6.1+ passes parameters through the constructor, and the allow-list only filters the setter phase. With a setter-only class, the same configuration blocked role as expected.

Lesson: an allow-list is a secondary defence that silently stops working when someone adds a constructor. A form DTO is the reliable fix.

Read in post: Form binding and validation in Spring MVC
Edge caseJuniorHibernate Validator is not an alternative to Bean ValidationYour code imports jakarta.validation.constraints. (the spec), and at runtime it needs an implementation; Hibernate Validator is the reference one. There's no "pick one": you code against the spec's API and the library runs underneath. spring-boot-starter-validation pulls in the Hibernate Validator version Boot was test

Your code imports jakarta.validation.constraints.* (the spec), and at runtime it needs an implementation; Hibernate Validator is the reference one. There's no "pick one": you code against the spec's API and the library runs underneath.

spring-boot-starter-validation pulls in the Hibernate Validator version Boot was tested with. Pinning a version yourself makes keeping it compatible your job. Only import org.hibernate.validator.constraints.* when you need a Hibernate-specific annotation such as @URL or @Range.

Read in post: Form binding and validation in Spring MVC
Trade-offJuniorValidate in the browser or on the serverBrowser (required, maxlength, type="email", JavaScript): instant feedback, saves a round trip. But anyone can switch it off or send the request with curl. Server (Bean Validation): the only check you can trust, and the only place that can check things needing data (is this email taken?). Do both: the browser for experi
  • Browser (required, maxlength, type="email", JavaScript): instant feedback, saves a round trip. But anyone can switch it off or send the request with curl.
  • Server (Bean Validation): the only check you can trust, and the only place that can check things needing data (is this email taken?).
  • Do both: the browser for experience, the server for correctness. Never only the browser.
Read in post: Form binding and validation in Spring MVC
Edge caseMidA misplaced BindingResult means the handler never runsThe course gets the order right but doesn't say why. I ran a handler declared as (@Valid UserForm form, Model model, BindingResult result): submitting without a full name never called the handler; Spring threw MethodArgumentNotValidException and returned 400. Changing it to (@Valid UserForm form, BindingResult result)

The course gets the order right but doesn't say why. I ran a handler declared as (@Valid UserForm form, Model model, BindingResult result): submitting without a full name never called the handler; Spring threw MethodArgumentNotValidException and returned 400. Changing it to (@Valid UserForm form, BindingResult result) let the handler run and see 2 errors.

The reason: Spring pairs each BindingResult with the model attribute parameter immediately before it. A handler with two form objects (@ModelAttribute a, BindingResult ra, @ModelAttribute b, BindingResult rb) follows the same rule.

Read in post: Form binding and validation in Spring MVC
Edge caseMid@UniqueEmail doesn't replace a unique constraintTwo people sign up with the same email at the same moment: both validators run exists before anyone has inserted, both see "not taken", both rows get saved. The validator only gives a nice message in the normal case. The email column still needs unique = true (the lab has it). Catch DataIntegrityViolationException on s

Two people sign up with the same email at the same moment: both validators run exists before anyone has inserted, both see "not taken", both rows get saved. The validator only gives a nice message in the normal case.

The email column still needs unique = true (the lab has it). Catch DataIntegrityViolationException on save and turn it into a field error: result.rejectValue("email", "duplicate", "Email already used"), then re-render the form. Compare emails case-insensitively in both places (the lab uses existsByEmailIgnoreCase; the database should store the lower()ed email).

Read in post: Form binding and validation in Spring MVC
Trade-offSeniorCheck for a taken email in a validator or in the serviceValidator: the error appears together with the others, and the controller stays short. But validation now hits the database, runs every time the object is validated, and is easy to misuse elsewhere (on an edit form, your own email counts as "taken"). Service: the business rule sits next to the save, is easy to test, an
  • Validator: the error appears together with the others, and the controller stays short. But validation now hits the database, runs every time the object is validated, and is easy to misuse elsewhere (on an edit form, your own email counts as "taken").
  • Service: the business rule sits next to the save, is easy to test, and is shared by forms, REST and batch jobs. The controller has to turn the exception into a field error itself.
  • In practice: format checks as annotations, data-dependent rules in the service, and the unique constraint as the final guard.
Read in post: Form binding and validation in Spring MVC
Edge caseMidsave() with an id from the form is an upsert that wipes columns not on the formSpring Data's save(): an entity without an id is persisted (insert), one with an id is merged (its whole state is copied onto the database row). Bind the entity with a hidden id input and call save(), and every field that isn't on the form (password, created date) becomes null. Change the hidden id and you edit another

Spring Data's save(): an entity without an id is persisted (insert), one with an id is merged (its whole state is copied onto the database row). Bind the entity with a hidden id input and call save(), and every field that isn't on the form (password, created date) becomes null. Change the hidden id and you edit another user.

Do what the lab does: take the id from the path, findById, copy each field from the DTO onto the loaded entity. Inside a @Transactional method, dirty checking writes the changes without calling save().

Read in post: Form binding and validation in Spring MVC
Edge caseJuniorDeleting through a GET linkA link like <a href="/admin/user/delete/5" is a GET with a side effect. Browser prefetching, crawlers, or an <img src=... on a hostile page can all trigger it, and CSRF tokens don't protect GET. State-changing actions use POST (or DELETE via JavaScript), carry a CSRF token, and ask for confirmation in the UI.

A link like <a href="/admin/user/delete/5"> is a GET with a side effect. Browser prefetching, crawlers, or an <img src=...> on a hostile page can all trigger it, and CSRF tokens don't protect GET. State-changing actions use POST (or DELETE via JavaScript), carry a CSRF token, and ask for confirmation in the UI.

Read in post: Form binding and validation in Spring MVC
InterviewJuniorHow do Bean Validation and Hibernate Validator differ?

Bean Validation (Jakarta Validation) is the spec with the annotations and API; Hibernate Validator is its reference implementation.

Your code imports jakarta.validation.*; at runtime Hibernate Validator does the checking. In Spring Boot, spring-boot-starter-validation brings it in with a managed version.

Read in post: Form binding and validation in Spring MVC
InterviewJuniorWhat's the difference between @NotNull, @NotEmpty and @NotBlank?

@NotNull only rejects null; @NotEmpty also rejects empty strings or collections; @NotBlank also rejects whitespace-only strings.

Typed-in text uses @NotBlank. Note that @Size, @Pattern and @Email treat null as valid, so they're usually combined with a "not" constraint.

Read in post: Form binding and validation in Spring MVC
InterviewJuniorWhy redirect after a successful form submission instead of returning a view?

So that F5 doesn't resend the POST (two orders, two users); that's the Post/Redirect/Get pattern.

The "saved" message travels as a flash attribute that lives for one redirect. On validation errors it's the opposite: return the view directly to keep the input and errors.

Read in post: Form binding and validation in Spring MVC
InterviewMidWhat happens if you drop the BindingResult from a handler with @Valid @ModelAttribute?

The handler doesn't run; Spring throws MethodArgumentNotValidException (a kind of BindException) and returns 400 by default.

BindingResult has to come right after the parameter it belongs to. With it, the controller decides: re-render the form with errors. In REST you usually let the exception escape and a @ControllerAdvice turns it into a JSON error.

Read in post: Form binding and validation in Spring MVC
InterviewMidWhat is mass assignment and how do you prevent it in Spring MVC?

It's when the app binds every request parameter onto an object and saves it, so a client can change fields that aren't on the form, like role or id; prevent it with a form DTO holding only the allowed fields.

@InitBinder with setAllowedFields is a secondary layer: in my test it didn't block parameters passed through constructor binding (Spring 6.1+). Copy from DTO to entity in explicit code and check permissions in the service.

Read in post: Form binding and validation in Spring MVC
InterviewMidHow do you write a validator that checks two fields match and shows the error under the right input?

Write a class-level constraint (@Target(TYPE)); in isValid, disable the default violation and build a new one with addPropertyNode("confirmPassword").

Without the property node the error is global and can only be shown at the top of the form. A field-level validator can't do this because it only sees one value.

Read in post: Form binding and validation in Spring MVC
InterviewMidHow do @Valid and @Validated differ?

@Valid is from the spec and validates the object, cascading into nested objects; Spring's @Validated also takes validation groups, and on a class it enables method validation.

Group example: creating a user requires a password, editing doesn't. Many teams avoid groups because they're hard to read, and use two separate DTOs for create and update instead.

Read in post: Form binding and validation in Spring MVC
InterviewSeniorYou already have a validator that checks for duplicate emails. Do you still need a unique constraint?

Yes. The validator reads before it writes, so two concurrent requests both see "not taken" and both insert; only a unique constraint in the database stops that.

Catch DataIntegrityViolationException (or check the constraint name) and turn it into a field error. The validator is still useful for the normal case because its message shows up alongside the other errors. Normalise emails to lower case before comparing in both layers.

Read in post: Form binding and validation in Spring MVC
InterviewSeniorReview this: @PostMapping update(@ModelAttribute User user) { repo.save(user); }. What do you say?

Three problems: mass assignment (the client changes role, id), save is a merge so columns not on the form become null, and there's no validation or permission check.

Fix: a UserForm with @Valid + BindingResult, the id from the path, findById and field-by-field copying inside a @Transactional service, a check that the caller may edit that user, then a redirect with a flash message.

Read in post: Form binding and validation in Spring MVC
Edge caseMidThe people who pay and the people who use expect different thingsIn B2B, the client (a director, procurement) wants reports and control; the users (employees, every day) want fast flows. Five extra mandatory fields for nicer reports can make users hate the product. Ask first: whose problem is this, who measures success, who pays, who lives with the consequences? If you can't answer,

In B2B, the client (a director, procurement) wants reports and control; the users (employees, every day) want fast flows. Five extra mandatory fields for nicer reports can make users hate the product. Ask first: whose problem is this, who measures success, who pays, who lives with the consequences? If you can't answer, the problem isn't defined yet.

Read in post: Problem solving like a senior
Trade-offSeniorAdd capacity, reduce demand or change perceptionAdd capacity (pods, replicas, bigger machines): works immediately, but costs money continuously and only moves the limit. Spread demand (rate limits, queues, staggered batches, caching, TTL jitter): cheap and a great fit for spiky load, at the cost of higher latency or some requests being limited. Change perception (pr
  • Add capacity (pods, replicas, bigger machines): works immediately, but costs money continuously and only moves the limit.
  • Spread demand (rate limits, queues, staggered batches, caching, TTL jitter): cheap and a great fit for spiky load, at the cost of higher latency or some requests being limited.
  • Change perception (progress, 202 Accepted + polling, old data with a timestamp): nearly free, useless if users need the result now.

Ask: is the load high all day or for a few minutes? Do users need the result now, or just to know it's being handled? Usually a mix: spread demand first, change perception for the rest, add capacity once you've measured and the other two aren't enough.

Read in post: Problem solving like a senior
Edge caseMidJumping to a solution before understanding the problemThe tell: the first sentence in the meeting is a technology ("let's use Kafka", "add Redis", "split it into microservices"). The result: you optimise something that isn't the bottleneck, add a system to operate, and the real problem remains. The fix: require a one-sentence problem statement with a number and a stakehol

The tell: the first sentence in the meeting is a technology ("let's use Kafka", "add Redis", "split it into microservices"). The result: you optimise something that isn't the bottleneck, add a system to operate, and the real problem remains.

The fix: require a one-sentence problem statement with a number and a stakeholder before discussing solutions. During incidents, keep "mitigate now" (reflexes, like a rollback) separate from "fix the root cause" (slow, data-driven).

Read in post: Problem solving like a senior
Edge caseMidA technically excellent fix for the wrong problemA solution can be technically excellent and still close no gap for any stakeholder: tuning backend queries when most of the wait is in the frontend; caching an endpoint hardly anyone calls; scaling the database when the culprit is a batch job running at 9 a.m. The fix: measure from the user's point of view first (RUM —

A solution can be technically excellent and still close no gap for any stakeholder: tuning backend queries when most of the wait is in the frontend; caching an endpoint hardly anyone calls; scaling the database when the culprit is a batch job running at 9 a.m.

The fix: measure from the user's point of view first (RUM — real user monitoring, measured in real users' browsers — and end-to-end traces), find where the time actually goes, and write the number that means "done" into the problem statement.

Read in post: Problem solving like a senior
Edge caseSenior5 Whys that stop at "human error"Ending with "because developer A forgot to check" means you haven't reached the root. Keep asking: why did the system let someone forget without anyone noticing — missing tests, a DB constraint, a review checklist item, an alert? A good root cause is fixable at the system or process level, so the next person can't make

Ending with "because developer A forgot to check" means you haven't reached the root. Keep asking: why did the system let someone forget without anyone noticing — missing tests, a DB constraint, a review checklist item, an alert? A good root cause is fixable at the system or process level, so the next person can't make the same mistake. Incidents usually have several causal branches, so pair 5 Whys with a causal diagram.

Read in post: Problem solving like a senior
TILThe two "Einstein" quotes in the slides are almost certainly not Einstein's"If I had an hour to solve a problem, I'd spend 55 minutes thinking about the problem and 5 minutes on the solution" and "Insanity is doing the same thing over and over and expecting different results" are routinely attributed to Einstein, but there's no reliable source for either in his writings or letters. The ideas

"If I had an hour to solve a problem, I'd spend 55 minutes thinking about the problem and 5 minutes on the solution" and "Insanity is doing the same thing over and over and expecting different results" are routinely attributed to Einstein, but there's no reliable source for either in his writings or letters. The ideas still hold. The side lesson: check the source before you quote it, even on a slide about critical thinking.

Read in post: Problem solving like a senior
InterviewJuniorHow do you define a "problem" before solving it?

A problem is the gap between the reality a stakeholder perceives and the reality they expect.

So before solving it I need to know whose problem it is, what the current reality measures, and what the expectation is. The definition also gives three ways to close the gap: change reality, change perception, or adjust the expectation.

Read in post: Problem solving like a senior
InterviewJuniorWhat is 5 Whys and when do you use it?

Asking "why?" repeatedly (around five times, not a strict number) to get from a symptom to a root cause, or from a surface request to the real goal.

I use it in postmortems, when analysing bugs, and when a request arrives as a solution ("add Redis") to find the goal behind it ("home page under one second"). Stop at a cause fixable at the system level, not at "human error".

Read in post: Problem solving like a senior
InterviewMidThe system is overloaded every morning at 9. How do you approach it?

Measure first to find where the time goes, then try the cheap fixes (spread demand, change perception) before adding capacity.

Measure: which endpoints, where the time goes (database, pool, CPU, external services), whether any job runs at the same time. Three families of fixes: reduce or spread demand (move batches, cache, rate-limit, queue), change perception (progress, 202 Accepted), add capacity (indexes, scheduled autoscaling). One change at a time, comparing numbers before and after. It's the elevator problem: widening the clock-in window is far cheaper than installing another elevator.

Read in post: Problem solving like a senior
InterviewMidWhat does a causal diagram add to 5 Whys?

5 Whys follows a single line, so it misses things when one effect has several causes; a causal diagram is a tree that shows every branch.

Each node is the result of its children, joined with AND or OR, so you can see where a branch can be cut. For example, "users are frustrated" = long waits AND nothing to do while waiting; cutting either branch is enough to reduce frustration. The leaves become a list of candidate solutions whose costs you can compare.

Read in post: Problem solving like a senior
InterviewMidYour manager asks you to "add Redis to the system". How do you respond?

Treat it as an option, not the problem: find the real goal and measure the bottleneck first.

Ask: what's slow, how it's measured, what the target is, how stale the data may be. Measure to find the bottleneck (a missing index? N+1 queries? an external service?). If caching really is a good option, still list the consequences (invalidation, operating Redis, what happens when it's down). Answer top-down: "I propose X to reach goal Y; Redis is one option, but first we need to measure Z."

Read in post: Problem solving like a senior
InterviewMidWhen reviewing a design that uses a message queue, what do you check?

I go through order, duplication, relationship, direction and consistency, then retries, a DLQ and lag monitoring.

Order: is it needed, and within what scope (per key or partition)? Duplication: delivery is at-least-once, so consumers must be idempotent. Relationship: who owns the data, and does the event carry enough of it? Direction: who depends on whom, any cycles? Consistency: which parts are async, how much lag is acceptable, and is publishing inside the transaction (outbox)? Plus retries, a dead-letter queue and lag monitoring.

Read in post: Problem solving like a senior
InterviewSeniorHow do you present a technical proposal to a non-technical audience?

Top-down, following the pyramid principle: the conclusion first, then two or three reasons with numbers, then cost and risk.

For example: "I propose moving the reporting batch to 2 a.m. Why: it uses 60% of the IOPS at 9 a.m., exactly when users complain. Cost: reports are up to 7 hours older, and accounting has agreed." To talk like that you have to understand the problem precisely and cut the noise, so it's a test for yourself too.

Read in post: Problem solving like a senior
InterviewSeniorDuring an incident, how do you move fast without "jumping to solutions"?

Separate two phases: mitigate with reflexes now, fix the root cause with slow thinking once things are stable.

Mitigation: roll back the latest deploy, switch off a feature flag, shift traffic, scale temporarily; cheap and reversible. Root cause: gather data, draw a causal diagram, run 5 Whys, then write a blameless postmortem. The trap is doing it the other way round: hunting for the root cause while users are still failing, or stopping at the temporary patch and never doing the slow part.

Read in post: Problem solving like a senior
Edge caseSeniorThe Reactor pattern is not the Actor modelThe slide is titled "Reactor pattern (Actor model)". They're two different things: Reactor: an I/O handling pattern. An event loop waits for readiness events on many connections and dispatches handlers. The unit is a connection and an I/O event. Actor model: a concurrency programming model. Each actor has private state

The slide is titled "Reactor pattern (Actor model)". They're two different things:

  • Reactor: an I/O handling pattern. An event loop waits for readiness events on many connections and dispatches handlers. The unit is a connection and an I/O event.
  • Actor model: a concurrency programming model. Each actor has private state and a mailbox, communicates only by sending messages, and processes one message at a time (Akka, Erlang). The unit is an actor and a business message.

An actor system can run on top of a reactor, but calling them the same is wrong. Mixing them up in an interview invites a follow-up challenge.

Read in post: Communication in system design, part 1
TILMidHTTP/2 server push is practically deadThe slide lists server push as a benefit. In reality Chrome removed it in version 106 (2022), because few sites used it well and it often pushed unneeded data. When the server needs to send data on its own, use something else: Server-Sent Events, WebSocket, or gRPC server streaming. For static assets, browsers use 103

The slide lists server push as a benefit. In reality Chrome removed it in version 106 (2022), because few sites used it well and it often pushed unneeded data. When the server needs to send data on its own, use something else: Server-Sent Events, WebSocket, or gRPC server streaming. For static assets, browsers use 103 Early Hints instead of push.

Read in post: Communication in system design, part 1
Trade-offSeniorgRPC is faster, but the price is paid in operationsgRPC wins on latency and CPU for frequent calls with small messages, and on streaming. The price: You can't curl it by hand; you need grpcurl with reflection enabled. Errors have only about 16 status codes (UNAVAILABLE, DEADLINEEXCEEDED...), so business errors need careful mapping. Older load balancers, API gateways an

gRPC wins on latency and CPU for frequent calls with small messages, and on streaming. The price:

  • You can't curl it by hand; you need grpcurl with reflection enabled.
  • Errors have only about 16 status codes (UNAVAILABLE, DEADLINE_EXCEEDED...), so business errors need careful mapping.
  • Older load balancers, API gateways and WAFs may not speak HTTP/2 to the backend.
  • The team must get used to code generation and schema compatibility checks.

My rule: REST at the edge and for most internal services; gRPC for a few hot call paths (tens of thousands of RPS) or when streaming is needed.

Read in post: Communication in system design, part 1
Edge caseSeniorgRPC on Kubernetes piles everything onto one podA Kubernetes ClusterIP Service balances at layer 4, i.e. per connection. gRPC keeps one long-lived HTTP/2 connection and multiplexes every request over it. Result: each client pod sticks to one server pod; scale the server to 10 pods and the new ones sit idle. How L4 and L7 differ, and how LB or NAT idle timeouts cut l

A Kubernetes ClusterIP Service balances at layer 4, i.e. per connection. gRPC keeps one long-lived HTTP/2 connection and multiplexes every request over it. Result: each client pod sticks to one server pod; scale the server to 10 pods and the new ones sit idle. How L4 and L7 differ, and how LB or NAT idle timeouts cut long-lived connections, is in Networking for backend engineers.

Fixes:

  • Client-side balancing: use a headless Service (clusterIP: None) so DNS returns every pod's IP, and configure the gRPC client with the round_robin policy.
  • An L7 load balancer or service mesh (Envoy, Linkerd, Istio) balances per HTTP/2 request.
  • Cap connection age on the server (MAX_CONNECTION_AGE) so clients reconnect periodically and spread out.

The slide says gRPC is "Kubernetes-friendly with built-in client load balancing". It is built in, but you have to enable it; by default it's off.

Read in post: Communication in system design, part 1
InterviewJuniorHow do JSON and Protobuf differ?

JSON is text, human-readable, with no required schema; Protobuf is binary, smaller and faster, but needs a schema file and code generation.

JSON suits public APIs and debugging; Protobuf suits high-load internal services and Kafka messages.

Read in post: Communication in system design, part 1
InterviewJuniorWhat does HTTP/2 improve over HTTP/1.1?

Multiplexing many requests over one TCP connection, header compression, and binary framing instead of text.

It removes head-of-line blocking at the HTTP layer but not at the TCP layer; HTTP/3 over QUIC solves the rest.

Read in post: Communication in system design, part 1
InterviewMidWhen would you choose gRPC over REST?

For internal service-to-service calls with high load and small messages, when streaming is needed, or when several languages need a strict contract.

For public APIs, browsers and partners, REST is still better because anyone can call it and the tooling is everywhere.

Read in post: Communication in system design, part 1
InterviewMidHow do you add a field to a Protobuf message without breaking old clients?

Add the field with a new, never-used number; old clients skip unknown fields. Don't change the number or type of existing fields.

When removing a field, mark its number and name reserved. Put buf breaking or a schema registry in CI to block breaking changes.

Read in post: Communication in system design, part 1
InterviewMidHow does the Reactor pattern work?

One or a few event loops use epoll to watch many connections; when one is ready they call its handler, and heavy work goes to a worker pool.

The main reactor accepts connections, sub reactors handle reads and writes, workers decode, compute and encode. The golden rule: never block the event loop.

Read in post: Communication in system design, part 1
InterviewSeniorYou scaled a gRPC service from 3 to 10 pods, but the 7 new pods get almost no requests. Why?

A Kubernetes Service balances per connection, and gRPC clients hold one long-lived HTTP/2 connection, so every request still goes to the old pods.

Fix it with a headless Service plus a round_robin client, an L7 proxy or service mesh, or MAX_CONNECTION_AGE so clients reconnect periodically.

Read in post: Communication in system design, part 1
InterviewSeniorA request passes through 4 services called synchronously. How do you design the timeouts?

Set one time budget for the whole request and propagate the deadline to each hop, which uses whatever is left, instead of each service having its own fixed timeout.

gRPC has deadline propagation built in; with REST you pass it in a header yourself. Retry at one layer only and only for idempotent operations, so call counts don't multiply level by level.

Read in post: Communication in system design, part 1
Edge caseMidThe slide's comparison misses two important pointsKafka has exactly-once. The idempotent producer (on by default since Kafka 3.0) prevents duplicates on retry; transactions let you read, process, write and commit offsets as one unit. But only within Kafka: writing to a database or calling an external API still needs an idempotent consumer. RabbitMQ can keep messages n
  • Kafka has exactly-once. The idempotent producer (on by default since Kafka 3.0) prevents duplicates on retry; transactions let you read, process, write and commit offsets as one unit. But only within Kafka: writing to a database or calling an external API still needs an idempotent consumer.
  • RabbitMQ can keep messages now too. RabbitMQ Streams (since 3.9) is an append-only, replayable log like Kafka. Quorum queues replace mirrored queues for durability.

The slide's throughput figures (Kafka ~10M, RabbitMQ ~500K messages/second) are orders of magnitude for a whole cluster under favourable conditions, not per-node numbers.

Read in post: Communication in system design, part 2
Trade-offMidSSE or WebSocketSSE: plain HTTP, passes through proxies, CDNs and load balancers easily; the browser reconnects on its own and sends Last-Event-ID to resume where it stopped. One-way and text only. Over HTTP/2, many SSE streams share one connection. WebSocket: two-way, binary, tiny per-message overhead. But you handle reconnects, hear
  • SSE: plain HTTP, passes through proxies, CDNs and load balancers easily; the browser reconnects on its own and sends Last-Event-ID to resume where it stopped. One-way and text only. Over HTTP/2, many SSE streams share one connection.
  • WebSocket: two-way, binary, tiny per-message overhead. But you handle reconnects, heartbeats and authentication yourself, and some proxies cut idle connections.

If the client only receives (notifications, stock prices, job progress), choose SSE. If the client also sends continuously (chat, games), choose WebSocket.

Read in post: Communication in system design, part 2
TILMidMQTT's three QoS levels and two often-forgotten featuresQoS 0: sent once, may be lost (at-most-once). QoS 1: resent until acknowledged, may duplicate (at-least-once). QoS 2: a four-step handshake, exactly once, the slowest. Retained message: the broker keeps a topic's last message, so a new subscriber immediately gets the current state. Last will: the broker publishes a mes
  • QoS 0: sent once, may be lost (at-most-once).
  • QoS 1: resent until acknowledged, may duplicate (at-least-once).
  • QoS 2: a four-step handshake, exactly once, the slowest.

Retained message: the broker keeps a topic's last message, so a new subscriber immediately gets the current state. Last will: the broker publishes a message on its own when a client disconnects abnormally, used to report a device going offline.

Read in post: Communication in system design, part 2
Edge caseMidQUIC doesn't "resend lost TCP packets"The slide lists QUIC's reliability benefit as "resending lost TCP packets". QUIC doesn't use TCP. It numbers its own packets, detects loss itself and resends the affected stream's data in new QUIC packets, right on top of UDP. Because retransmission is handled per stream, one lost packet only slows that stream, unlike

The slide lists QUIC's reliability benefit as "resending lost TCP packets". QUIC doesn't use TCP. It numbers its own packets, detects loss itself and resends the affected stream's data in new QUIC packets, right on top of UDP. Because retransmission is handled per stream, one lost packet only slows that stream, unlike TCP, which makes everything behind it wait.

Read in post: Communication in system design, part 2
Trade-offSeniorWhen the Risk API fails or times out: allow or blockFail-open (allow): customers aren't affected and revenue holds, but fraudsters can exploit exactly the moment scoring is down. Fail-closed (block): perfectly safe, but every legitimate transaction is refused too, losing revenue and trust. A common balance is conditional fail-open. On timeout, the Payment service applie
  • Fail-open (allow): customers aren't affected and revenue holds, but fraudsters can exploit exactly the moment scoring is down.
  • Fail-closed (block): perfectly safe, but every legitimate transaction is refused too, losing revenue and trust.

A common balance is conditional fail-open. On timeout, the Payment service applies a minimal fallback rule set that runs inside it (amount limits, a local deny list): small transactions go through, large ones go to REVIEW or require extra authentication (OTP, 3-D Secure). And every transaction allowed this way is rescored asynchronously afterwards.

Read in post: Communication in system design, part 2
InterviewJuniorHow do polling, long polling and WebSocket differ?

Polling asks periodically; long polling asks and the server holds the request until there's data; WebSocket opens a two-way channel that stays ready.

Polling is simple but wasteful and slow; WebSocket is the fastest but stateful and harder to scale.

Read in post: Communication in system design, part 2
InterviewJuniorWhen do you use SSE instead of WebSocket?

When you only need one-way pushes from server to client, such as notifications or price updates.

SSE is plain HTTP so it passes through proxies easily, and the browser reconnects on its own and resumes from Last-Event-ID.

Read in post: Communication in system design, part 2
InterviewMidKafka or RabbitMQ for an order processing system?

Kafka if you need high throughput, many consumers reading the same events, and replay; RabbitMQ if you need complex routing, delays, TTL or priorities at the queue level.

For orders, the "order created" event is consumed by several services and may need reprocessing, so Kafka usually fits better. A "send an email after 30 minutes" task is neater with RabbitMQ delays.

Read in post: Communication in system design, part 2
InterviewMidDoes Kafka have exactly-once?

Yes, within Kafka: the idempotent producer prevents duplicate writes, and transactions bundle reading, writing and committing offsets into one unit.

Outside Kafka (writing to a database, calling an API) it's still at-least-once, so consumers must be idempotent, for example with a processed-messages table and a unique key.

Read in post: Communication in system design, part 2
InterviewMidHow do you push an order book to hundreds of thousands of viewers?

Send a snapshot with a sequence number once, then only diffs with increasing sequence numbers, conflate updates roughly every 100 ms, and broadcast through pub/sub.

On a sequence gap the client reloads the snapshot. Conflation cuts bandwidth by tens of times without viewers noticing.

Read in post: Communication in system design, part 2
InterviewSeniorWhat do you worry about when scaling WebSocket to a million connections?

Memory and file descriptors per node, the load balancer's idle timeout, routing messages to the node holding each user, and reconnect storms when a node dies.

Separate a gateway layer that only holds connections, keep a user → gateway map in Redis, use heartbeats, jittered client backoff, and drain connections before deploying.

Read in post: Communication in system design, part 2
InterviewSeniorThe fraud scoring system times out. Should the Payment service allow or block?

Conditional fail-open: apply a minimal fallback rule set inside the Payment service, allow small transactions, require extra authentication or review for large ones, and rescore everything asynchronously.

Blocking everything loses revenue every time scoring has an incident; allowing everything lets fraudsters strike exactly then. Track how often fail-open triggers as a key metric.

Read in post: Communication in system design, part 2
InterviewSeniorWhy not compute all fraud features in the stream processor?

Because the stream lags by hundreds of milliseconds to seconds, while fraudsters fire transactions very close together; the few most important counters must be incremented during scoring.

The rest (complex features, long windows) is fine to compute in the stream, since it's off the payment path.

Read in post: Communication in system design, part 2
Edge caseJuniororder is an SQL keyword, so the Order entity needs another table nameAn entity named Order makes Hibernate create a table order, and select ... from order fails with a syntax error because ORDER is a keyword (ORDER BY). Fix: @Table(name = "orders"). The lab names the class ShopOrder to avoid clashing with Spring Data's Sort.Order. Don't turn on global identifier quoting just for one tab

An entity named Order makes Hibernate create a table order, and select ... from order fails with a syntax error because ORDER is a keyword (ORDER BY). Fix: @Table(name = "orders"). The lab names the class ShopOrder to avoid clashing with Spring Data's Sort.Order. Don't turn on global identifier quoting just for one table.

Read in post: Cart and checkout with Spring
Edge caseJuniorAdding the same product twice creates two linesIn the beginner version every click on "Add" creates a new detail row, so the cart ends up with two lines for the same laptop. The right fix lives in the aggregate (Cart.add adds to the existing line), plus a unique (cartid, productid) so the database rejects any code path that sneaks around it. The test addingSameProd

In the beginner version every click on "Add" creates a new detail row, so the cart ends up with two lines for the same laptop. The right fix lives in the aggregate (Cart.add adds to the existing line), plus a unique (cart_id, product_id) so the database rejects any code path that sneaks around it. The test addingSameProductTwiceIncrementsQuantity adds 1, then 2, and checks there is exactly one line with quantity 3.

Read in post: Cart and checkout with Spring
Edge caseMidStoring a total-quantity column on the cart and updating it by handThe beginner version keeps a sum column on cart, does +1 on add and -1 on delete, and also copies it into the session. That's three copies of one number. One code path that forgets to update it (adding quantity 2, deleting a line with quantity 3, placing an order) and they drift apart. Compute totalQuantity() from the

The beginner version keeps a sum column on cart, does +1 on add and -1 on delete, and also copies it into the session. That's three copies of one number. One code path that forgets to update it (adding quantity 2, deleting a line with quantity 3, placing an order) and they drift apart. Compute totalQuantity() from the lines when needed; for a few dozen lines the cost is negligible. If you really need a cached total, update it in the same transaction and the same method as the line change.

Read in post: Cart and checkout with Spring
Trade-offMidShopping cart in the session or in the databaseSession: no table, guests can use it. But it's gone when the session expires, invisible on another phone, it makes the session bigger (every request reads it, see part 5), and you can't analyse abandoned carts. Database: durable, synced across devices, enables "you left something in your cart" emails. But every action
  • Session: no table, guests can use it. But it's gone when the session expires, invisible on another phone, it makes the session bigger (every request reads it, see part 5), and you can't analyse abandoned carts.
  • Database: durable, synced across devices, enables "you left something in your cart" emails. But every action is a database write, and you need to clean up stale carts.
  • Combined: keep the guest cart in the session or in a table keyed by an anonymous cookie. On login, merge each line into the database cart with the same Cart.add (adding quantities on duplicates), then drop the temporary cart.
Read in post: Cart and checkout with Spring
Edge caseJuniorCalculating money with doubledouble stores binary fractions, so 0.1 + 0.2 is 0.30000000000000004. With whole-dong prices the error hides for a while, then shows up with percentage discounts, tax or foreign currencies. Use BigDecimal built from a string or valueOf, compare with compareTo (not equals, which treats 2.0 and 2.00 as different), and a D

double stores binary fractions, so 0.1 + 0.2 is 0.30000000000000004. With whole-dong prices the error hides for a while, then shows up with percentage discounts, tax or foreign currencies. Use BigDecimal built from a string or valueOf, compare with compareTo (not equals, which treats 2.0 and 2.00 as different), and a DECIMAL(precision, scale) column. Details in the post on BigDecimal and String.

Read in post: Cart and checkout with Spring
Trade-offSeniorDecrementing stock: conditional UPDATE, optimistic or pessimistic lockConditional UPDATE (used in the lab): one SQL statement, no prior read, no retry. Fits when the rule fits in a WHERE clause (enough stock left). Optimistic (@Version): read, check in Java, write with the version; retry on conflict. Fits complex rules with little contention. Hot products keep retrying. Pessimistic (SELE
  • Conditional UPDATE (used in the lab): one SQL statement, no prior read, no retry. Fits when the rule fits in a WHERE clause (enough stock left).
  • Optimistic (@Version): read, check in Java, write with the version; retry on conflict. Fits complex rules with little contention. Hot products keep retrying.
  • Pessimistic (SELECT ... FOR UPDATE): lock the row from the read. Easy to reason about but holds locks longer, and deadlocks when one order locks several products in different orders (lock by ascending product_id).
  • Measured on a booking problem in optimistic and pessimistic locking; time-limited holds (keep stock for 15 minutes during online payment) in holding seats concurrently.
Read in post: Cart and checkout with Spring
Edge caseSeniorclearAutomatically wipes out changes to entities loaded earlierIn the lab's first run, the stock query was declared @Modifying(clearAutomatically = true, flushAutomatically = true). The order test reported the cart still held 3 items after checkout. Cause: clearAutomatically calls EntityManager.clear() after the UPDATE, which detaches every managed entity, including the Cart loade

In the lab's first run, the stock query was declared @Modifying(clearAutomatically = true, flushAutomatically = true). The order test reported the cart still held 3 items after checkout. Cause: clearAutomatically calls EntityManager.clear() after the UPDATE, which detaches every managed entity, including the Cart loaded at the start of the method. The later cart.clear() modifies an object nobody tracks any more, so no DELETE runs and no error is raised.

Fix: drop clearAutomatically and keep only flushAutomatically (flush pending changes before the bulk statement). The trade-off is that the Product entities in the context keep the old stock; here only name and price are used, so it's fine. If you need the new stock, call entityManager.refresh(product). More on bulk updates with @Modifying in JPA part 2.

Read in post: Cart and checkout with Spring
TILMidA unique constraint is the last safety net"Is there already an order with this requestId?" followed by an insert is check-then-act: two parallel requests can both see "no". The unique (userid, requestid) makes the second insert fail with DataIntegrityViolationException instead of creating a duplicate. Catch it in the controller and read back the existing order

"Is there already an order with this requestId?" followed by an insert is check-then-act: two parallel requests can both see "no". The unique (user_id, request_id) makes the second insert fail with DataIntegrityViolationException instead of creating a duplicate. Catch it in the controller and read back the existing order. Likewise, the unique (cart_id, product_id) blocks duplicate lines when two tabs add the same product.

Read in post: Cart and checkout with Spring
Edge caseSeniorPaginating orders while fetching a collectionAdd @EntityGraph(attributePaths = "lines") to a query that takes a Pageable and the SQL can no longer use LIMIT (one order becomes several joined rows). Hibernate 6 warns HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory: it loads every matching order into memory and slices the pag

Add @EntityGraph(attributePaths = "lines") to a query that takes a Pageable and the SQL can no longer use LIMIT (one order becomes several joined rows). Hibernate 6 warns HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory: it loads every matching order into memory and slices the page there. The admin page works on test data, then falls over at a hundred thousand orders. Instead: paginate over orders without lines (the admin table needs only total and status), or fetch a page of ids first and load lines with where order_id in (...). Pagination in depth in part 8.

Read in post: Cart and checkout with Spring
InterviewJuniorWhy must an order line store the product's price and name instead of just product_id?

Because an order is a record of one moment: later changes to a product's price or name must not change orders already placed.

With only product_id, an admin raising the price tomorrow would "raise" the total of every old order, breaking invoices and reconciliation. Keep product_id for analytics, but name and unit price are copies.

Read in post: Cart and checkout with Spring
InterviewJuniorWhat goes wrong if you name an entity Order?

The table order collides with the SQL keyword ORDER, so select ... from order is a syntax error.

Fix it with @Table(name = "orders"). Don't enable global quoting for one table.

Read in post: Cart and checkout with Spring
InterviewMidA customer clicks "Place order" twice. How do you make sure only one order is created?

Give the form an idempotency key (a requestId generated when checkout opens), check it inside the order transaction, and add a unique constraint on (user_id, request_id) as a safety net.

Disabling the button in JavaScript only lowers the odds (slow network, retries, two tabs). The second request finds the existing order and returns it. If both run in parallel, the loser hits the unique constraint; catch it and read the order back.

Read in post: Cart and checkout with Spring
InterviewMidWhy not store the number of items in the cart as its own column?

Because it's derived from the lines; storing it separately means keeping it in sync on every code path, and sooner or later it drifts.

Computing it on demand is fast enough for a few dozen lines. If you really need a cached column, update it in the same transaction as the line change, in a single method of the aggregate.

Read in post: Cart and checkout with Spring
InterviewMidWould you keep the cart in HttpSession or in the database?

The database for logged-in users (durable, works across devices); the session or an anonymous cookie for guests, merged into the database cart on login.

The session should hold ids, not JPA entities: entities get detached, lazy loading breaks, and they must be serializable when Spring Session stores them in Redis or JDBC.

Read in post: Cart and checkout with Spring
InterviewSeniorTwo people buy the last unit at the same time. How does your design avoid overselling?

Decrement stock with UPDATE product SET stock = stock - :q WHERE id = :id AND stock >= :q inside the order transaction; zero rows updated means throw and roll back the whole order.

The database locks the row during the update, so the two statements run one after the other on that row and the second sees stock = 0 and changes nothing. Reading stock in Java and calling save is a lost update. When the rule doesn't fit a WHERE clause, use @Version with retry, or FOR UPDATE with locks taken in id order. A test with two threads released together proves it.

Read in post: Cart and checkout with Spring
InterviewSeniorA @Transactional method runs a bulk update and then modifies an entity it loaded earlier, but the change is never saved. Why?

The bulk update is declared @Modifying(clearAutomatically = true): it clears the persistence context, the loaded entity becomes detached, and dirty checking no longer sees its changes.

There's no exception, just no SQL. Fix: drop clearAutomatically (keep flushAutomatically so earlier changes are flushed before the bulk statement), reload the entity after the bulk statement, or run the bulk update last. Write tests that check database state after the method, not just its return value.

Read in post: Cart and checkout with Spring
InterviewSeniorThe admin order list is paginated and must show each order's line count. How do you write the query?

Paginate over orders without fetching the collection, then get the line counts with one aggregate group by order_id query for that page's ids (or a count subquery in a projection).

A fetch join or entity graph on a collection combined with Pageable makes Hibernate load the whole result into memory and slice it there (warning HHH90003004). For one user's history, unpaginated or small, a single-query entity graph is fine.

Read in post: Cart and checkout with Spring
Edge caseMidA system call is not a hardware interruptThe course slides say "a system call generates an interrupt". That was only true for old 32-bit Linux, which used int 0x80 (a software interrupt). On x86-64, glibc uses the dedicated syscall instruction: the CPU jumps straight to the kernel's entry point without going through the interrupt table. The precise word is a

The course slides say "a system call generates an interrupt". That was only true for old 32-bit Linux, which used int 0x80 (a software interrupt). On x86-64, glibc uses the dedicated syscall instruction: the CPU jumps straight to the kernel's entry point without going through the interrupt table.

The precise word is a trap (a mode switch the program asks for), as opposed to an interrupt sent by hardware (a NIC with a packet, a timer ending a time slice). It matters when you read metrics: the in column of vmstat counts hardware interrupts, not system calls.

Read in post: Operating systems for backend engineers
TILSeniorSystem.nanoTime() usually never enters the kernelclockgettime is called so often that Linux puts it in the vDSO: a page of kernel code mapped into every process that reads the time from shared memory without switching to kernel mode. That's why System.nanoTime() costs about 20 ns on Linux. The exception: on some VMs the clocksource doesn't support the vDSO and every

clock_gettime is called so often that Linux puts it in the vDSO: a page of kernel code mapped into every process that reads the time from shared memory without switching to kernel mode. That's why System.nanoTime() costs about 20 ns on Linux.

The exception: on some VMs the clocksource doesn't support the vDSO and every clock read becomes a real syscall. Code that reads the clock in tight loops (logging, metrics) can get noticeably slower.

Read in post: Operating systems for backend engineers
Trade-offMidMonolithic, microkernel and hybrid kernelsMonolithic (Linux): parts call each other with plain function calls, so it's fast; one buggy driver can take the whole machine down. Loadable modules (modprobe) let you load drivers at runtime, but they still run in kernel mode. Microkernel (QNX, seL4, MINIX): a minimal kernel, with drivers and file systems running in
  • Monolithic (Linux): parts call each other with plain function calls, so it's fast; one buggy driver can take the whole machine down. Loadable modules (modprobe) let you load drivers at runtime, but they still run in kernel mode.
  • Microkernel (QNX, seL4, MINIX): a minimal kernel, with drivers and file systems running in user space. A crashed driver can be restarted; the price is extra IPC and mode switches, so it's slower.
  • Hybrid (Windows NT, macOS XNU): microkernel-style structure, but many services moved back into kernel mode for speed.

What it means for backend work: the network stack and file systems live in the kernel, so optimizing I/O means crossing the user/kernel boundary less often (batching, zero-copy, epoll), which is what part 3 is about.

Read in post: Operating systems for backend engineers
TILMidTo the Linux kernel, a thread is just another taskLinux has no separate structure for threads: processes and threads are both taskstruct and are scheduled the same way. A thread is created with clone() and flags like CLONEVM | CLONEFILES | ..., so it shares the page table and file descriptor table. Each thread has its own TID under /proc/<pid/task/. That's why top -H

Linux has no separate structure for threads: processes and threads are both task_struct and are scheduled the same way. A thread is created with clone() and flags like CLONE_VM | CLONE_FILES | ..., so it shares the page table and file descriptor table. Each thread has its own TID under /proc/<pid>/task/.

That's why top -H -p <pid> lists individual Java threads with their %CPU. The TID in hex matches nid=0x... in a jstack thread dump: that's how you find the thread that's burning CPU.

Read in post: Operating systems for backend engineers
Edge caseMidunable to create native thread is not a heap problemThis error means pthreadcreate failed. Raising -Xmx won't help; it can even make things worse because a bigger heap leaves less room for native memory. Causes: hitting ulimit -u, the cgroup's pids.max (the pod PID limit), kernel.threads-max, or running out of virtual memory for stacks. The root cause is almost always u

This error means pthread_create failed. Raising -Xmx won't help; it can even make things worse because a bigger heap leaves less room for native memory. Causes: hitting ulimit -u, the cgroup's pids.max (the pod PID limit), kernel.threads-max, or running out of virtual memory for stacks.

The root cause is almost always unbounded thread creation: new Thread() per request, newCachedThreadPool() under a traffic spike, every client library creating its own pool. Count threads with ls /proc/<pid>/task | wc -l, then consolidate into a few bounded pools or use virtual threads for I/O waits.

Read in post: Operating systems for backend engineers
Trade-offMidSequential versus time-sliced on few coresTrue for pure CPU work, measured by total time and average completion time: slicing doesn't reduce the work, it only adds context switches and cold caches. In exercise 2 (16 tasks on 1 CPU), the totals are nearly equal, but interleaving makes the first task finish after ~450 ms instead of ~50 ms, and the average after

True for pure CPU work, measured by total time and average completion time: slicing doesn't reduce the work, it only adds context switches and cold caches. In exercise 2 (16 tasks on 1 CPU), the totals are nearly equal, but interleaving makes the first task finish after ~450 ms instead of ~50 ms, and the average after ~800 ms instead of ~440 ms.

False in two places that matter for backends:

  • Tasks that wait on I/O: while A waits for the database the CPU is idle, so letting B run is a clear win.
  • Latency and fairness: one 2-second request run to completion blocks every 5 ms request behind it.

Rule of thumb: size CPU-bound pools to the core count, give I/O-bound work more threads (or virtual threads), and never let the two share a pool.

Read in post: Operating systems for backend engineers
Edge caseSeniorCPU throttling raises p99 even when average usage looks lowThe dashboard says the pod uses 40% of its CPU limit, yet p99 occasionally jumps by 50–100 ms. Usage is averaged per minute, while the quota is enforced per 100 ms period: a parallel GC cycle or a JIT burst together with a wave of requests can burn the quota in a few ms. Check nrthrottled and throttledusec in /sys/fs/c

The dashboard says the pod uses 40% of its CPU limit, yet p99 occasionally jumps by 50–100 ms. Usage is averaged per minute, while the quota is enforced per 100 ms period: a parallel GC cycle or a JIT burst together with a wave of requests can burn the quota in a few ms.

Check nr_throttled and throttled_usec in /sys/fs/cgroup/cpu.stat (cgroup v2), or the container_cpu_cfs_throttled_periods_total metric. Exercise 2 was throttled in 13 of 24 periods. Fixes: fewer threads running in parallel to match the limit, a higher limit, or requests without limits for latency-sensitive services.

Read in post: Operating systems for backend engineers
Edge caseMidA shell-form ENTRYPOINT keeps SIGTERM away from JavaWith ENTRYPOINT java -jar app.jar (shell form) or ["sh", "-c", "java ..."], PID 1 is sh and Java is its child. sh doesn't forward signals, so Spring never shuts down gracefully; after the grace period the pod gets SIGKILL (137) and in-flight requests are cut off. Fix: use the exec form ["java", "-jar", "app.jar"], or e

With ENTRYPOINT java -jar app.jar (shell form) or ["sh", "-c", "java ..."], PID 1 is sh and Java is its child. sh doesn't forward signals, so Spring never shuts down gracefully; after the grace period the pod gets SIGKILL (137) and in-flight requests are cut off.

Fix: use the exec form ["java", "-jar", "app.jar"], or exec java $JAVA_OPTS -jar app.jar so Java replaces the shell as PID 1. If you need a real init (reaping zombies, forwarding signals), use tini or docker run --init.

Read in post: Operating systems for backend engineers
InterviewJuniorWhat's the difference between a process and a thread?

A process has its own address space and is isolated from other processes; a thread runs inside a process and shares memory with its other threads.

A thread shares the heap, code and open files, but has its own stack and registers. Threads are cheaper to create and switch, but shared memory needs synchronization, and one thread corrupting shared state can bring down the whole process.

Read in post: Operating systems for backend engineers
InterviewJuniorWhat is a system call? Give a Java example.

It's how a user-mode application asks the kernel to do privileged work: read, write, socket, connect, mmap, clone.

In Java, FileInputStream.read, Socket.connect and new Thread().start() all end up as system calls through the JVM and glibc. Each call switches into kernel mode and back, so calling too often (unbuffered byte-by-byte reads) is slow.

Read in post: Operating systems for backend engineers
InterviewJuniorWhat's the difference between concurrency and parallelism?

Concurrency means several tasks make progress over the same period, possibly just by taking turns on one core; parallelism means several tasks run at the same instant on several cores.

A server handling 1,000 requests on 4 cores is concurrent (1,000 requests in flight) and parallel (at most 4 running at once).

Read in post: Operating systems for backend engineers
InterviewMidWhat does a context switch cost, and why is switching threads cheaper than switching processes?

About 1–5 µs directly, with a usually bigger indirect cost from cold caches and TLB; threads of one process share a page table, so the TLB stays useful.

The direct part is entering the kernel, running the scheduler, and saving and loading registers. Two processes need a page table switch. Measure with the cs column of vmstat and pidstat -w (voluntary/involuntary per thread).

Read in post: Operating systems for backend engineers
InterviewMidDoes a load average of 30 on an 8-core machine mean we're out of CPU?

Not necessarily: on Linux the load average counts tasks waiting for a CPU and D tasks in uninterruptible I/O.

High idle plus high wa points to a disk or NFS bottleneck. Only when CPU is near 100% and the r column of vmstat is well above the core count are you short on CPU. Check iostat -x and count D tasks too.

Read in post: Operating systems for backend engineers
InterviewMidHow do Java threads map to OS threads, and how are virtual threads different?

Platform threads are 1 with OS threads; virtual threads are M on a few carrier threads.

A platform thread has a native stack (1 MB virtual by default), is scheduled by the kernel, costs tens of µs to create, and is limited by the OS and the cgroup. When a virtual thread waits on I/O, the JVM unmounts it and parks its stack on the heap, so the kernel does no context switch. Great for I/O-heavy work, no help for CPU-bound work.

Read in post: Operating systems for backend engineers
InterviewMidWhy can unable to create native thread happen with free heap?

Because the OS refused to create a native thread; the heap isn't involved.

Causes: ulimit -u, the cgroup's pids.max, kernel.threads-max, or no virtual memory left for stacks. The root cause is usually unbounded thread creation. Count threads via /proc/<pid>/task or a thread dump, then use bounded pools or virtual threads; raising -Xmx doesn't help.

Read in post: Operating systems for backend engineers
InterviewSeniorA pod uses 40% of its CPU limit but p99 spikes in bursts. How do you investigate?

Suspect CPU throttling: the limit is a quota per 100 ms period, while usage is averaged per minute.

Parallel GC, the JIT and big pools can burn the quota in the first few ms of a period. Check nr_throttled and throttled_usec in cpu.stat or container_cpu_cfs_throttled_periods_total, and line them up with the GC log. Fixes: fewer parallel threads to match the limit (ParallelGCThreads, ActiveProcessorCount, pool sizes), a higher limit, or requests without limits for latency-sensitive services.

Read in post: Operating systems for backend engineers
InterviewSeniorHow do you size a thread pool, given what you know about the scheduler?

Separate the kinds of work: CPU-bound pools at about availableProcessors, I/O-bound pools larger in proportion to wait/compute time, then measure and adjust.

  • CPU-bound: about availableProcessors (which already reflects the CPU limit); more threads only add context switches.
  • I/O-bound: roughly cores × (1 + wait time / compute time), capped by downstream resources (connection pools, partner rate limits); or virtual threads with a semaphore.
  • Measure: high nvcswch/s and a long run queue mean too many threads; low CPU with high latency means too few or a downstream bottleneck.
Read in post: Operating systems for backend engineers
InterviewSeniorEvery deploy produces a few 502s and the log has no graceful shutdown line. Why?

Java isn't receiving SIGTERM, usually because a shell-form ENTRYPOINT makes sh PID 1 and it doesn't forward signals; the pod is SIGKILLed after the grace period (exit 137).

Fix it with the exec form, exec java ... or tini. Add server.shutdown=graceful, a Spring timeout shorter than terminationGracePeriodSeconds, and a short preStop sleep, because endpoint removal runs in parallel with SIGTERM.

Read in post: Operating systems for backend engineers
Edge caseSeniorReading and removing with two separate commands can lose or duplicate alertsBetween ZRANGE and ZREM, the device may send a heartbeat (new score). Removing by member name then deletes the new timer and a live device is "forgotten". Two scan jobs running in parallel alert the same device twice. The fix: wrap read and remove in one Lua script (same key, so same slot) that only removes members who

Between ZRANGE and ZREM, the device may send a heartbeat (new score). Removing by member name then deletes the new timer and a live device is "forgotten". Two scan jobs running in parallel alert the same device twice.

The fix: wrap read and remove in one Lua script (same key, so same slot) that only removes members whose score is still ≤ now, and run only one scanner per key (leader election, or one owner per key).

Read in post: A liveness system
Trade-offSeniorRedis sorted set or an in-memory timing wheelPick the ZSET when load is moderate and you want something simple and durable. Pick the timing wheel when heartbeat load is huge and you accept owning partitioning and recovery. At 333K/second I'd pick the timing wheel and spread devices over N instances by hash(deviceid).
Redis ZSET Timing wheel in the service
Timer reset O(log n) + a network round trip O(1) in RAM, ~100 ns
Finding expired O(log n + m) scan one bucket
Precision milliseconds one tick (say 1 second)
Survives restart yes (AOF/RDB, replicas) no, must be rebuilt
Spreading load by key, Redis Cluster your job: route each device to the right instance

Pick the ZSET when load is moderate and you want something simple and durable. Pick the timing wheel when heartbeat load is huge and you accept owning partitioning and recovery. At 333K/second I'd pick the timing wheel and spread devices over N instances by hash(device_id).

Read in post: A liveness system
TILMidTiming wheels ship with Netty and KafkaNetty has HashedWheelTimer (one wheel, counting rounds), used for idle timeouts across millions of connections. Kafka uses hierarchical timing wheels for its "purgatory", where waiting requests (for example a produce with acks=all waiting on replicas) are held until they complete or expire. Both trade precision (one ti

Netty has HashedWheelTimer (one wheel, counting rounds), used for idle timeouts across millions of connections. Kafka uses hierarchical timing wheels for its "purgatory", where waiting requests (for example a produce with acks=all waiting on replicas) are held until they complete or expire. Both trade precision (one tick) for O(1) cost.

Read in post: A liveness system
Edge caseSeniorA timing wheel lives in RAM: a restart loses every timerWhen the service restarts, the wheel is empty. Do nothing and any device that died just before the restart will never be reported. Recovery: persist each device's lastseen somewhere durable (Redis, Cassandra) in batches; on startup, load it back and set a timer at lastseen + timeout. Devices already past due are report

When the service restarts, the wheel is empty. Do nothing and any device that died just before the restart will never be reported.

Recovery: persist each device's last_seen somewhere durable (Redis, Cassandra) in batches; on startup, load it back and set a timer at last_seen + timeout. Devices already past due are reported immediately. When adding or removing instances, use consistent hashing so only a fraction of devices move.

Read in post: A liveness system
Trade-offSeniorDisruptor or BlockingQueue for the liveness problemThe Disruptor is tens of times faster, but: fixed size (a power of 2), a busy-spin wait strategy burns a whole core, the programming model is less familiar, and it only works inside one JVM. For liveness alerts, the I/O of sending an alert (a few ms) dwarfs the queue cost by thousands of times. A bounded ArrayBlockingQ

The Disruptor is tens of times faster, but: fixed size (a power of 2), a busy-spin wait strategy burns a whole core, the programming model is less familiar, and it only works inside one JVM.

For liveness alerts, the I/O of sending an alert (a few ms) dwarfs the queue cost by thousands of times. A bounded ArrayBlockingQueue plus a ThreadPoolExecutor is usually enough. The Disruptor pays off when the queue itself is the bottleneck: matching engines, log pipelines, in-memory event processing at millions per second.

Read in post: A liveness system
Edge caseSeniorA new instance takes over a group of devices and fires a wave of false alarmsDuring a rebalance, the new instance loads lastseen from storage. If the batch writing lastseen is a few seconds behind, many devices look overdue and get falsely reported. The fix: give each instance a "grace period" of one timeout after it takes over devices; only report devices that stay silent through that window.

During a rebalance, the new instance loads last_seen from storage. If the batch writing last_seen is a few seconds behind, many devices look overdue and get falsely reported.

The fix: give each instance a "grace period" of one timeout after it takes over devices; only report devices that stay silent through that window.

Read in post: A liveness system
InterviewMidDesign the simplest possible disconnected-device detector with Redis.

One ZSET per device type, member = device_id, score = expiry time; a heartbeat is a ZADD that overwrites it, and a job every second fetches and removes members with score ≤ now in one Lua script.

ZADD is O(log n); fetching expired is O(log n + m). Cap how many you take per scan so you don't block Redis, and shard the keys once load exceeds one node.

Read in post: A liveness system
InterviewMidWhy not use Redis key TTLs and keyspace notifications to detect expiry?

Because Redis expires keys lazily and by random sampling, so the expired event can arrive noticeably late, and notifications are fire-and-forget pub/sub: a disconnected subscriber loses events.

If you need guarantees, use a structure you can scan (a ZSET) or timers inside your own service.

Read in post: A liveness system
InterviewMidWhat is a timing wheel, and why does a timer reset cost only O(1)?

A circular array of buckets, each holding the timers that expire at that tick; a reset looks up the old timer in a map, unlinks it from its bucket and links it into bucket (cursor + timeout) mod size.

Each tick scans only one bucket. The price is that precision is rounded to one tick.

Read in post: A liveness system
InterviewSeniorA timing wheel doesn't suit long timers. How do you handle them?

Use hierarchical timing wheels: several wheels with different ticks (seconds, minutes, hours); far-off timers sit on a coarse wheel and move down to finer ones as they get close.

Kafka does this for its purgatory. The alternative is counting remaining rounds on one wheel, but every pass of the hand then walks timers that aren't due.

Read in post: A liveness system
InterviewSeniorIs 333K heartbeats per second into a Redis ZSET okay?

Not on one node; you'd have to shard the keys by hash(device_id), and every heartbeat still costs a network round trip.

At this load, an in-memory timing wheel inside the service itself (devices routed by hash) is much cheaper; you just add batched last_seen persistence for recovery.

Read in post: A liveness system
InterviewSeniorWhy is the LMAX Disruptor faster than ArrayBlockingQueue?

No locks (CAS and memory barriers), a pre-allocated ring buffer so almost no garbage, each side keeps its own sequence so nobody fights over a size field, and consumers read in batches.

Add padding against false sharing and a contiguous, cache-friendly array. The price: fixed size, busy-spinning burns CPU, and it only works inside one JVM.

Read in post: A liveness system
InterviewSenior100K devices expire in the same tick. How does your system react?

The scanner only collects timers and pushes them to a bounded queue; a worker pool sends alerts, batched and grouped by region; when the queue is full the scanner waits (backpressure) instead of blowing up memory.

A big simultaneous wave is usually an infrastructure incident (power or signal loss), so collapse it into one regional alert rather than 100K messages.

Read in post: A liveness system
InterviewSeniorThe service holding the timing wheel restarts. How do you avoid missing dead devices?

Persist each device's last_seen to durable storage in batches, reload it on startup and set timers at last_seen + timeout, with a grace period to avoid false alarms from slightly stale data.

Route devices with consistent hashing so that adding or removing an instance only moves a fraction of them.

Read in post: A liveness system
Edge caseSeniorDeduplicating on message_id misses duplicates where the producer created a new messageA (consumergroup, messageid) key only protects against the same message being delivered again. If the producer retries at the application level (catching an exception and calling send again, or an outbox republishing a message that went out but wasn't marked yet) and generates a fresh UUID each time, the consumer sees

A (consumer_group, message_id) key only protects against the same message being delivered again. If the producer retries at the application level (catching an exception and calling send again, or an outbox republishing a message that went out but wasn't marked yet) and generates a fresh UUID each time, the consumer sees two different messages and processes both. Use a stable business key where one exists (transaction_id, order_id + event_type), or generate message_id once and store it with the outbox row so a republish reuses the same id.

Read in post: Idempotency part 2
Trade-offSeniorSide effects outside the database in a consumer: accept duplicates or route through the DBSending an email, a push notification or calling a partner API can't join the database transaction with the dedupe table. A crash right after sending but before committing still sends again. Accept at-least-once: fine for effects that are harmless when repeated (a "your order shipped" email arriving twice). Cheap, no e

Sending an email, a push notification or calling a partner API can't join the database transaction with the dedupe table. A crash right after sending but before committing still sends again.

  • Accept at-least-once: fine for effects that are harmless when repeated (a "your order shipped" email arriving twice). Cheap, no extra infrastructure.
  • Write a "to-do" row to the database in the same transaction as the dedupe row; a separate worker performs it, marks it done, and calls the external party with that task's own idempotency key. Right for anything involving money or that must not repeat (calling a refund API). The cost: an extra table, a worker and some latency.
  • Ask before acting (if the external party has a lookup API): check "already sent/refunded?" before each call. One extra request, and still a small gap without an idempotency key.
Read in post: Idempotency part 2
Edge caseSeniorSetting acks=1 silently turns the idempotent producer offIdempotence has been on by default since Kafka 3.0, but setting acks=1 (or retries=0, or max.in.flight 5) without setting enable.idempotence makes the producer quietly turn it off. Explicitly setting enable.idempotence=true together with acks=1, on the other hand, fails at startup with a ConfigException. So always spel

Idempotence has been on by default since Kafka 3.0, but setting acks=1 (or retries=0, or max.in.flight > 5) without setting enable.idempotence makes the producer quietly turn it off. Explicitly setting enable.idempotence=true together with acks=1, on the other hand, fails at startup with a ConfigException. So always spell out enable.idempotence=true and acks=all for important data, so conflicts surface immediately.

Read in post: Idempotency part 2
TILSeniorThe 5 in max.in.flight comes from the broker remembering only the last 5 batchesFor each (producer ID, partition), the broker keeps metadata for the last 5 batches so it can recognise a resent one. That's why an idempotent producer allows at most 5 unacknowledged requests per connection: a retry of any of them is still recognised, and a batch with an out-of-order sequence is rejected rather than w

For each (producer ID, partition), the broker keeps metadata for the last 5 batches so it can recognise a resent one. That's why an idempotent producer allows at most 5 unacknowledged requests per connection: a retry of any of them is still recognised, and a batch with an out-of-order sequence is rejected rather than written in the wrong order. Before idempotence existed (older Kafka), keeping order across retries meant setting max.in.flight=1 and paying for it in throughput.

Read in post: Idempotency part 2
Trade-offSeniorTrust the IPN, the return URL, or ask the gateway yourselfReturn URL: fastest, but travels through the browser, can be edited and may never arrive. Display only. IPN: server-to-server, signed, retried; the primary source of truth. It can be late, duplicated, or lost entirely if your endpoint is down for long. Active query (the transaction-query API): the most certain, used fo
  • Return URL: fastest, but travels through the browser, can be edited and may never arrive. Display only.
  • IPN: server-to-server, signed, retried; the primary source of truth. It can be late, duplicated, or lost entirely if your endpoint is down for long.
  • Active query (the transaction-query API): the most certain, used for reconciliation and overdue IPNs. Costs requests and is rate-limited, so it doesn't replace the IPN for every order. A sound design uses all three: the IPN updates the status, the return URL triggers the frontend to ask the backend, and the reconciliation job patches the orders that slipped through.
Read in post: Idempotency part 2
InterviewJuniorWhy not update the payment status from the return URL?

Because the return URL travels through the browser: its parameters can be edited, and it may never arrive.

If the user closes the tab before the redirect, it never comes. Use it only for display and to make the frontend ask the backend for the real status. The status is updated from the signed server-to-server IPN, plus a reconciliation job.

Read in post: Idempotency part 2
InterviewMidHow do you build an idempotent Kafka consumer?

In one database transaction: insert a "processed" marker with ON CONFLICT DO NOTHING, and only if it was inserted, write the business change; commit the offset after the transaction commits.

The key is (consumer_group, message_id or a business id) in a processed_message table. A redelivered message hits the key and is skipped. Handle ordering with a version or event_time, and purge the dedupe table after retention plus the replay window.

Read in post: Idempotency part 2
InterviewMidHow long should a processed_message table be kept?

Longer than the period during which a message can be redelivered: the topic's retention plus your largest replay window.

The replay window is when you reset offsets during an incident. Anything shorter and a replay reprocesses old messages. Purge in batches or partition the table by day so deletes are cheap; if you deduplicate on a business key stored in the data table itself, there's nothing to purge.

Read in post: Idempotency part 2
InterviewSeniorHow does Kafka's idempotent producer work, and what are its limits?

The broker remembers recent sequences per (PID, partition), drops duplicate batches and rejects out-of-order ones. It only covers the client's own internal retries, within one producer session.

  • The producer has a PID and epoch, and each batch to a partition carries a sequence number.
  • It needs acks=all, retries > 0, max.in.flight ≤ 5. On by default since Kafka 3.0, but silently disabled if you set acks=1 without spelling out enable.idempotence.
  • Limits: a restart gets a new PID (you need a transactional.id), it doesn't stop the application calling send twice, and it says nothing about consumers.
Read in post: Idempotency part 2
InterviewSeniorHow would you design a payment gateway IPN handler?

Verify the signature, find the order, compare the amount, and only then update through a state-machine conditional update. If the order is already final, reply "already confirmed" so the gateway stops resending.

  • Only transition out of PENDING_PAYMENT; write the transaction and ledger entries in the same transaction; keep a unique constraint on the gateway's transaction number.
  • The return URL is display-only.
  • A reconciliation job queries the gateway for overdue pending orders, marks them EXPIRED and releases held resources.
Read in post: Idempotency part 2
InterviewSeniorKafka has exactly-once, so why must consumers still be idempotent?

Because Kafka's exactly-once only covers the read-from-Kafka → process → write-to-Kafka loop; database writes, API calls and emails fall outside that transaction.

Exactly-once (idempotent producer, transactions, read_committed) commits offsets and output in the same Kafka transaction. A crash between the PostgreSQL write and the offset commit still reprocesses the message. Side effects outside Kafka still need deduplication in the database, in the same transaction as the business change.

Read in post: Idempotency part 2
TILSeniorKafka's exactly-once only holds inside KafkaKafka's exactly-once (idempotent producer + transactions + consumers with isolation.level=readcommitted) only covers the read from Kafka, process, write back to Kafka loop (exactly what Kafka Streams uses). Writing to PostgreSQL, calling a payment API or sending an email is a side effect outside Kafka's transaction. A

Kafka's exactly-once (idempotent producer + transactions + consumers with isolation.level=read_committed) only covers the read from Kafka, process, write back to Kafka loop (exactly what Kafka Streams uses). Writing to PostgreSQL, calling a payment API or sending an email is a side effect outside Kafka's transaction. A crash between the database write and the offset commit still means reprocessing, so the consumer has to be idempotent on its own.

Read in post: Idempotency part 1
Edge caseMidMySQL's INSERT IGNORE swallows far more than duplicate keysINSERT IGNORE downgrades every ignorable error to a warning, not just duplicate keys, even in strict mode. Over-long strings get truncated, wrongly typed values become defaults, foreign-key violations are silently skipped: you think you're deduplicating while you're writing corrupted data. Use INSERT ... ON DUPLICATE K

INSERT IGNORE downgrades every ignorable error to a warning, not just duplicate keys, even in strict mode. Over-long strings get truncated, wrongly typed values become defaults, foreign-key violations are silently skipped: you think you're deduplicating while you're writing corrupted data.

Use INSERT ... ON DUPLICATE KEY UPDATE id = id (a no-op) or catch error 1062 explicitly. PostgreSQL's ON CONFLICT (column) DO NOTHING only ignores conflicts on the constraint you name.

Read in post: Idempotency part 1
Trade-offSeniorWhich idempotency technique to pickMoney systems usually combine them: an idempotency key at the API, a state machine for the transaction status, and a unique constraint on ledger entries.
Technique Strength Cost / limit
Conditional update / state machine cheapest, no extra table, correct for any state transition doesn't work for creates or increments
Unique constraint on a business key ((user_id, request_id), (order_id, payment_attempt)) blocks duplicates in the database even in parallel one index; needs a client-supplied or natural key
Separate dedupe store (idempotency keys, processed messages) most general, can store the response to replay it a table, an index, a cleanup job; must share the transaction
Dedupe in Redis fast, built-in TTL not transactional with the database: an early filter only, never the source of truth

Money systems usually combine them: an idempotency key at the API, a state machine for the transaction status, and a unique constraint on ledger entries.

Read in post: Idempotency part 1
Edge caseMidStoring the response in a jsonb column makes replays not quite identicalIn my first run I stored responsebody as jsonb, and the 20 requests came back as two "different responses": {"paymentid":1} from the first request and {"paymentid": 1} from the replays. jsonb stores a parsed form, and PostgreSQL re-formats it on the way out (adds whitespace, reorders keys, drops duplicate keys). A clie

In my first run I stored response_body as jsonb, and the 20 requests came back as two "different responses": {"payment_id":1} from the first request and {"payment_id": 1} from the replays. jsonb stores a parsed form, and PostgreSQL re-formats it on the way out (adds whitespace, reorders keys, drops duplicate keys).

A client that compares strings or verifies a signature over the body will notice. Store the response as text/bytea (along with important headers such as Location) if replays must be byte-for-byte identical.

Read in post: Idempotency part 1
TILSeniorPostgreSQL makes a second INSERT wait while an uncommitted transaction holds the unique keyTransaction A has inserted key k1 but not committed; transaction B running INSERT ... ON CONFLICT DO NOTHING with the same key does not return immediately, it waits for A. If A commits, B gets "0 rows" (already exists); if A rolls back, B's insert succeeds. I measured B waiting the full ~2 seconds A stayed open. That's

Transaction A has inserted key k1 but not committed; transaction B running INSERT ... ON CONFLICT DO NOTHING with the same key does not return immediately, it waits for A. If A commits, B gets "0 rows" (already exists); if A rolls back, B's insert succeeds. I measured B waiting the full ~2 seconds A stayed open.

That's why "claim the key in the same transaction as the business logic" handles concurrent duplicates without a separate lock. The flip side: a duplicate holds a connection while it waits, so keep the transaction short. InnoDB waits the same way (it takes a lock on the duplicate record).

Read in post: Idempotency part 1
Trade-offSeniorClaiming the key in one transaction vs a two-phase IN_PROGRESS then COMPLETEDOne transaction (the approach above): key, business change and response commit together. Simple, and you never get orphaned keys. Only valid when the whole operation lives in one database and runs quickly. Two phases: commit the key as INPROGRESS (a short transaction), call the external system (payment gateway, another
  • One transaction (the approach above): key, business change and response commit together. Simple, and you never get orphaned keys. Only valid when the whole operation lives in one database and runs quickly.
  • Two phases: commit the key as IN_PROGRESS (a short transaction), call the external system (payment gateway, another service), then commit COMPLETED + response. Required whenever there's an outbound call, because you can't hold a database transaction open while waiting seconds for HTTP. Duplicates arriving meanwhile get 409.
  • The cost of two phases: handle keys stuck in IN_PROGRESS when the process dies mid-way (store locked_until, allow a takeover after it expires). The outbound call must itself be idempotent (pass the same key down to the gateway) so the rerun doesn't charge twice.
Read in post: Idempotency part 1
Edge caseMidStoring a request_id without a UNIQUE constraint deduplicates nothingA requestid NOT NULL column without a unique index is decoration. Checking in code (existsByRequestId, then insert) isn't enough either: two concurrent requests both see "not there yet" and both insert. Only a database constraint can referee every parallel request. Scope it to the caller ((userid, requestid)). If the t

A request_id NOT NULL column without a unique index is decoration. Checking in code (existsByRequestId, then insert) isn't enough either: two concurrent requests both see "not there yet" and both insert. Only a database constraint can referee every parallel request.

Scope it to the caller ((user_id, request_id)). If the table already holds duplicates, clean them up first; PostgreSQL can build the unique index CONCURRENTLY and then attach it as a constraint, avoiding a long table lock.

Read in post: Idempotency part 1
Edge caseSeniorA lock prevents concurrent runs, not repeated runsA retry that arrives after the first attempt finished and released the lock will acquire it and debit a second time. Two more holes: The lock's TTL can expire while the first attempt is still running (a GC pause, a slow database), letting the second run in parallel. A blind DEL with the constant value "1" lets one clie

A retry that arrives after the first attempt finished and released the lock will acquire it and debit a second time. Two more holes:

  • The lock's TTL can expire while the first attempt is still running (a GC pause, a slow database), letting the second run in parallel.
  • A blind DEL with the constant value "1" lets one client delete another client's lock. You need a random token plus compare-and-delete in Lua.

Idempotency needs a durable record (a unique constraint, a dedupe table); the lock is just an optimisation to reduce contention. If you still need a lock on a shared resource, use a fencing token (an increasing number the database checks to reject a stale lock holder), or a database lock (SELECT ... FOR UPDATE, advisory locks, see transactions and locking).

Read in post: Idempotency part 1
InterviewJuniorWhat is idempotency and why do distributed systems need it?

An idempotent operation reaches the same final state whether it runs once or many times; distributed systems need it so retries are safe.

A sender can't distinguish "the request was lost" from "the response was lost", so it has to retry, and retries make every channel at-least-once. An idempotent receiver makes those retries harmless.

Read in post: Idempotency part 1
InterviewJuniorWhy isn't checking "does it exist yet?" in code before inserting enough to prevent duplicates?

Because it's a check-then-act race: two concurrent requests both see "not there" and both insert.

Only a unique constraint in the database sees every parallel request and can stop the second row.

Read in post: Idempotency part 1
InterviewMidWhat's the difference between at-most-once, at-least-once and exactly-once?

At-most-once can lose, at-least-once can duplicate, and exactly-once is really at-least-once plus receiver-side deduplication.

At-most-once: no retries. At-least-once: retry until acknowledged. Exactly-once delivery isn't achievable over an unreliable network; what you can build is exactly-once processing (idempotent consumers, unique constraints, a dedupe store).

Read in post: Idempotency part 1
InterviewMidCan a distributed lock replace idempotency?

No. A lock only prevents two runs at the same time; a retry that arrives after the first attempt released the lock still runs again.

The lock can also expire before the first attempt finishes. Idempotency needs a durable record that the work was done (a unique constraint, a dedupe table); a lock is only an optimisation to reduce contention.

Read in post: Idempotency part 1
InterviewSeniorWhen do you claim the idempotency key in one transaction, and when do you use two phases?

One transaction when the whole operation lives in one database and is short; two phases when there's an external call.

  • One transaction: key, change and response commit together, and concurrent duplicates simply wait on the unique index.
  • Two phases (commit IN_PROGRESS, call out, commit COMPLETED): because you can't keep a transaction open while waiting on HTTP. Handle stuck keys with an expiring lease, return 409 to in-flight duplicates, and pass the key down so the external call is itself idempotent.
Read in post: Idempotency part 1
InterviewSeniorBug report: a user is told "this place is already booked" right after successfully booking it. How do you investigate?

I'd suspect a retry of a request that had already succeeded: the second attempt ran the whole flow and found the nights BOOKED by attempt 1.

Check the logs by request_id for two requests a few seconds apart, and check whether the table has a unique constraint on request_id. Fix: unique (user_id, request_id), claim it before locking availability, and return the existing booking to the repeat.

Read in post: Idempotency part 1
Trade-offMidB+tree or B-tree for a database indexB-tree (data in every node): a lookup can occasionally stop early, but the fan-out is small, so the tree is taller, and range scans have to move up and down the tree. B+tree (data only in leaves, leaves linked): fan-out in the thousands, so 20 million rows fit in 3 levels; range scans and ORDER BY just walk the leaves;
  • B-tree (data in every node): a lookup can occasionally stop early, but the fan-out is small, so the tree is taller, and range scans have to move up and down the tree.
  • B+tree (data only in leaves, leaves linked): fan-out in the thousands, so 20 million rows fit in 3 levels; range scans and ORDER BY just walk the leaves; every lookup costs exactly the tree height, which makes it predictable.
  • Databases choose the B+tree because OLTP queries are mostly equality, range and sort over data bigger than RAM, where every tree level may be a disk read.
Read in post: Inside an index
Edge caseMidInnoDB doesn't let you pick any column as the clustered indexThe slides say "the clustered index defaults to the PK, but you can choose other columns". That's true for SQL Server (CREATE CLUSTERED INDEX on any column) and false for InnoDB, where the order is fixed: (1) the primary key; (2) without a PK, the first unique index whose columns are all NOT NULL; (3) failing that, a h

The slides say "the clustered index defaults to the PK, but you can choose other columns". That's true for SQL Server (CREATE CLUSTERED INDEX on any column) and false for InnoDB, where the order is fixed: (1) the primary key; (2) without a PK, the first unique index whose columns are all NOT NULL; (3) failing that, a hidden 6-byte DB_ROW_ID (GEN_CLUST_INDEX).

Verified on MySQL 8.4: a table with only UNIQUE (code) and code NOT NULL shows exactly one index, uq_code, in mysql.innodb_index_stats, because it has become the clustered index. To change the clustering column, change the PK.

Read in post: Inside an index
Trade-offSeniorSecondary indexes pointing at the PK (InnoDB) or at a physical location (PostgreSQL)InnoDB, leaves hold the PK: moving a row never touches secondary indexes; updating non-indexed columns touches no index. The cost: reading through a secondary index is two tree walks, and a fat PK (16-byte UUID, composite key) bloats every secondary index. PostgreSQL, leaves hold a TID: one tree walk per read, and all
  • InnoDB, leaves hold the PK: moving a row never touches secondary indexes; updating non-indexed columns touches no index. The cost: reading through a secondary index is two tree walks, and a fat PK (16-byte UUID, composite key) bloats every secondary index.
  • PostgreSQL, leaves hold a TID: one tree walk per read, and all indexes are equal. The cost: every non-HOT update adds an entry to every index, which means write amplification (one logical write causing many physical writes), bloat and more WAL.
  • In 2016 Uber moved a large system from PostgreSQL to MySQL, mainly over write amplification on heavily indexed, constantly updated tables, plus the physical replication of that era. The lesson isn't "MySQL is better"; the storage model has to fit the workload. On PostgreSQL, keep update-heavy tables lightly indexed, avoid indexing columns that change often, and lower the fillfactor.
Read in post: Inside an index
Edge caseMidA unique constraint on a nullable column doesn't stop duplicates the way you thinkUNIQUE (tenantid, externalref) with a nullable externalref allows any number of (1, NULL) rows on MySQL and PostgreSQL. If the business rule is "at most one record without a reference per tenant": declare the column NOT NULL with a meaningful default, or use NULLS NOT DISTINCT (PostgreSQL 15+), or use a partial unique

UNIQUE (tenant_id, external_ref) with a nullable external_ref allows any number of (1, NULL) rows on MySQL and PostgreSQL. If the business rule is "at most one record without a reference per tenant":

  • declare the column NOT NULL with a meaningful default, or
  • use NULLS NOT DISTINCT (PostgreSQL 15+), or
  • use a partial unique index ON t (tenant_id) WHERE external_ref IS NULL.

When you do want many NULLs (unverified emails), say so in a comment so the next person doesn't "fix" it.

Read in post: Inside an index
Edge caseSeniorA UUIDv4 primary key causes page splits, index bloat and double the WALRandom keys leave pages 50–70% full: the InnoDB clustered index is 80 MB vs 41 MB with BIGINT AUTOINCREMENT. PostgreSQL writes 60 MB of WAL for 200,000 inserts vs 30 MB with UUIDv7, because the first change to each page after a checkpoint writes the whole page to WAL, and with scattered keys every page is a "first chan

Random keys leave pages 50–70% full: the InnoDB clustered index is 80 MB vs 41 MB with BIGINT AUTO_INCREMENT. PostgreSQL writes 60 MB of WAL for 200,000 inserts vs 30 MB with UUIDv7, because the first change to each page after a checkpoint writes the whole page to WAL, and with scattered keys every page is a "first change". Once the index outgrows RAM, every insert also costs a random read.

If IDs must be generated client-side, use UUIDv7 (or ULID), stored as uuid/BINARY(16), never varchar(36).

Read in post: Inside an index
Trade-offSeniorIncreasing bigint, UUIDv4, UUIDv7/ULID or Snowflakebigint identity: smallest, sequential inserts. Downsides: you need the database to get an ID, and it leaks volume and is guessable (/orders/1001 → try 1002). UUIDv4: generated anywhere, unguessable, but page splits as in the lab. UUIDv7/ULID: 48 bits of time up front, so nearly increasing, and still generated anywhere
  • bigint identity: smallest, sequential inserts. Downsides: you need the database to get an ID, and it leaks volume and is guessable (/orders/1001 → try 1002).
  • UUIDv4: generated anywhere, unguessable, but page splits as in the lab.
  • UUIDv7/ULID: 48 bits of time up front, so nearly increasing, and still generated anywhere (UUIDv7 is RFC 9562). Downsides: 16 bytes, leaks creation time. PostgreSQL 18 has uuidv7(); JDK 21 doesn't.
  • Snowflake (64 bits: time + machine id + counter): a bigint that's generated in a distributed way, but you must hand out unique machine ids and you depend on the clock.
  • Sensible default for one service on one database: bigint PK, plus a unique UUIDv7 column if you need a public ID. IDs generated in many places: UUIDv7 as the PK.
Read in post: Inside an index
Edge caseSeniorA second column in key_len or Index Cond doesn't mean it narrows the scanWith an index on (a, b) and WHERE a = 97 AND b = 2, MySQL reports keylen = 8 and PostgreSQL prints Index Cond: ((a = 97) AND (b = 2)), matching the "(a, b)" answer. In reality b only positions the starting point (97, 2). Every entry with a larger a is still read, and b is just filtered inside the index (Index Condition

With an index on (a, b) and WHERE a >= 97 AND b = 2, MySQL reports key_len = 8 and PostgreSQL prints Index Cond: ((a >= 97) AND (b = 2)), matching the "(a, b)" answer. In reality b only positions the starting point (97, 2). Every entry with a larger a is still read, and b is just filtered inside the index (Index Condition Pushdown: filtering on the index entry before fetching the row).

On 1 million rows: MySQL estimates 62,908 entries scanned and PostgreSQL's Bitmap Index Scan reads 38 index buffers. Rewritten as a IN (97, 98, 99) AND b = 2 it's 30 entries and 9 buffers. Look at the scanned range in EXPLAIN FORMAT=TREE or the buffers in EXPLAIN (ANALYZE, BUFFERS).

Read in post: Inside an index
Edge caseMidA B+tree never gets unbalanced; bloat is what you should watchSplits and merges keep every leaf at the same depth, so "the index got unbalanced" is the wrong diagnosis. What degrades is page density, measured with pgstatindex() (the pgstattuple extension). After deleting 90% of the rows, VACUUM only reclaims completely empty pages, so the 1-million-row PK index stays at 21 MB wit

Splits and merges keep every leaf at the same depth, so "the index got unbalanced" is the wrong diagnosis. What degrades is page density, measured with pgstatindex() (the pgstattuple extension). After deleting 90% of the rows, VACUUM only reclaims completely empty pages, so the 1-million-row PK index stays at 21 MB with 9% leaf density; REINDEX INDEX CONCURRENTLY brings it to 2.2 MB.

Rebuild when you measure persistently low density, not on a calendar. MySQL: OPTIMIZE TABLE (a full InnoDB table rebuild). If bloat keeps coming back from deleting old data, fix the root cause with partitioning and dropping partitions.

Read in post: Inside an index
Edge caseSeniorA failed CREATE INDEX CONCURRENTLY leaves an INVALID index behindIf CREATE UNIQUE INDEX CONCURRENTLY hits duplicates or gets cancelled, the index still exists with pgindex.indisvalid = false (verified: the error says could not create unique index, yet pgindex still lists accemail | f). An INVALID index is never used for reads but is still maintained on writes. After every failure: D

If CREATE UNIQUE INDEX CONCURRENTLY hits duplicates or gets cancelled, the index still exists with pg_index.indisvalid = false (verified: the error says could not create unique index, yet pg_index still lists acc_email | f).

An INVALID index is never used for reads but is still maintained on writes. After every failure: DROP INDEX CONCURRENTLY and retry; migration scripts should check indisvalid.

Read in post: Inside an index
Edge caseSeniorMySQL online ALTER TABLE can still freeze the whole table through the metadata lockLOCK=NONE allows reads and writes during the build, but at its start and end ALTER needs an exclusive metadata lock (a lock on the table's structure) for a moment. If a long-running transaction (or a session that forgot to commit) holds a shared metadata lock, the ALTER waits, and every new query on the table, SELECT i

LOCK=NONE allows reads and writes during the build, but at its start and end ALTER needs an exclusive metadata lock (a lock on the table's structure) for a moment. If a long-running transaction (or a session that forgot to commit) holds a shared metadata lock, the ALTER waits, and every new query on the table, SELECT included, queues behind it.

Prevention: set lock_wait_timeout to a few seconds and retry, and check information_schema.innodb_trx first. PostgreSQL has the same problem with ACCESS EXCLUSIVE: set lock_timeout.

Read in post: Inside an index
TILMidMySQL merges two indexes for an OR when both sides are indexedWith WHERE id = 1 OR age = 18 and no index on age, MySQL 8.4 scans the whole 1-million-row table (~112 ms). But WHERE id = 1 OR name = 'user77' with name indexed gives an index merge: scan PRIMARY for one side, idxname for the other, deduplicate by row ID, 0.07 ms in total. PostgreSQL does the same with BitmapOr. OR do

With WHERE id = 1 OR age = 18 and no index on age, MySQL 8.4 scans the whole 1-million-row table (~112 ms). But WHERE id = 1 OR name = 'user77' with name indexed gives an index merge: scan PRIMARY for one side, idx_name for the other, deduplicate by row ID, 0.07 ms in total.

PostgreSQL does the same with BitmapOr. OR doesn't kill indexes by itself; a side without an index does.

Read in post: Inside an index
InterviewJuniorWhat's the difference between a key and an index?

A key is a data constraint (PK, unique, foreign key); an index is a data structure for fast lookup.

The database enforces PK and UNIQUE with indexes. For foreign keys, InnoDB creates an index on the child column automatically, PostgreSQL doesn't.

Read in post: Inside an index
InterviewJuniorWhy do databases use B+trees rather than binary trees or B-trees?

Because a B+tree is very short (fan-out in the thousands) and a range scan is just a sideways walk along the leaves.

Each node is a disk page. B+tree internal nodes hold only keys, so 20 million rows fit in 3 levels; linked leaves make range scans and ORDER BY a sideways walk. Binary trees are far too tall; B-trees carry data in internal nodes, so their fan-out is smaller.

Read in post: Inside an index
InterviewJuniorDoes a unique index allow multiple NULLs?

On MySQL and PostgreSQL, yes, because NULL isn't equal to NULL. SQL Server allows one NULL.

PostgreSQL 15+ has NULLS NOT DISTINCT to treat NULLs as duplicates.

Read in post: Inside an index
InterviewMidWhat's a clustered index? Can InnoDB cluster on a column other than the primary key?

A clustered index has whole rows in its leaves and defines the physical order; one per table. InnoDB doesn't let you choose.

InnoDB uses the PK; otherwise the first unique index with all columns NOT NULL; otherwise a hidden row id. SQL Server is the one that lets you cluster on a non-PK column. PostgreSQL uses a heap.

Read in post: Inside an index
InterviewMidWhy do InnoDB secondary indexes store the primary key rather than the row address?

Because row locations change on page splits, merges and rebuilds; storing the PK means moving a row never forces secondary index updates.

The cost is a second lookup into the clustered index, and a fat PK makes every secondary index fat.

Read in post: Inside an index
InterviewMidWhat is a HOT update in PostgreSQL, and how do you get more of them?

If an update changes no indexed column and the page has room, the new version stays on the same page and no index gets a new entry.

To get more: lower the table fillfactor, don't index frequently changing columns, keep autovacuum fast enough. Track n_tup_hot_upd in pg_stat_user_tables.

Read in post: Inside an index
InterviewMidWith an index on (a, b), can WHERE b = ? use the index?

Usually not, because the leading column is missing; the exception is skip scan when a has few values.

Skip scan exists in MySQL 8.0.13+ and PostgreSQL 18; MySQL also requires a covering index. If WHERE b = ? is a main query, create an index that starts with b instead of relying on skip scan.

Read in post: Inside an index
InterviewSeniorWhy is a UUIDv4 primary key slow, and what would you use instead?

Random keys insert into the middle of the tree, causing page splits and a bigger, fragmented index. Use bigint if the database assigns IDs, UUIDv7/ULID/Snowflake if they're generated in a distributed way.

Once the index outgrows RAM, every insert also costs a random read. On 1 million rows: an 80 MB InnoDB clustered index vs 41 MB for bigint; PostgreSQL writes twice the WAL of UUIDv7.

Read in post: Inside an index
InterviewSeniorHow do the InnoDB and PostgreSQL storage models affect index design?

InnoDB needs a short, increasing PK; PostgreSQL needs few indexes on update-heavy tables.

  • InnoDB: secondaries store the PK, reads cost two tree walks; updating non-indexed columns touches no index.
  • PostgreSQL: indexes point to TIDs, reads cost one tree walk, but non-HOT updates add an entry to every index. Update-heavy tables need few indexes, a lower fillfactor and a well-tuned autovacuum.
Read in post: Inside an index
InterviewSeniorShould you rebuild indexes regularly because B+trees become unbalanced?

No. B+trees are always balanced; what degrades is bloat after mass deletes or updates.

Measure with pgstatindex, rebuild deliberately with REINDEX CONCURRENTLY or OPTIMIZE TABLE. If bloat keeps coming back from time-based deletes, partition instead.

Read in post: Inside an index
InterviewSeniorHow would you add a unique index to a 200-million-row production table?

Clean up duplicates first, then build the index online (CONCURRENTLY or LOCK=NONE/gh-ost), verify the result, and run it off-peak.

  • Clean up duplicates: GROUP BY ... HAVING count(*) > 1.
  • PostgreSQL: CREATE UNIQUE INDEX CONCURRENTLY, watch pg_stat_progress_create_index, check indisvalid, then ADD CONSTRAINT ... UNIQUE USING INDEX.
  • MySQL: ALGORITHM=INPLACE, LOCK=NONE with a small lock_wait_timeout, or gh-ost; check for long transactions first.
  • Watch replication lag.
Read in post: Inside an index
TILSeniorMySQL 8 has LOCK INSTANCE FOR BACKUP, lighter than the global lockFLUSH TABLES WITH READ LOCK blocks every write on the instance. If a long query is running it has to wait, and new writes queue up behind it: the whole system stalls. MySQL 8.0 added LOCK INSTANCE FOR BACKUP: it only blocks DDL and a few admin operations and lets DML keep running, enough for hot backups such as MySQL E

FLUSH TABLES WITH READ LOCK blocks every write on the instance. If a long query is running it has to wait, and new writes queue up behind it: the whole system stalls.

MySQL 8.0 added LOCK INSTANCE FOR BACKUP: it only blocks DDL and a few admin operations and lets DML keep running, enough for hot backups such as MySQL Enterprise Backup or Percona XtraBackup. With mysqldump, use --single-transaction to get a consistent snapshot through MVCC instead of locks.

Read in post: Locks in InnoDB
Edge caseMidFOR SHARE is not enough for "read, check, then write"S is compatible with S, so two transfer requests both get S on account A, both see enough money, then both ask for X to write. Each waits for the other to release its S, and InnoDB detects a deadlock and rolls one back (I reproduced it on MySQL 8.4: the second session got error 1213). When you read in order to decide a

S is compatible with S, so two transfer requests both get S on account A, both see enough money, then both ask for X to write. Each waits for the other to release its S, and InnoDB detects a deadlock and rolls one back (I reproduced it on MySQL 8.4: the second session got error 1213).

When you read in order to decide a write, use FOR UPDATE (X from the start, the second request waits) or put the condition into the UPDATE itself.

Read in post: Locks in InnoDB
Edge caseSeniorThe range-lock diagram in many references no longer matches MySQL 8.4Many references (including the slides' diagram, taken from the book Efficient MySQL Performance) show UPDATE ... WHERE accountnumber BETWEEN 2 AND 5 at RR also taking a next-key lock on the record right after the range (or on the supremum if there's none). That's the behaviour of older MySQL versions. On MySQL 8.4 I me

Many references (including the slides' diagram, taken from the book Efficient MySQL Performance) show UPDATE ... WHERE account_number BETWEEN 2 AND 5 at RR also taking a next-key lock on the record right after the range (or on the supremum if there's none). That's the behaviour of older MySQL versions.

On MySQL 8.4 I measured: a record lock on 2, a next-key lock on 5, and nothing on 9. When you need to know exactly what a statement locks, run it on the version you actually use and read data_locks; don't trust a diagram.

Read in post: Locks in InnoDB
InterviewJuniorHow do a shared lock and an exclusive lock differ?

S is a read lock that many transactions can hold at once; X is a write lock with a single holder that blocks both S and X.

S blocks anyone who wants to write. FOR SHARE takes S; FOR UPDATE, UPDATE and DELETE take X. A plain SELECT takes no lock thanks to MVCC.

Read in post: Locks in InnoDB
InterviewJuniorWhy is an UPDATE by primary key the cheapest kind of locking in InnoDB?

Because it sets a single record lock (X,REC_NOT_GAP) on exactly one record, at both REPEATABLE READ and READ COMMITTED.

An equality match on the primary key finds exactly one record in the clustered index. No gap lock, no extra locks on secondary indexes, so it doesn't block inserts or updates of other rows.

Read in post: Locks in InnoDB
InterviewMidWhat are intention locks for?

They let a whole-table lock request detect a conflict immediately, without scanning every row.

They're table-level locks (IS/IX) set before locking rows, announcing "this transaction holds S/X locks on some rows". Intention locks don't block each other, so they don't reduce row-level concurrency.

Read in post: Locks in InnoDB
InterviewMidWhat does an UPDATE on an unindexed column lock at REPEATABLE READ?

Effectively the whole table: next-key locks on every record it scanned plus the supremum.

It has to scan the clustered index, so it blocks all other updates and inserts. At READ COMMITTED, InnoDB releases the locks on rows that don't match the WHERE right away. The right fix is an index for the condition.

Read in post: Locks in InnoDB
InterviewSeniordata_locks shows X,GAP and X,GAP,INSERT_INTENTION WAITING on the same record. What is going on?

One transaction holds a gap lock on the gap before that record, and another wants to INSERT into that gap, so it waits.

The gap (or next-key) lock typically comes from a locking read or a range UPDATE at RR, or a SELECT ... FOR UPDATE on a value that doesn't exist. If both hold the gap and both insert, it becomes a deadlock. Ways out: use a unique constraint instead of check-then-insert, lock by primary key, or consider READ COMMITTED.

Read in post: Locks in InnoDB
InterviewSeniorA diagram says a range UPDATE also locks the record after the range. How do you verify it?

Run that statement in a transaction on the exact MySQL version you use, then read performance_schema.data_locks.

Look at index_name, lock_mode, lock_data. On MySQL 8.4, BETWEEN 2 AND 5 on the primary key only locks record 2 and next-key 5, not the following record; older versions did. Locking behaviour changes between versions, so always measure instead of trusting a diagram.

Read in post: Locks in InnoDB
Edge caseMidHigh %wa (iowait) does not mean the CPU is busyIn top/vmstat, wa is the share of time the CPU was idle while some I/O was outstanding. It tells you "someone is waiting on the disk", not that the CPU is used up. Likewise, %util in iostat close to 100% on an SSD or NVMe drive doesn't prove saturation, because those devices serve many requests in parallel; look at awa

In top/vmstat, wa is the share of time the CPU was idle while some I/O was outstanding. It tells you "someone is waiting on the disk", not that the CPU is used up. Likewise, %util in iostat close to 100% on an SSD or NVMe drive doesn't prove saturation, because those devices serve many requests in parallel; look at await and aqu-sz instead.

Read in post: I/O models
Trade-offSeniorBlocking, event loop, async I/O or virtual threadsBlocking, one thread per connection: sequential code, easy to debug, meaningful stack traces. Every waiting connection holds a platform thread (~1 MB of virtual stack plus context switches), so a few thousand is the ceiling. Non-blocking + multiplexing (event loop): a handful of threads serve tens of thousands of conne
  • Blocking, one thread per connection: sequential code, easy to debug, meaningful stack traces. Every waiting connection holds a platform thread (~1 MB of virtual stack plus context switches), so a few thousand is the ceiling.
  • Non-blocking + multiplexing (event loop): a handful of threads serve tens of thousands of connections. The price is callback/reactive code that is hard to read, and one accidental blocking call stalls the whole loop.
  • True async (io_uring, IOCP): the fewest system calls, a good fit for storage engines and proxies; the JDK doesn't use io_uring yet.
  • Virtual threads (Java 21): blocking-style code, multiplexing underneath. For CRUD services calling a database and HTTP APIs it's usually the best balance today.
Read in post: I/O models
Edge caseMidAn unbuffered InputStream.read() costs one system call per byteFileInputStream.read() and read() on a socket stream have no Java-side buffer: every call goes into the kernel. Reading a 20 MB file this way takes about 7 seconds even when the file is already in the page cache; reading 64 KB chunks takes about 10 ms. Always wrap with BufferedInputStream/BufferedReader, or use Files.r

FileInputStream.read() and read() on a socket stream have no Java-side buffer: every call goes into the kernel. Reading a 20 MB file this way takes about 7 seconds even when the file is already in the page cache; reading 64 KB chunks takes about 10 ms. Always wrap with BufferedInputStream/BufferedReader, or use Files.readAllBytes, Files.newBufferedReader or transferTo. The same goes for writes: OutputStream.write(int) is unbuffered.

Read in post: I/O models
Edge caseSeniorRegular files have no non-blocking I/O on LinuxONONBLOCK has no effect on regular files: read() still blocks if the data isn't in the page cache. select/poll always report a regular file as ready, and epollctl rejects it with EPERM, which is why a Java NIO Selector won't accept a FileChannel. Non-blocking I/O is a network story.

O_NONBLOCK has no effect on regular files: read() still blocks if the data isn't in the page cache. select/poll always report a regular file as ready, and epoll_ctl rejects it with EPERM, which is why a Java NIO Selector won't accept a FileChannel. Non-blocking I/O is a network story.

Read in post: I/O models
Edge caseSeniorEphemeral ports limit the client side, not the serverA TCP connection is identified by a four-tuple (source IP, source port, destination IP, destination port), so a server listening on 8080 can accept millions of connections from different clients. The port limit only bites outbound: connections to the same destination IP:port have about 28,000 source ports (iplocalportr

A TCP connection is identified by a four-tuple (source IP, source port, destination IP, destination port), so a server listening on 8080 can accept millions of connections from different clients. The port limit only bites outbound: connections to the same destination IP have about 28,000 source ports (ip_local_port_range defaults to 32768–60999). Each actively closed connection keeps its port in TIME_WAIT for 60 seconds. The symptom is Cannot assign requested address; the fix is keep-alive and connection pooling. Which side holds TIME_WAIT, and the common connection errors, are in Networking for backend engineers.

Read in post: I/O models
TILMidA Java NIO Selector is epoll on LinuxSelector.open() picks an implementation per OS: EPollSelectorImpl on Linux, KQueueSelectorImpl on macOS (exercise 2 prints exactly that class name), WEPollSelectorImpl on Windows. register(selector, OPREAD) maps to epollctl(ADD) and select() maps to epollwait. NIO uses level-triggered mode; Netty's native EpollEventLoo

Selector.open() picks an implementation per OS: EPollSelectorImpl on Linux, KQueueSelectorImpl on macOS (exercise 2 prints exactly that class name), WEPollSelectorImpl on Windows. register(selector, OP_READ) maps to epoll_ctl(ADD) and select() maps to epoll_wait. NIO uses level-triggered mode; Netty's native EpollEventLoopGroup transport uses edge-triggered.

Read in post: I/O models
Trade-offSeniorLevel-triggered or edge-triggered epollLevel-triggered (LT, the default): reports an fd as long as unread data remains, so a short read gets reported again next time. The cost is repeated notifications and extra system calls under load. Edge-triggered (ET, EPOLLET): reports only when new data arrives, so fewer wake-ups; a good fit for carefully tuned event
  • Level-triggered (LT, the default): reports an fd as long as unread data remains, so a short read gets reported again next time. The cost is repeated notifications and extra system calls under load.
  • Edge-triggered (ET, EPOLLET): reports only when new data arrives, so fewer wake-ups; a good fit for carefully tuned event loops (Nginx, Netty native). You must use non-blocking sockets and read/write until EAGAIN, or the leftover data sits there and the connection "hangs" without a single log line.
  • If you aren't writing your own event loop: use a library and let it decide.
Read in post: I/O models
Edge caseSeniorOne blocking call in an event loop stalls thousands of connectionsEach Netty or WebFlux event loop thread serves many connections. Calling JDBC, Thread.sleep, Reactor's block() or reading a big file inside a handler blocks that thread, and every connection on that loop stalls with it. The symptom: p99 latency spikes while CPU stays low. Fix it by moving blocking work to Schedulers.bo

Each Netty or WebFlux event loop thread serves many connections. Calling JDBC, Thread.sleep, Reactor's block() or reading a big file inside a handler blocks that thread, and every connection on that loop stalls with it. The symptom: p99 latency spikes while CPU stays low. Fix it by moving blocking work to Schedulers.boundedElastic() or using a non-blocking driver (R2DBC); BlockHound catches these calls in tests.

Read in post: I/O models
Trade-offSeniorfsync on every write or let the kernel flushfsync on every commit (InnoDB innodbflushlogattrxcommit=1): no committed transaction is lost; throughput is capped by fsync latency, relieved by group commit. fsync once a second (InnoDB =2, Redis appendfsync everysec): much faster, may lose about a second of data. No fsync, rely on replication (Kafka's default): durab
  • fsync on every commit (InnoDB innodb_flush_log_at_trx_commit=1): no committed transaction is lost; throughput is capped by fsync latency, relieved by group commit.
  • fsync once a second (InnoDB =2, Redis appendfsync everysec): much faster, may lose about a second of data.
  • No fsync, rely on replication (Kafka's default): durable because of several machines, safe only if replicas don't fail together.
Read in post: I/O models
Edge caseMidSequential is not "3–4× faster" than randomOn an HDD, random 4 KB reads give about 100–200 IOPS (a few hundred KB/s) while sequential reads give 150–250 MB/s: a gap of hundreds of times, because every random read waits for the head to move and the platter to spin. On NVMe the gap shrinks when many requests run in parallel, but one-at-a-time random reads are sti

On an HDD, random 4 KB reads give about 100–200 IOPS (a few hundred KB/s) while sequential reads give 150–250 MB/s: a gap of hundreds of times, because every random read waits for the head to move and the platter to spin. On NVMe the gap shrinks when many requests run in parallel, but one-at-a-time random reads are still tens of times slower than sequential. The design takeaway: write-heavy data should be appended sequentially.

Read in post: I/O models
Edge caseSeniorA failed fsync can "succeed" when retriedIn 2018 PostgreSQL discovered ("fsyncgate") that when fsync fails because of a device error, Linux may mark the dirty pages clean and clear the error. A retried fsync then returns success although the data never reached the disk. PostgreSQL now PANICs and recovers from the WAL instead of retrying. For important data, n

In 2018 PostgreSQL discovered ("fsyncgate") that when fsync fails because of a device error, Linux may mark the dirty pages clean and clear the error. A retried fsync then returns success although the data never reached the disk. PostgreSQL now PANICs and recovers from the WAL instead of retrying. For important data, never retry fsync and call it done.

Read in post: I/O models
Edge caseMidRaising ulimit doesn't fix a file descriptor leakIf the fd count (ls /proc/<pid/fd | wc -l) keeps rising under constant load, raising the limit from 1,024 to 65,536 only postpones the outage. Find the source with lsof -p <pid grouped by type and path. The usual suspects: streams outside try-with-resources, unclosed Files.lines()/Files.list() (they hold an fd until th

If the fd count (ls /proc/<pid>/fd | wc -l) keeps rising under constant load, raising the limit from 1,024 to 65,536 only postpones the outage. Find the source with lsof -p <pid> grouped by type and path. The usual suspects: streams outside try-with-resources, unclosed Files.lines()/Files.list() (they hold an fd until the stream is closed), and HTTP response bodies that are never closed. Track Micrometer's process.files.open and alert above 80% of process.files.max.

Read in post: I/O models
InterviewJuniorIs reading RAM I/O? What is DMA?

No: the CPU accesses RAM directly, while I/O is exchanging data with the outside through the kernel and drivers.

I/O means talking to disks, the network or peripherals. DMA lets a device copy data into RAM without the CPU, then signal completion with an interrupt.

Read in post: I/O models
InterviewJuniorWhat is a file descriptor? What does "Too many open files" mean?

An fd is an integer the kernel returns when a process opens a file, socket, pipe or device; the error means the process hit its fd limit.

The limit is set by ulimit -n or LimitNOFILE. You hit it because the limit is low or because fds are leaking. An fd count that only ever grows is a leak.

Read in post: I/O models
InterviewJuniorWhy wrap a FileInputStream in a BufferedInputStream?

Because FileInputStream.read() is unbuffered, so every call is a system call.

Reading 20 MB byte by byte takes seconds, with a 64 KB buffer about 100 ms. Add try-with-resources so the stream is always closed.

Read in post: I/O models
InterviewMidExplain blocking, non-blocking, multiplexed and asynchronous I/O.

They differ in which phase blocks the thread: waiting for data, or copying it from kernel to user space.

Blocking blocks in both. Non-blocking returns EAGAIN if there's no data yet. Multiplexing lets one thread wait on many fds. Asynchronous (io_uring, IOCP) blocks in neither. The first three are still synchronous because the thread waits during the copy.

Read in post: I/O models
InterviewMidWhy does epoll scale better than select and poll?

Because epoll registers each fd once and epoll_wait costs only as much as the ready fds, while select/poll scan all N fds on every call.

select/poll take the whole fd set on every call and both the kernel and the application scan all N fds: O(N), and select is capped at 1,024. epoll registers with epoll_ctl (a red-black tree), and the kernel moves fds onto a ready list via callbacks when data arrives.

Read in post: I/O models
InterviewMidIs a server listening on port 8080 limited to 65,535 connections?

No. A connection is identified by the source and destination IP/port four-tuple, so the real limits are fds, memory and the threading model.

The port limit only affects outbound connections to the same destination (~28,000 source ports, 60-second TIME_WAIT), which is why you need connection pooling and keep-alive.

Read in post: I/O models
InterviewSeniorTomcat has 200 threads by default. What happens to request 201 and connection 9,000?

Request 201 is accepted but waits for a free worker; connection 9,000 exceeds max-connections (8,192), so it waits in the backlog and is refused once that fills.

The NIO connector separates holding connections from processing them: the Poller holds up to 8,192 connections, the worker pool (200) runs servlets. Beyond 8,192 connections, new ones wait in the accept-count backlog (100); once that fills, clients time out or are refused. Virtual threads remove the 200 ceiling, but it moves to the connection pool, which needs a timeout.

Read in post: I/O models
InterviewSeniorHow do virtual threads run blocking code on top of epoll?

The JDK turns a blocking read into: register the fd with epoll, park the virtual thread, unpark it when the socket is ready.

When a virtual thread reads a socket with no data, the JDK switches the socket to non-blocking, registers the fd with an internal poller (epoll on Linux), parks the virtual thread and unmounts it from its carrier. When epoll reports readiness, the poller unparks it and it resumes on any carrier, with its stack kept on the heap. Exceptions: file I/O occupies the carrier (the scheduler compensates with a temporary carrier), and on Java 21 I/O inside synchronized pins (fixed in Java 24).

Read in post: I/O models
InterviewSeniorwrite() returned successfully, then the machine lost power. Is the data there?

Maybe not: write() only copies into the page cache and the kernel flushes later.

Durability needs fsync (FileChannel.force(true)). Databases fsync every commit with group commit, or relax to once a second and accept losing up to a second; Kafka relies on replication.

Read in post: I/O models
InterviewSeniorA service throws "Too many open files" at 3 a.m. How do you investigate?

Check the limit and the current fd count, use the metric's history to tell a low limit from a leak, then find the source with lsof.

  • Check the limit (cat /proc/<pid>/limits) and the open fd count (ls /proc/<pid>/fd | wc -l).
  • The fd metric's history: rising with load and falling back means the limit is too low, a steady climb means a leak.
  • Group fds with lsof -p <pid> and ss -tanp: many handles to the same path mean unclosed streams; many CLOSE_WAIT sockets to one host mean unclosed response bodies.
  • Fix the root cause in code and alert when fds exceed 80% of the limit.
Read in post: I/O models
Edge caseSeniorHash joins need no index but do need memory, and work_mem applies per nodeA nested loop needs an index on the inner join column; a hash join doesn't use an index to combine rows, and an index only helps when it filters an input. What a hash join needs is memory: exceed workmem or joinbuffersize (MySQL) and it spills to disk (Batches 1, temp read/written). workmem is a limit per Sort/Hash nod

A nested loop needs an index on the inner join column; a hash join doesn't use an index to combine rows, and an index only helps when it filters an input. What a hash join needs is memory: exceed work_mem or join_buffer_size (MySQL) and it spills to disk (Batches > 1, temp read/written).

work_mem is a limit per Sort/Hash node of every query (hashes also get hash_mem_multiplier, 2 by default since PostgreSQL 15). 200 connections × 3 nodes × 256 MB can exhaust the server's RAM, so raise it only for the reporting job: SET LOCAL work_mem = '256MB'.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Edge caseMidMySQL has no merge join; PostgreSQL uses it all the time"Merge joins are rarely used because sorting is expensive" is only true of MySQL, because MySQL has no sort-merge join: only nested loops (plus variants such as batched key access) and, since 8.0.18, hash joins. PostgreSQL, SQL Server and Oracle pick merge joins fairly often: inputs already sorted by an index, a result

"Merge joins are rarely used because sorting is expensive" is only true of MySQL, because MySQL has no sort-merge join: only nested loops (plus variants such as batched key access) and, since 8.0.18, hash joins. PostgreSQL, SQL Server and Oracle pick merge joins fairly often: inputs already sorted by an index, a result that needs ORDER BY on the join key, or two inputs too big for a hash table. Look at the plan before carrying an observation from one database to another.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Trade-offSeniorNested loop, hash join or merge joinNested loop: small outer side, indexed inner side; first row immediately (good for LIMIT and paginated APIs); any join condition. A disaster when the outer side is larger than estimated or the inner index is missing. Hash join: joining most of two large tables on an equality with no suitable index (reports, ETL). Needs
  • Nested loop: small outer side, indexed inner side; first row immediately (good for LIMIT and paginated APIs); any join condition. A disaster when the outer side is larger than estimated or the inner index is missing.
  • Hash join: joining most of two large tables on an equality with no suitable index (reports, ETL). Needs memory; returns nothing until the build is done.
  • Merge join (PostgreSQL): both sides already ordered by the key or the result needs ORDER BY on it; light on memory. If it has to sort two large inputs, it usually loses to a hash join.
  • When a plan is bad, suspect a wrong row estimate before the algorithm.
Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Edge caseMidA condition on the right-hand table in WHERE turns a LEFT JOIN into an INNER JOINCustomers without a PAID order have o.status = NULL, and NULL = 'PAID' isn't true, so their rows are dropped. This bug shows up the moment someone adds a status filter to an "all customers and their revenue" report. Conditions on the right-hand table belong in ON; put them in WHERE only when you really mean to filter (

Customers without a PAID order have o.status = NULL, and NULL = 'PAID' isn't true, so their rows are dropped. This bug shows up the moment someone adds a status filter to an "all customers and their revenue" report. Conditions on the right-hand table belong in ON; put them in WHERE only when you really mean to filter (like WHERE o.id IS NULL to find customers with no orders).

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Trade-offMidJOIN, IN/EXISTS or JOIN + DISTINCT to filter by another tableJOIN + DISTINCT: easy to write, but duplicates rows when the other side has several matches (1–3 tickets per booking), then spends extra work removing the duplicates. EXISTS / IN (subquery): says exactly "at least one", becomes a semi-join (a join that only asks whether a match exists) and stops at the first match. Usu
  • JOIN + DISTINCT: easy to write, but duplicates rows when the other side has several matches (1–3 tickets per booking), then spends extra work removing the duplicates.
  • EXISTS / IN (subquery): says exactly "at least one", becomes a semi-join (a join that only asks whether a match exists) and stops at the first match. Usually the best choice; also helps when the subquery returns a very small set used to filter a large table.
  • NOT IN (subquery): a trap when the subquery can return NULL: a single NULL makes the result empty. Use NOT EXISTS (an anti-join).
  • There's no absolute rule; compare with EXPLAIN ANALYZE on real data.
Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Trade-offSeniorOne JOIN or several single-table queriesOne JOIN: one round-trip, the database sees the whole picture to choose an algorithm, and everything is read from one snapshot, so it's consistent. Split queries: per-entity caching works well, a table can move to another service/shard easily. The cost: more round-trips, data across queries can be inconsistent outside
  • One JOIN: one round-trip, the database sees the whole picture to choose an algorithm, and everything is read from one snapshot, so it's consistent.
  • Split queries: per-entity caching works well, a table can move to another service/shard easily. The cost: more round-trips, data across queries can be inconsistent outside a shared transaction, the application combines and paginates.
  • A very long IN costs parsing and can hit limits (the PostgreSQL JDBC driver allows at most 32,767 parameters per statement); use = ANY(?) with a single array parameter. Don't let the split turn into N+1.
Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Edge caseSeniorOn a partitioned table, PRIMARY KEY and UNIQUE must include the partition keyUniqueness is only checked within each partition, so PRIMARY KEY (bookref) fails with must include all partitioning columns. The PK becomes (bookref, bookdate), and bookref is no longer guaranteed unique across the table: two bookings with the same code in different months can both be inserted. Ways out: a partition ke

Uniqueness is only checked within each partition, so PRIMARY KEY (book_ref) fails with must include all partitioning columns. The PK becomes (book_ref, book_date), and book_ref is no longer guaranteed unique across the table: two bookings with the same code in different months can both be inserted.

Ways out: a partition key that's part of the natural key, globally unique ids (a sequence, UUIDv7), or a small side table that enforces global uniqueness. Foreign keys pointing at a partitioned table must reference the whole (book_ref, book_date); MySQL doesn't support foreign keys on partitioned InnoDB tables at all.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Edge caseMidQueries that don't filter on the partition key read every partitionPruning only happens when WHERE has a condition on the partition key that the planner (or the executor, for run-time parameters) can use. Looking up by bookref produces 15 Index Scans; 500 partitions means 500 index descents, plus planning time that grows with the partition count. Wrapping the key in a function (WHERE

Pruning only happens when WHERE has a condition on the partition key that the planner (or the executor, for run-time parameters) can use. Looking up by book_ref produces 15 Index Scans; 500 partitions means 500 index descents, plus planning time that grows with the partition count. Wrapping the key in a function (WHERE date(book_date) = ...) kills pruning too. Before partitioning, list the main queries: if most of them lack the key, don't partition.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Trade-offSeniorPartition or shardPartition: one server, no application changes, transactions and joins work as usual. Does not add write capacity, RAM or storage beyond one machine; when the server dies, everything is gone. Shard: spreads write load and data across machines, and a failure only affects part of it. The cost: cross-shard transactions/joi
  • Partition: one server, no application changes, transactions and joins work as usual. Does not add write capacity, RAM or storage beyond one machine; when the server dies, everything is gone.
  • Shard: spreads write load and data across machines, and a failure only affects part of it. The cost: cross-shard transactions/joins are very expensive or unavailable, a wrong shard key nearly means starting over, rebalancing is complex.
  • Partition first; shard only when one node (even with read replicas) can't handle the write load or the data size.
Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Trade-offSeniorClimb the ladder instead of jumping straight to shardingQuery, index: cheap, easy to undo, solve most incidents. Archive, cache: shrink the hot data, at the cost of jobs and invalidation. Replicas, partitions, shards, other databases: change the architecture (lag, schema constraints, operational cost) and are very hard to undo. In an interview: ask for numbers (size, read/w
  • Query, index: cheap, easy to undo, solve most incidents.
  • Archive, cache: shrink the hot data, at the cost of jobs and invalidation.
  • Replicas, partitions, shards, other databases: change the architecture (lag, schema constraints, operational cost) and are very hard to undo.
  • In an interview: ask for numbers (size, read/write ratio, main queries, hot data) and walk up the steps; don't say "shard" right away.
Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewJuniorWhat join algorithms do databases use?

Three: nested loop, hash join and merge join.

Nested loop: for each outer row, find matching inner rows; good with an index on the join column. Hash join: build a hash table from the smaller input and probe it with the larger one; good for large equality joins. Merge join: sort both inputs and walk them in step; PostgreSQL has it, MySQL doesn't.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewJuniorDoes it matter whether a condition goes in ON or WHERE?

Not for an INNER JOIN; for a LEFT JOIN it does.

A condition on the right-hand table in WHERE removes the NULL rows and effectively turns it into an INNER JOIN. To keep every row of the left table, put the condition in ON.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewMidWhen is a hash join better than a nested loop?

When joining most of two large tables on an equality, especially without a suitable index on the join column.

A nested loop wins when the outer side is small and the inner side is indexed, or when you need the first rows fast with LIMIT. In the lab, joining all 2.1 million × 3.1 million rows took 0.7 seconds with a hash join and 3.7 with a nested loop.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewMidIn a PostgreSQL plan, what does Batches: 4 on a Hash node mean?

The build input didn't fit in work_mem, so the hash join spilled to disk in 4 parts.

Both inputs were split into 4 partitions by a hash of the key, the ones not yet processed were written to temp files, and they were joined pair by pair; you'll see temp read/written with it. Options: raise work_mem for that session, shrink the build input's rows or columns, or accept it if the query isn't hot.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewSeniorYou partition an orders table by created_at. What can break?

Table-wide uniqueness, foreign keys, queries without created_at, creating new partitions, and planning time.

  • PK/unique constraints must include created_at, so order_id is no longer guaranteed unique across the table; foreign keys pointing at the table have to change.
  • Queries by order_id or customer_id without created_at scan every partition.
  • You need a job that creates next month's partition in advance (or a default partition), or inserts fail.
  • Many partitions increase planning time.

What you gain is time-based pruning and removing old data by detaching.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
InterviewSeniorThe main table has reached a few hundred million rows and is getting slow. How do you approach it?

Measure first, then climb from cheap to expensive, moving up only when the numbers show the previous step isn't enough.

Measure: size, top queries by total time, read/write ratio, how much of the data is hot. The steps: rewrite queries, add indexes, archive, cache, read replicas, partition/shard, a different database. Each step is more expensive and harder to undo than the previous one.

Read in post: How joins run (nested loop, hash join, merge join) and when to partition a table
Edge caseMidPre-created spare columns c1..c6 are an anti-pattern on modern databasesThe "create c1 VARCHAR(200), c2, …, c6 INT up front and use them later" trick was born when old MySQL had to lock the table to add a column and couldn't index JSON expressions. Both reasons are gone: MySQL 8.0.29+ adds a column at any position with ALGORITHM=INSTANT (3 ms on 1 million rows). PostgreSQL 11+ adds a colum

The "create c1 VARCHAR(200), c2, …, c6 INT up front and use them later" trick was born when old MySQL had to lock the table to add a column and couldn't index JSON expressions. Both reasons are gone:

  • MySQL 8.0.29+ adds a column at any position with ALGORITHM=INSTANT (3 ms on 1 million rows).
  • PostgreSQL 11+ adds a column with a constant default by changing metadata only (0.8 ms).
  • JSON fields can be indexed through generated columns, functional indexes or GIN.

Spare columns leave meaningless names, types guessed wrong, confusing ORM mappings and docs, and nobody dares drop them. Add a real column with the right name and type through a migration (Flyway, Liquibase).

Read in post: Evolving a schema
Trade-offSeniorPut a new attribute into the JSON column or make it a real columnA real column when the attribute is used for filtering, joining or sorting, needs constraints (NOT NULL, CHECK, FK), or is on most rows. The database knows its type, keeps accurate statistics for the planner and stores it compactly. The JSON column for sparse attributes that vary by record type (sales-channel metadata,
  • A real column when the attribute is used for filtering, joining or sorting, needs constraints (NOT NULL, CHECK, FK), or is on most rows. The database knows its type, keeps accurate statistics for the planner and stores it compactly.
  • The JSON column for sparse attributes that vary by record type (sales-channel metadata, per-tenant settings), or data that is only read and displayed whole. The slides say "leverage JSON if possible"; I'd refine that to "leverage JSON for the sparse, rarely queried part".
  • In between: an occasional filter gets a generated column or an expression index; once it becomes a primary filter, promote it to a real column.
  • Signs of overuse: data->>'...' all over WHERE, nobody knows which keys exist, every row has a different shape. Then you need JSON Schema in the application or CHECK (jsonb_typeof(...)).
Read in post: Evolving a schema
Edge caseSeniorAn "online" ALTER can still freeze a whole table because of the metadata lockA metadata lock is a lock on the table's definition. Even INSTANT or INPLACE, LOCK=NONE needs an exclusive metadata lock for a moment at the start and end (the slides call it "a small lock at the end"). If a long transaction is touching the table (a 10-minute report, a session that forgot to commit), the ALTER waits, a

A metadata lock is a lock on the table's definition. Even INSTANT or INPLACE, LOCK=NONE needs an exclusive metadata lock for a moment at the start and end (the slides call it "a small lock at the end").

If a long transaction is touching the table (a 10-minute report, a session that forgot to commit), the ALTER waits, and every new query queues behind it: the whole table stalls. PostgreSQL does the same with ACCESS EXCLUSIVE.

Prevention: set a short lock_wait_timeout (MySQL) or lock_timeout (PostgreSQL), say 3 seconds, for the migration session and retry; check for long transactions before you start.

Read in post: Evolving a schema
Edge caseMidIn MySQL, TIMESTAMP is the type that depends on time_zone, not DATETIMEThe slides say DATETIME "depends on the time zone"; it's the other way round. TIMESTAMP is converted from the session timezone to UTC on write and back on read; DATETIME stores the value as given and knows nothing about zones. MySQL 8.4: write '2026-11-18 09:00:00' into both columns with timezone = '+07:00', read with

The slides say DATETIME "depends on the time zone"; it's the other way round. TIMESTAMP is converted from the session time_zone to UTC on write and back on read; DATETIME stores the value as given and knows nothing about zones.

  • MySQL 8.4: write '2026-11-18 09:00:00' into both columns with time_zone = '+07:00', read with '+00:00': TIMESTAMP returns 02:00, DATETIME still says 09:00.
  • TIMESTAMP stops at 2038: writing '2038-01-19 03:14:08' (UTC) fails with error 1292.
  • Storage since MySQL 5.6.4: DATETIME 5 bytes, TIMESTAMP 4 bytes, plus 0–3 bytes for fractional seconds.

For data that lives past 2038 (contracts, installment plans, warranties), don't use TIMESTAMP.

Read in post: Evolving a schema
TILSeniorSince MySQL 8.0.22, filters are pushed down into views with GROUP BYSince MySQL 8.0.22 the optimizer does derived condition pushdown. With a view vclickcount (GROUP BY userid) over 500,000 rows, SELECT FROM vclickcount WHERE userid = 42 still runs a ref lookup on idxuser and reads only 25 rows, because the condition on the grouping column is applied before aggregation. Conditions on th

Since MySQL 8.0.22 the optimizer does derived condition pushdown. With a view v_click_count (GROUP BY user_id) over 500,000 rows, SELECT * FROM v_click_count WHERE user_id = 42 still runs a ref lookup on idx_user and reads only 25 rows, because the condition on the grouping column is applied before aggregation.

Conditions on the aggregated column (cnt > 30) or arriving through a JOIN are not pushed down. It's controlled by optimizer_switch='derived_condition_pushdown=on'.

Read in post: Evolving a schema
Edge caseSeniorA view with GROUP BY that gets JOINed is computed in full before filteringA view with GROUP BY looks like a small, tidy table, so it tends to get joined into other queries. MySQL (TEMPTABLE) and PostgreSQL push down a filter on the grouping column, but not a condition coming through a JOIN: the database computes the entire view and joins afterwards. MySQL 8.4: joining 3 users with a click-co

A view with GROUP BY looks like a small, tidy table, so it tends to get joined into other queries. MySQL (TEMPTABLE) and PostgreSQL push down a filter on the grouping column, but not a condition coming through a JOIN: the database computes the entire view and joins afterwards.

  • MySQL 8.4: joining 3 users with a click-count view (500,000 rows) took 65 ms because all 20,000 groups were built; against the base table, 0.05 ms.
  • PostgreSQL 16 with 2 million posts: 242 ms versus 0.06 ms.

Always check the EXPLAIN of queries on views, especially views stacked on views.

Read in post: Evolving a schema
InterviewJuniorDoes a view store data?

A regular view doesn't; it stores only the query.

Every read re-runs it against the base tables. A materialized view (PostgreSQL has them, MySQL doesn't) stores the result and must be refreshed to pick up changes.

Read in post: Evolving a schema
InterviewJuniorWhy not store money as FLOAT or DOUBLE?

Because IEEE 754 stores the nearest binary value, so 0.1 can't be represented exactly.

Adding 0.10 ten times as a double in Java gives 0.9999999999999999. Use DECIMAL in the database and BigDecimal (built from a string or valueOf) in Java, or integers in the smallest currency unit.

Read in post: Evolving a schema
InterviewJuniorHow do INT(1) and INT(11) differ?

Not at all in storage or range: both are 4-byte INTs.

The number in parentheses is only a display width, which MySQL 8 has deprecated and drops from the table definition.

Read in post: Evolving a schema
InterviewMidHow do TIMESTAMP and DATETIME differ in MySQL?

TIMESTAMP follows the session time_zone and stops at 2038; DATETIME stores the value as given, with no zone.

TIMESTAMP is stored internally as UTC, takes 4 bytes and ends on 2038-01-19. DATETIME takes 5 bytes and goes to year 9999. For data beyond 2038 or deliberate local times, use DATETIME plus a time zone column; for system instants, store UTC.

Read in post: Evolving a schema
InterviewMidHow do MERGE and TEMPTABLE views differ in MySQL?

MERGE folds the user's query into the view and runs it on the base tables; TEMPTABLE computes the view into a temporary table first.

MERGE can use indexes. TEMPTABLE is required for GROUP BY, DISTINCT, aggregates, LIMIT and UNION. Since 8.0.22 filters on grouping columns are pushed inside, but conditions coming through a JOIN are not.

Read in post: Evolving a schema
InterviewMidHow do varchar(n) and text differ in PostgreSQL?

In storage they're the same; varchar(n) just adds a length check.

Long values are compressed and moved to TOAST automatically in both. That's unlike MySQL, where TEXT may live off-page, can only get prefix indexes and can't use an index for sorting.

Read in post: Evolving a schema
InterviewSeniorWhen does an attribute go into the JSON column and when does it become a real column?

A real column when it's used for filtering, joining, sorting or constraints, or most rows have it; JSON for sparse, display-only attributes.

JSON suits attributes that vary by record type. For occasional filters, a generated column or an expression/GIN index; once it becomes a primary filter, promote it. Adding columns is cheap now (INSTANT in MySQL 8, constant defaults in PG 11+), so "avoiding ALTER" is no longer a reason.

Read in post: Evolving a schema
InterviewSeniorAn online ALTER still froze production. Why, and how do you prevent it?

Because the ALTER still needs an exclusive metadata lock for a moment, and it has to wait for long transactions touching the table.

While the ALTER waits, every new query queues behind it, so the whole table stalls. Prevent it with a short lock_wait_timeout/lock_timeout for the migration session plus retries, checking for long transactions first, and running during off-peak hours.

Read in post: Evolving a schema
InterviewSeniorWhat should you watch for when using views as a permission layer in PostgreSQL?

By default a view runs with its owner's privileges, so a role granted only the view still reads the base table through it.

That's the mechanism, but also a hole if unintended. Since PG 15, security_invoker = true makes the view check the caller's privileges. security_barrier prevents user-written functions from seeing filtered rows. For per-row permissions, consider row-level security.

Read in post: Evolving a schema
InterviewSeniorWhat does REFRESH MATERIALIZED VIEW CONCURRENTLY require and what do you get for it?

It requires a unique index with no WHERE clause on the materialized view; in return, readers aren't blocked during the refresh.

Without that index PostgreSQL refuses. The cost is a slower refresh because old and new results are diffed row by row. The data is still stale until the next refresh.

Read in post: Evolving a schema
Edge caseJuniorThe Java consumer doesn't create a random group when group.id is missingThe slides say a consumer without a group name creates a random group. That's the behaviour of kafka-console-consumer (the CLI generates console-consumer-xxxxx). A Java KafkaConsumer calling subscribe() without a group.id throws InvalidGroupIdException. You can still read without a group via assign() (you pick partitio

The slides say a consumer without a group name creates a random group. That's the behaviour of kafka-console-consumer (the CLI generates console-consumer-xxxxx). A Java KafkaConsumer calling subscribe() without a group.id throws InvalidGroupIdException. You can still read without a group via assign() (you pick partitions yourself), but you can't commit offsets and there's no rebalancing. So "every consumer must belong to a group" is only true with subscribe().

Read in post: Inside Kafka consumer groups
Trade-offSeniorRange or cooperative-stickyRange: predictable, and with two topics of equal partition count, partition i of both always goes to the same consumer. Kafka Streams and hand-written joins need this (co-partitioning). The cost: skew with many topics, and eager stops the whole group. Cooperative-sticky: few moves, unaffected consumers don't stop, loca
  • Range: predictable, and with two topics of equal partition count, partition i of both always goes to the same consumer. Kafka Streams and hand-written joins need this (co-partitioning). The cost: skew with many topics, and eager stops the whole group.
  • Cooperative-sticky: few moves, unaffected consumers don't stop, local per-partition caches survive. The cost: two rebalance rounds, more complex logic, and no co-partitioning guarantee.
  • The Java client default since 3.0 is [RangeAssignor, CooperativeStickyAssignor], which means range is still used; the cooperative entry only prepares for an upgrade. To get cooperative you must set it explicitly (the two-step rolling upgrade is in the configuration post).
Read in post: Inside Kafka consumer groups
Trade-offSeniorStatic membership: fewer rebalances or slower failure detectionGain: a rolling deploy of 20 pods no longer causes 40 rebalances (one leave and one join per pod). Caches and local state tied to partitions are kept. Cost: when a pod really dies, its partitions are read by nobody until session.timeout.ms expires. A 5-minute session to tolerate slow deploys means 5 minutes of lag when
  • Gain: a rolling deploy of 20 pods no longer causes 40 rebalances (one leave and one join per pod). Caches and local state tied to partitions are kept.
  • Cost: when a pod really dies, its partitions are read by nobody until session.timeout.ms expires. A 5-minute session to tolerate slow deploys means 5 minutes of lag when a node dies.
  • Set the session timeout a bit above a pod's (p99) restart time, no more. Each instance needs a unique id: two instances with the same id fence the older one (FencedInstanceIdException).
  • Spring Kafka with concurrency > 1 appends -1, -2… to group.instance.id for each child consumer.
Read in post: Inside Kafka consumer groups
Edge caseSeniorSwitching to group.protocol=consumer while keeping the old settingsUnder the new protocol, partition.assignment.strategy, session.timeout.ms and heartbeat.interval.ms are no longer the client's job. I checked with client 4.1.1: setting any of the three together with group.protocol=consumer makes the consumer fail to start (ConfigException: session.timeout.ms cannot be set when group.p

Under the new protocol, partition.assignment.strategy, session.timeout.ms and heartbeat.interval.ms are no longer the client's job. I checked with client 4.1.1: setting any of the three together with group.protocol=consumer makes the consumer fail to start (ConfigException: session.timeout.ms cannot be set when group.protocol=CONSUMER). Flipping the new flag with one line in a shared config file takes down every service that still sets the old values. Remove them from the client and tune them on the broker (cluster-wide) or per group with kafka-configs --entity-type groups. Client-side custom assignors stop working too.

Read in post: Inside Kafka consumer groups
Edge caseSeniorA batch longer than max.poll.interval.ms creates a reprocessing loopPast the deadline, the client leaves the group itself; the following commit is rejected (CommitFailedException); the next poll rejoins, gets the partition back from the old committed offset, processes the same batch and overruns again. Nothing ever stops the process. Do the math up front: max.poll.records × p99 process

Past the deadline, the client leaves the group itself; the following commit is rejected (CommitFailedException); the next poll rejoins, gets the partition back from the old committed offset, processes the same batch and overruns again. Nothing ever stops the process.

Do the math up front: max.poll.records × p99 processing time per record < max.poll.interval.ms, with a 2× safety margin. Example: p99 800 ms per record, interval 300 s: at most about 300 / 0.8 / 2 ≈ 187 records per poll. Raising session.timeout.ms does not help, because this is the progress check, not the heartbeat. Ways to handle long tasks (pausing partitions, async processing, splitting the pipeline) are in partition counts, lag and long-running tasks.

Read in post: Inside Kafka consumer groups
Trade-offSeniorSkip the poison pill or stop the partitionSkip and send to a DLT: the partition keeps moving and lag doesn't grow. The cost: the broken record is handled later (or never), and per-key ordering breaks: later events for the same key are processed before the broken one. Stop the partition (retry forever, page the on-call): absolute ordering, right for ledgers or
  • Skip and send to a DLT: the partition keeps moving and lag doesn't grow. The cost: the broken record is handled later (or never), and per-key ordering breaks: later events for the same key are processed before the broken one.
  • Stop the partition (retry forever, page the on-call): absolute ordering, right for ledgers or account state transitions. The cost: one bad record stalls the whole partition.
  • Middle ground: a few retries for transient errors (DB timeouts), straight to the DLT for permanent ones (deserialization, validation); for order-sensitive flows, mark that key "blocked" and route later events for the same key to the DLT as well.
Read in post: Inside Kafka consumer groups
InterviewJuniorCan two consumers in the same group read the same partition?

No: within a group, each partition belongs to at most one consumer. With more consumers than partitions, some sit idle.

Two different groups are independent, and each reads all the data.

Read in post: Inside Kafka consumer groups
InterviewJuniorWhen does a consumer group rebalance?

When a consumer joins, leaves or is considered dead (missed heartbeats, exceeded max.poll.interval.ms), when a subscription changes, or when a topic gains partitions.

Static membership makes a quick restart stop counting as "leave then join".

Read in post: Inside Kafka consumer groups
InterviewMidHow do eager and cooperative rebalancing differ, in numbers?

Eager revokes every partition from every consumer each time; cooperative revokes only what must move, over two rounds.

In a 6-partition lab adding two consumers, eager (range) revoked 10 partitions from the first consumer, cooperative-sticky only 4. When the third consumer joined, cooperative moved only 2 partitions.

Read in post: Inside Kafka consumer groups
InterviewMidHow do heartbeats and max.poll.interval.ms differ?

Heartbeats prove the process is alive and run on a background thread; max.poll.interval.ms proves the processing loop is moving, measured between poll() calls.

A process stuck in processing still heartbeats fine; only the poll check catches it. That's why raising session.timeout.ms doesn't rescue a slow batch.

Read in post: Inside Kafka consumer groups
InterviewMidCan you commit offsets in onPartitionsLost?

You shouldn't: by then the consumer has been kicked out and the partition may belong to someone else, so the commit fails or overwrites the new owner's progress.

Commits belong in onPartitionsRevoked, while the consumer is still a valid member. onPartitionsLost only cleans up.

Read in post: Inside Kafka consumer groups
InterviewSeniorWhat does KIP-848 change compared with the classic protocol?

The broker computes the assignment and delivers it via heartbeats; no group leader, no JoinGroup/SyncGroup and no group-wide barrier; each consumer releases and acquires partitions gradually.

Consequences: one slow consumer doesn't drag the group; heartbeat and session timeout are configured on the broker; the assignor is chosen with group.remote.assignor. It needs brokers and clients on 4.0+.

Read in post: Inside Kafka consumer groups
InterviewSeniorDesign a consumer group so a rolling deploy of 50 pods doesn't spike lag.

KIP-848 if possible; otherwise cooperative-sticky plus static membership with a session timeout above one pod's restart time.

Also: clean shutdown to commit before leaving, max.poll.records small enough that rebalances don't wait on long batches, and measure rebalance-total and lag during deploys to prove it.

Read in post: Inside Kafka consumer groups
InterviewSeniorThe consumer shows no errors, heartbeats are steady, but lag doesn't drop and side effects repeat. What do you suspect?

The max.poll.interval.ms loop: kicked out, commit fails, the same batch comes back and gets reprocessed forever.

Check time-between-poll-max and logs for CommitFailedException. Fix by lowering max.poll.records to fit worst-case processing time, or by moving long work out of the poll loop.

Read in post: Inside Kafka consumer groups
InterviewSeniorHow do you handle poison pills and still keep per-key ordering?

Classify errors: retry transient ones, DLT permanent ones; for order-sensitive flows, block that key and route later events for the same key to the DLT too.

Plain skipping keeps the partition moving but breaks per-key order; stopping the partition keeps order but lets one bad record block every other key. Choose by business need.

Read in post: Inside Kafka consumer groups
Edge caseMid@Transactional around kafkaTemplate.send() doesn't make the two writes atomicIn Spring, calling send() inside a JPA @Transactional method only means the event is sent while the DB transaction is open. If the DB commit fails afterwards, the event is already in Kafka. Sending after commit with @TransactionalEventListener(phase = AFTERCOMMIT) breaks the other way: the commit succeeds, the service

In Spring, calling send() inside a JPA @Transactional method only means the event is sent while the DB transaction is open. If the DB commit fails afterwards, the event is already in Kafka. Sending after commit with @TransactionalEventListener(phase = AFTER_COMMIT) breaks the other way: the commit succeeds, the service dies before sending, the event is lost. Both are still dual writes.

Read in post: Kafka in practice (2)
Trade-offSeniorOutbox or CDC directly on business tablesDirect CDC needs no change to the write path and suits syncing data to search or a warehouse. But events expose the table schema: renaming a column breaks consumers, and one business operation touching three tables becomes three separate events. An outbox costs a table and a line of code per write, and in return the ev

Direct CDC needs no change to the write path and suits syncing data to search or a warehouse. But events expose the table schema: renaming a column breaks consumers, and one business operation touching three tables becomes three separate events. An outbox costs a table and a line of code per write, and in return the event is a stable business contract that you name and version. Between services, I choose the outbox.

Read in post: Kafka in practice (2)
Edge caseSeniorKafka's exactly-once doesn't cover external side effectsenable.idempotence stops duplicates in the Kafka log, Kafka transactions stop duplicates across Kafka topics. Neither knows you wrote to a DB or called a payment gateway. A consumer that dies after the DB write but before committing the offset gets that record again. Every sink with real effects still needs idempotency

enable.idempotence stops duplicates in the Kafka log, Kafka transactions stop duplicates across Kafka topics. Neither knows you wrote to a DB or called a payment gateway. A consumer that dies after the DB write but before committing the offset gets that record again. Every sink with real effects still needs idempotency at the application level.

Read in post: Kafka in practice (2)
Trade-offSeniorPer-key ordering or high parallelism in the consumerProcessing a whole partition sequentially is simplest, but throughput is capped by the partition count. Parallelism per key within a partition (one queue per key, like the Confluent Parallel Consumer) keeps per-key order while adding concurrency, at the cost of managing offsets yourself: only commit up to an offset who

Processing a whole partition sequentially is simplest, but throughput is capped by the partition count. Parallelism per key within a partition (one queue per key, like the Confluent Parallel Consumer) keeps per-key order while adding concurrency, at the cost of managing offsets yourself: only commit up to an offset whose predecessors are all done. I start with sequential per partition and move to per-key parallelism only when measurements say so.

Read in post: Kafka in practice (2)
InterviewJuniorWhat ordering does Kafka guarantee?

Only within a partition. To keep related messages in order, give them the same key so they land in the same partition.

A topic with many partitions has no total order. One partition does, but loses parallelism.

Read in post: Kafka in practice (2)
InterviewJuniorWhat is a dual write?

An operation that must write to two systems (say a DB and Kafka) with no shared transaction, so sometimes one side succeeds and the other doesn't.

The standard fix is the transactional outbox: write the event to an outbox table in the same DB transaction, then CDC or a relay ships it to Kafka.

Read in post: Kafka in practice (2)
InterviewMidWhy not just send to Kafka inside the DB transaction?

Because Kafka doesn't take part in the DB transaction: the send succeeds, the commit fails, and the event is out while the DB rolls back.

The other way (send after commit), a crash between the two loses the event. On top of that, the DB transaction stays open while waiting on the broker.

Read in post: Kafka in practice (2)
InterviewMidWhat configuration makes producers and consumers lose nothing?

Producer: acks=all, idempotence on, retries within delivery.timeout.ms, topics with RF 3 and min.insync.replicas=2. Consumer: commit after processing, stable group.id.

Auto-commit is only safe when processing is synchronous in the poll loop. At-least-once comes with duplicates, so the consumer must be idempotent.

Read in post: Kafka in practice (2)
InterviewMidWhat are the downsides of the transactional outbox?

Added latency, an outbox table that grows unless cleaned, and only at-least-once, so consumers must tolerate duplicates.

With Debezium you can insert and delete in the same transaction because the connector reads the WAL. Monitor the connector: if it stops, events pile up in the WAL and the DB's disk fills.

Read in post: Kafka in practice (2)
InterviewSeniorKafka has exactly-once, so why must a consumer that writes to a DB still be idempotent?

Because Kafka's exactly-once only covers writes to Kafka and offset commits; the DB write sits outside that transaction.

A consumer that dies after the DB write but before committing the offset reprocesses the record. Fix: a unique constraint on the message ID in the same transaction as the side effect, or store offsets in the DB itself.

Read in post: Kafka in practice (2)
InterviewSeniorDesign it so an order's events are processed in order end to end.

Key = order_id, an idempotent producer, and a consumer that processes each partition sequentially; add a version check in the consumer as a defense.

Avoid what breaks order: adding partitions, non-blocking retry topics, several producers for one order. If events go through an outbox, order follows DB commit order, so updates to one order must lock its row.

Read in post: Kafka in practice (2)
InterviewSeniorOutbox, CDC on tables, event sourcing: which do you pick to publish events between services?

The outbox: the event is a business contract I define, written atomically with the state, and it still uses CDC to ship.

CDC on tables suits internal data sync (search, warehouse) because it exposes the table schema. Event sourcing is only worth it when the event history itself is the business (a ledger, an audit trail), given its complexity.

Read in post: Kafka in practice (2)
Edge caseSeniorsend() can block the calling thread for 60 seconds"Asynchronous" only holds while things are healthy. send() blocks when: The topic's metadata is missing (brokers unreachable, topic doesn't exist). buffer.memory (default 32 MB) is full because the brokers are slower than your writes. Both wait up to max.block.ms (default 60,000 ms) and then throw TimeoutException. Cal

"Asynchronous" only holds while things are healthy. send() blocks when:

  • The topic's metadata is missing (brokers unreachable, topic doesn't exist).
  • buffer.memory (default 32 MB) is full because the brokers are slower than your writes.

Both wait up to max.block.ms (default 60,000 ms) and then throw TimeoutException. Call send() on an HTTP worker thread and a broker incident drains your web server's thread pool. Stay safe: lower max.block.ms for SLA-bound paths (say 1–2 s), watch buffer-available-bytes, and have a plan for failed sends (outbox, a 503).

Read in post: Inside the Kafka producer
Edge caseMidDoing heavy work inside the producer callbackCallbacks (and whenComplete on Spring KafkaTemplate's CompletableFuture) run on the sender thread. A database write or HTTP call there makes every other batch of that producer wait. A callback should log, bump a metric, or hand work to another executor.

Callbacks (and whenComplete on Spring KafkaTemplate's CompletableFuture) run on the sender thread. A database write or HTTP call there makes every other batch of that producer wait. A callback should log, bump a metric, or hand work to another executor.

Read in post: Inside the Kafka producer
Trade-offSeniorChoosing a producer compression codeclz4: fastest to compress and decompress, moderate ratio. The safe default for latency-sensitive flows. zstd: ratio close to gzip, much faster. Good for high-volume topics where you pay for bandwidth or storage (logs, CDC, analytics). snappy: similar to lz4, common in older systems. gzip: good ratio but the most CPU; li
  • lz4: fastest to compress and decompress, moderate ratio. The safe default for latency-sensitive flows.
  • zstd: ratio close to gzip, much faster. Good for high-volume topics where you pay for bandwidth or storage (logs, CDC, analytics).
  • snappy: similar to lz4, common in older systems.
  • gzip: good ratio but the most CPU; little reason to pick it now that zstd exists.
  • Keep the topic at compression.type=producer (default) so the broker stores batches as they arrive. A different codec on the topic forces the broker to decompress and recompress, burning CPU and losing zero-copy.
Read in post: Inside the Kafka producer
Edge caseMidDefaultPartitioner and UniformStickyPartitioner are deprecatedOld code often sets partitioner.class=...DefaultPartitioner or UniformStickyPartitioner. Since Kafka 3.3 both are deprecated and switch off the slow-broker avoidance. The right move: leave partitioner.class unset to get the built-in logic. To spread keyed records as if they had no key, use partitioner.ignore.keys=true.

Old code often sets partitioner.class=...DefaultPartitioner or UniformStickyPartitioner. Since Kafka 3.3 both are deprecated and switch off the slow-broker avoidance. The right move: leave partitioner.class unset to get the built-in logic. To spread keyed records as if they had no key, use partitioner.ignore.keys=true. Write a custom partitioner only for a real business rule (for example isolating one huge tenant).

Read in post: Inside the Kafka producer
Edge caseSeniorThe "expired" error comes from delivery.timeout.ms, not retriesDuring a long broker outage the callback gets TimeoutException: Expiring N record(s) ... has passed since batch creation. The record sat in the accumulator longer than delivery.timeout.ms, even if it was never retried. Raising retries changes nothing. To ride out longer outages, raise delivery.timeout.ms (and give buff

During a long broker outage the callback gets TimeoutException: Expiring N record(s) ... has passed since batch creation. The record sat in the accumulator longer than delivery.timeout.ms, even if it was never retried. Raising retries changes nothing. To ride out longer outages, raise delivery.timeout.ms (and give buffer.memory room for the backlog); to fail fast, lower it.

Read in post: Inside the Kafka producer
Edge caseSeniorA long-open transaction freezes read_committed consumersThe LSO can't move past an open transaction, so every readcommitted consumer on that partition stops, even for records from other producers committed after it. Lag climbs while consumers report no errors. Usual causes: a producer stuck mid-transaction (long GC, waiting on a DB), or a dead producer whose transactional.i

The LSO can't move past an open transaction, so every read_committed consumer on that partition stops, even for records from other producers committed after it. Lag climbs while consumers report no errors. Usual causes: a producer stuck mid-transaction (long GC, waiting on a DB), or a dead producer whose transactional.id nobody reuses.

The bound is transaction.timeout.ms (default 60 s), after which the coordinator aborts. Keep transactions short (hundreds of ms to 1 s), monitor the partition's LastStableOffsetLag, and use kafka-transactions.sh find-hanging / abort for hung transactions.

Read in post: Inside the Kafka producer
Trade-offSeniorA stable transactional.id or a random oneStable per role (for example payment-relay-0, tied to a StatefulSet pod): a new instance fences the old one (the zombie) and finishes its open transaction. That is the whole point of transactional.id. Random per start: no name clashes when scaling, but no fencing, and a dead instance's open transaction waits for the ti
  • Stable per role (for example payment-relay-0, tied to a StatefulSet pod): a new instance fences the old one (the zombie) and finishes its open transaction. That is the whole point of transactional.id.
  • Random per start: no name clashes when scaling, but no fencing, and a dead instance's open transaction waits for the timeout.
  • Since Kafka 2.5 (KIP-447), fencing in consume-transform-produce relies on the consumer group metadata passed to sendOffsetsToTransaction, so you no longer need one transactional.id per input partition. Spring Kafka uses transactionIdPrefix plus a suffix per producer.
Read in post: Inside the Kafka producer
TILSeniorKafka 4.0 bumps the epoch after every transaction (KIP-890)Before, a "stray" batch from an old transaction (a slow retry) could land in the producer's next transaction, causing hanging transactions or mixed data. KIP-890 (Kafka 4.0) has the coordinator bump the epoch after every transaction and the broker verify that a partition joined the transaction. A stray batch with an ol

Before, a "stray" batch from an old transaction (a slow retry) could land in the producer's next transaction, causing hanging transactions or mixed data. KIP-890 (Kafka 4.0) has the coordinator bump the epoch after every transaction and the broker verify that a partition joined the transaction. A stray batch with an old epoch is rejected, like the InvalidProducerEpochException in the lab.

Read in post: Inside the Kafka producer
InterviewJuniorIs KafkaProducer.send() synchronous?

No: it puts the record in a buffer and returns a Future immediately; a background thread sends batches. But it can block when metadata is missing or the buffer is full.

To wait for the result, use send().get() (slow, defeats batching) or a callback. Spring's KafkaTemplate.send() returns a CompletableFuture; send errors live in the future, so a try/catch around the call doesn't catch them.

Read in post: Inside the Kafka producer
InterviewJuniorWhich partition does a keyless record go to?

The producer sticks to one partition until it has sent about a batch, then moves to another (sticky), so the spread is even over time but bursty over short windows.

Before Kafka 2.4 it was round-robin per record. Since 3.3 the next partition is also weighted toward less loaded brokers.

Read in post: Inside the Kafka producer
InterviewMidHow do linger.ms and batch.size interact?

A batch is sent when it reaches batch.size or has waited linger.ms, whichever comes first.

Under high load batches fill first and linger costs almost no latency. Under low load linger decides; my lab at 5,000 msg/s took 14,333 requests with linger 0 and 554 with linger 5. The default linger is 5 ms since Kafka 4.0.

Read in post: Inside the Kafka producer
InterviewMidWhat do you set retries to on a producer?

Leave the default (Integer.MAX_VALUE) and bound it with delivery.timeout.ms, because what you control is how long you tolerate an incident, not how many attempts.

Alongside: idempotence on so retries don't duplicate or reorder, and a callback that handles non-retriable errors (record too large, no permission) and the TimeoutException on expiry.

Read in post: Inside the Kafka producer
InterviewMidWhy shouldn't the topic use a different compression codec from the producer?

The broker would have to decompress and recompress every batch, burning CPU and losing zero-copy; with compression.type=producer the broker stores batches as they are.

Pick the codec on the producer: lz4 for latency, zstd for ratio. Consumers decompress using the codec recorded in each batch, no config needed.

Read in post: Inside the Kafka producer
InterviewSeniorExplain how Kafka transactions work underneath.

A producer with a transactional.id gets a PID and epoch from the coordinator; the coordinator logs state in __transaction_state; on commit it writes COMMIT markers into every participating partition, and read_committed consumers read only up to the LSO.

  • initTransactions() bumps the epoch, fences the old instance and completes any open transaction.
  • Each new partition in the transaction is registered with the coordinator; consumer offsets go through sendOffsetsToTransaction.
  • Commit is two-phase: PREPARE_COMMIT in the coordinator's log (the point of no return), then the markers.
  • Cost: extra round trips, markers take offsets, and open transactions block read_committed consumers.
Read in post: Inside the Kafka producer
InterviewSeniorWhat is a zombie producer and how does Kafka stop it?

A zombie is an old instance that thinks it's still alive (say after a long GC pause) while a new one has replaced it; Kafka stops it with an epoch tied to the transactional.id.

The new instance's initTransactions() bumps the epoch; every request from the old instance carries a lower epoch and is rejected (ProducerFencedException / InvalidProducerEpochException). So transactional.id must be stable per role, not random.

Read in post: Inside the Kafka producer
InterviewSeniorConsumer lag is growing but the consumer reports no errors, and the topic is transactional. What do you suspect?

An open (or hung) transaction is holding the LSO, so read_committed consumers can't move on even though new data exists.

Check: compare the LSO with the high watermark (LastStableOffsetLag), run kafka-transactions.sh find-hanging --broker-id N. Fix: find the producer holding the transaction, lower transaction.timeout.ms, abort the hung transaction with the tool.

Read in post: Inside the Kafka producer
InterviewSeniorsend() hangs for 60 seconds when the cluster is down. How do you redesign?

Lower max.block.ms on synchronous paths, isolate with a bulkhead, and ideally decouple the Kafka write from the request with an outbox.

send() blocks on metadata or a full buffer.memory. Watch buffer-available-bytes and record-queue-time-avg to see it coming; an outbox turns a Kafka incident into delay instead of API errors.

Read in post: Inside the Kafka producer
Trade-offMidMetadata in the JSON envelope or in Kafka headersIn the envelope (body): self-describing, travels with the message everywhere (files, S3, logs), easy to debug. But routing or filtering means deserialising the whole body, and everyone must share the envelope library. In Kafka headers: readable without parsing the payload, understood by frameworks (Spring puts kafkacor
  • In the envelope (body): self-describing, travels with the message everywhere (files, S3, logs), easy to debug. But routing or filtering means deserialising the whole body, and everyone must share the envelope library.
  • In Kafka headers: readable without parsing the payload, understood by frameworks (Spring puts kafka_correlationId and kafka_replyTopic there), and the payload stays a pure business schema. But headers are easily dropped when data leaves Kafka (connectors, exports) unless configured to be kept.
  • In practice, both: correlation id, reply topic and trace context (traceparent) in headers; business data and ids in the body.
Read in post: Case study
Edge caseMidCommands and events share one topicEvery consumer has to parse the envelope and branch on type; consumers that only want events still receive and discard commands. Retention, partition count and ACLs can't be tuned per kind, although a command is worthless after a few seconds and an event may need to be kept for weeks. Split them: wallet.fund-transferre

Every consumer has to parse the envelope and branch on type; consumers that only want events still receive and discard commands. Retention, partition count and ACLs can't be tuned per kind, although a command is worthless after a few seconds and an event may need to be kept for weeks. Split them: wallet.fund-transferred (event, many consumers), fraud-check.commands (command, one owner), fraud-check.replies for results.

Read in post: Case study
Edge caseSeniorAn uncapped backoff turns a 2.6-second reply into a 5.1-second oneMeasured: a reply ready at 2,600 ms is seen at 5,105 ms; null comes back at 327,665 ms without a poll after the last one at 163,825 ms. Fix: a separate business timeout (a few hundred ms to 2 s), a capped backoff, or better, no polling at all (CompletableFuture, BLPOP with a timeout, ReplyingKafkaTemplate), and always

Measured: a reply ready at 2,600 ms is seen at 5,105 ms; null comes back at 327,665 ms without a poll after the last one at 163,825 ms. Fix: a separate business timeout (a few hundred ms to 2 s), a capped backoff, or better, no polling at all (CompletableFuture, BLPOP with a timeout, ReplyingKafkaTemplate), and always check one last time before reporting a timeout.

Read in post: Case study
Edge caseSeniorA fraud-check timeout becomes an empty HTTP 200On timeout, sendSync returns null, getPayload() throws an NPE, catch (Exception e) swallows it, logs "Failed to produce" (the wrong cause: the send succeeded) and returns null; the controller answers an empty 200. Suspicious payments go through exactly when fraud detection is in trouble. Fix: a three-state result (APPR

On timeout, sendSync returns null, getPayload() throws an NPE, catch (Exception e) swallows it, logs "Failed to produce" (the wrong cause: the send succeeded) and returns null; the controller answers an empty 200. Suspicious payments go through exactly when fraud detection is in trouble. Fix: a three-state result (APPROVED, REJECTED, UNKNOWN), timeout as an explicit outcome, and a policy for UNKNOWN decided by the business.

Read in post: Case study
Trade-offSeniorFail open or fail closed when the fraud check doesn't answerFail open (let it through): users aren't affected, but a fraudster only needs to wait for (or cause) an outage. Fits small, low-risk payments. Fail closed (block): money is safe, but an outage in a supporting service becomes an outage of the whole payment flow. In between: let payments through below a limit (say 500,00
  • Fail open (let it through): users aren't affected, but a fraudster only needs to wait for (or cause) an outage. Fits small, low-risk payments.
  • Fail closed (block): money is safe, but an outage in a supporting service becomes an outage of the whole payment flow.
  • In between: let payments through below a limit (say 500,000 VND) or for users with a good history, put the rest into PENDING_REVIEW and re-check when fraud-detection is back. This is a business decision and must be written down (an ADR), not a return null in a catch.
Read in post: Case study
Edge caseMidtry/catch around kafkaTemplate.send() doesn't see send failuresKafkaTemplate.send (Spring Kafka 3.x) returns a CompletableFuture<SendResult<K, V; KafkaProducer.send only throws immediately for serialisation errors or waiting for metadata longer than max.block.ms. Later failures (delivery.timeout.ms expiring, NotEnoughReplicasException, missing permissions) live in the future. Hand

KafkaTemplate.send (Spring Kafka 3.x) returns a CompletableFuture<SendResult<K, V>>; KafkaProducer.send only throws immediately for serialisation errors or waiting for metadata longer than max.block.ms. Later failures (delivery.timeout.ms expiring, NotEnoughReplicasException, missing permissions) live in the future. Handle them with whenComplete((result, ex) -> …) or .get(timeout); in request-reply, complete the pending future exceptionally.

Read in post: Case study
Edge caseMidexceptionally after whenComplete receives a CompletionException, not a TimeoutExceptionorTimeout(...) completes the future with a TimeoutException, but the stage created by .whenComplete(...) passes it downstream wrapped in a CompletionException. So ex instanceof TimeoutException is always false; my first run returned ERROR-HOLD instead of TIMEOUT-HOLD because of this. Always unwrap ex.getCause() when ex

orTimeout(...) completes the future with a TimeoutException, but the stage created by .whenComplete(...) passes it downstream wrapped in a CompletionException. So ex instanceof TimeoutException is always false; my first run returned ERROR->HOLD instead of TIMEOUT->HOLD because of this. Always unwrap ex.getCause() when ex is a CompletionException before classifying.

Read in post: Case study
Trade-offSeniorOne group per instance or one partition per instance for the reply topicOne group per instance (setSharedReplyTopic(true)): nothing else to configure, autoscaling just works. But every instance reads every reply: N instances mean N times the read traffic, and every scale-up leaves a group with stale offsets behind. One partition per instance (the KafkaHeaders.REPLYPARTITION header, a consu
  • One group per instance (setSharedReplyTopic(true)): nothing else to configure, autoscaling just works. But every instance reads every reply: N instances mean N times the read traffic, and every scale-up leaves a group with stale offsets behind.
  • One partition per instance (the KafkaHeaders.REPLY_PARTITION header, a consumer with a fixed assign()): each reply is read once. But you need a stable identity (a StatefulSet ordinal), at least as many partitions as the maximum number of instances, and when an instance dies nobody reads its replies (acceptable, since its requests died with it).
  • A reply topic per instance also works, but creating and deleting topics with the pod lifecycle is an operational burden.
Read in post: Case study
Trade-offSeniorOutbox with a polling relay or with CDC (Debezium)Polling relay: just the database and a job, easy to debug. Latency equals the poll interval (100 ms–1 s), a steady query load, and the outbox table needs cleaning up. CDC: low latency, no extra queries, commit order preserved. But you add Kafka Connect + Debezium, and a forgotten PostgreSQL replication slot retains WAL
  • Polling relay: just the database and a job, easy to debug. Latency equals the poll interval (100 ms–1 s), a steady query load, and the outbox table needs cleaning up.
  • CDC: low latency, no extra queries, commit order preserved. But you add Kafka Connect + Debezium, and a forgotten PostgreSQL replication slot retains WAL until the disk fills up.
  • Both are at-least-once, so idempotent consumers are mandatory. Start with polling; move to CDC when latency or query load becomes a problem.
Read in post: Case study
Trade-offSeniorShould you do synchronous request-reply over Kafka?Avoid it when: you can call the other side directly over HTTP/gRPC; a user is waiting with a budget of a few hundred milliseconds; there is only one receiver. Acceptable when: the other side only speaks Kafka (a legacy system, another team); you need a buffer when it's overloaded; you want the command stream kept for a
  • Avoid it when: you can call the other side directly over HTTP/gRPC; a user is waiting with a budget of a few hundred milliseconds; there is only one receiver.
  • Acceptable when: the other side only speaks Kafka (a legacy system, another team); you need a buffer when it's overloaded; you want the command stream kept for audit or replay. Then use ReplyingKafkaTemplate or per-instance reply partitions, a short timeout, and an explicit UNKNOWN outcome.
  • Best when the product can change: an asynchronous UX (202 + status + push), letting Kafka do what it's good at.
Read in post: Case study
InterviewJuniorWhat's the difference between an event and a command?

An event reports something that happened and waits for no answer; a command asks one specific party to do something and usually needs a result.

An event (FundTransferred) is immutable and the sender doesn't know who listens. A command (CheckFraud) has one owner and can be rejected. Their lifetime, ownership and number of consumers differ, so they usually live in different topics.

Read in post: Case study
InterviewJuniorWhat is a correlation id for in request-reply?

To match a reply with the request that is waiting for it.

The caller generates a unique id, sends it with the request (usually in a header), and the responder copies it verbatim into the reply. The caller keeps an id → future map (or a key in a shared store) and completes the future when a reply with a matching id arrives.

Read in post: Case study
InterviewMidSeveral instances wait for replies over Kafka — how does each reply reach the right instance?

Three ways: a consumer group per instance, a reply partition per instance, or a shared group plus a shared correlation store.

  1. A separate consumer group per instance on the reply topic, each receiving every reply and discarding the rest: simple, N times the reads.
  2. Each instance owns a reply partition, the request carries a reply-partition header, and the instance reads it with assign(): efficient, needs a stable identity.
  3. A shared group plus a correlation store such as Redis (whoever receives the reply writes it, the waiting instance reads it): one more system on the critical path.
Read in post: Case study
InterviewMidWhat is a dual write and how does the outbox solve it?

A dual write is writing to the database and Kafka without a shared transaction; the outbox writes both into the database in one transaction and a relay sends to Kafka.

Without a shared transaction, one side can succeed while the other fails. With the outbox, a relay (polling or CDC) reads the outbox table and sends. The result is at-least-once, so consumers must deduplicate by message id.

Read in post: Case study
InterviewMidYour servlet thread pool is exhausted by requests waiting for replies — what do you do?

Set a short business timeout, then stop blocking platform threads: go async in the controller or use virtual threads, and add a bulkhead and a circuit breaker.

  • Return a CompletableFuture/DeferredResult from the controller (Spring MVC supports async processing), or use virtual threads (Java 21, spring.threads.virtual.enabled=true) so waiting is cheap.
  • A bulkhead caps concurrent requests on this endpoint so it can't take others down.
  • A circuit breaker for when the other side keeps failing.
Read in post: Case study
InterviewSeniorWould you approve a synchronous fraud check over Kafka?

Not as a default: it adds two broker hops, a correlation store and temporal coupling, and the user still waits.

  • If fraud-detection can change: call it over HTTP/gRPC with a timeout and a circuit breaker, and still publish the event through the outbox for post-hoc scoring.
  • If it only speaks Kafka: ReplyingKafkaTemplate or per-instance reply partitions, a dedicated command topic, a 1–2 s timeout, and an UNKNOWN outcome with a clear policy.
  • If the product allows it: move to an asynchronous UX.
Read in post: Case study
InterviewSeniorThe fraud check times out — where does the payment go?

That's a business decision and must be written down; technically, the result needs a third state, UNKNOWN.

Options: fail closed (reject), fail open (accept), or a hybrid: accept below a limit or for trusted users, put the rest into PENDING_REVIEW and re-check when fraud-detection recovers. A timeout must never turn into null or "clean". Track the UNKNOWN rate as a risk metric.

Read in post: Case study
InterviewSeniorWhy is Kryo with setRegistrationRequired(false) a risk?

Because the data contains class names and Kryo instantiates any class on the classpath when reading — the same family of vulnerabilities as Java deserialisation.

Anyone who can write to Redis can make the service instantiate arbitrary classes. The format is also tied to the class layout, so a rolling deploy that changes a field leaves old and new instances unable to read each other's data. Use JSON with fixed types, or require class registration, and protect Redis with ACLs/TLS.

Read in post: Case study
InterviewSeniorThe outbox relay sends duplicates — does the idempotent producer help?

No; consumers have to deduplicate by message id.

If the relay dies after Kafka acks but before marking the rows as sent, that batch is sent again. The idempotent producer only deduplicates internal retries within the same producer session (PID + sequence number); it can't deduplicate two send calls from two sessions. A transactional producer can't join the database transaction either. Use a processed-message table with a unique constraint, in the same transaction as the business effect.

Read in post: Case study
Edge caseMidDeserializing to a String before parsing JSONA consumer that uses StringDeserializer and then calls objectMapper.readValue(str, Order.class) does two jobs: decode UTF-8 into a String (a copy), then parse again. With big messages and high throughput, that's double the garbage for the GC. The right way: a deserializer that reads straight from byte[] (objectMapper.r

A consumer that uses StringDeserializer and then calls objectMapper.readValue(str, Order.class) does two jobs: decode UTF-8 into a String (a copy), then parse again. With big messages and high throughput, that's double the garbage for the GC. The right way: a deserializer that reads straight from byte[] (objectMapper.readValue(bytes, Order.class)), or a ready-made one (Spring's JsonDeserializer, KafkaAvroDeserializer).

A worse version: the producer sends a String that is already JSON through JsonSerializer, so the value gets wrapped in another layer of quotes ("{\"id\":1}"). The consumer parses out a string, not an object.

Read in post: Kafka serialization and Schema Registry
Trade-offSeniorSchemaless JSON or Avro/Protobuf with Schema RegistrySchemaless JSON: no extra infrastructure, readable with kafka-console-consumer. But the contract only lives in the authors' heads; one producer changing amount from a number to a string breaks consumers at runtime, and nothing stops it beforehand. Avro/Protobuf + Registry: messages 2–3× smaller, schemas checked for com
  • Schemaless JSON: no extra infrastructure, readable with kafka-console-consumer. But the contract only lives in the authors' heads; one producer changing amount from a number to a string breaks consumers at runtime, and nothing stops it beforehand.
  • Avro/Protobuf + Registry: messages 2–3× smaller, schemas checked for compatibility at registration (a bad deploy fails on the producer, not on the consumers). The cost is one more service to run (the Registry must be highly available) and tooling that understands schemas for debugging.
  • Middle ground: JSON Schema in the Registry. JSON stays readable and gets compatibility checks; messages stay big.
Read in post: Kafka serialization and Schema Registry
Edge caseSeniorLeaving auto.register.schemas=true in productionBy default the serializer registers whatever schema it's using. A broken build (an accidental field change) will register a new version if it's technically compatible even when it's wrong for the business, or get rejected mid-flight if it isn't. In production: auto.register.schemas=false, use.latest.version=true, and r

By default the serializer registers whatever schema it's using. A broken build (an accidental field change) will register a new version if it's technically compatible even when it's wrong for the business, or get rejected mid-flight if it isn't. In production: auto.register.schemas=false, use.latest.version=true, and register schemas from CI (the Registry's Maven/Gradle plugin) with a compatibility check before merge.

Read in post: Kafka serialization and Schema Registry
Edge caseSeniorBACKWARD only compares with the previous versionv1 → v2 adds note with a default (valid). v2 → v3 drops the default from note: against v2 it's still BACKWARD (v2 data always has note). The lab confirms it: v3 against v2 is true, but v3 against both v1 and v2 under BACKWARDTRANSITIVE is false. A v3 consumer rereading v1 messages still in the topic (30-day retention,

v1 → v2 adds note with a default (valid). v2 → v3 drops the default from note: against v2 it's still BACKWARD (v2 data always has note). The lab confirms it: v3 against v2 is true, but v3 against both v1 and v2 under BACKWARD_TRANSITIVE is false. A v3 consumer rereading v1 messages still in the topic (30-day retention, or a compacted topic) will fail. Topics that keep data for long should use BACKWARD_TRANSITIVE or FULL_TRANSITIVE.

Read in post: Kafka serialization and Schema Registry
Trade-offSeniorBACKWARD or FULL for a shared event topicBACKWARD: flexible for producers (they may remove fields), but every consumer must upgrade before the producer. With 6 teams reading the topic, that's deploy-schedule coordination. FULL: only fields with defaults may be added or removed, but producers and consumers deploy independently in any order. I pick FULLTRANSITI
  • BACKWARD: flexible for producers (they may remove fields), but every consumer must upgrade before the producer. With 6 teams reading the topic, that's deploy-schedule coordination.
  • FULL: only fields with defaults may be added or removed, but producers and consumers deploy independently in any order.
  • I pick FULL_TRANSITIVE for topics shared across teams, and BACKWARD for one team's internal topics (it controls its own deploy order).
  • A truly breaking change (a field's meaning, the key) is beyond any mode: create a new topic (orders.v2), dual-write for a while, migrate consumers gradually.
Read in post: Kafka serialization and Schema Registry
Edge caseMidThe __TypeId__ header forces consumers to use the producer's class nameThe producer sends com.shop.order.OrderPaid; the billing service has com.shop.billing.OrderPaidEvent. With default settings, JsonDeserializer reads the header and tries to load com.shop.order.OrderPaid: "class not in trusted packages" or ClassNotFoundException. A package rename in the producer during a refactor breaks

The producer sends com.shop.order.OrderPaid; the billing service has com.shop.billing.OrderPaidEvent. With default settings, JsonDeserializer reads the header and tries to load com.shop.order.OrderPaid: "class not in trusted packages" or ClassNotFoundException. A package rename in the producer during a refactor breaks every consumer too. Fix: turn off type headers on the producer and set a default type on the consumer (as in the YAML above), or use spring.json.type.mapping to map logical names (orderPaid:com.shop.billing.OrderPaidEvent). Don't set trusted.packages: "*" for outside data: that's a door for deserialization attacks.

Read in post: Kafka serialization and Schema Registry
InterviewJuniorWhat does Kafka store, and who turns objects into bytes?

The broker stores only bytes; the producer's serializer turns key and value into bytes, and the consumer's deserializer does the reverse.

Kafka has no default serializer and doesn't check types. Both sides must agree on the format; a mismatch fails when the consumer reads.

Read in post: Kafka serialization and Schema Registry
InterviewJuniorWhy not deserialize to a String and then parse the JSON?

Because it costs an extra copy and decode per message; reading straight from bytes to an object is faster and makes less garbage.

Jackson can read directly from byte[], and Spring's JsonDeserializer already does this.

Read in post: Kafka serialization and Schema Registry
InterviewMidHow does Schema Registry work?

The producer registers a schema and gets an id; each message carries magic byte 0 plus a 4-byte id; the consumer looks up the id to get the schema and decode, with caching.

The Registry checks compatibility at registration and stores schemas in the _schemas topic. The default subject is <topic>-value.

Read in post: Kafka serialization and Schema Registry
InterviewMidHow do BACKWARD and FORWARD compatibility differ?

BACKWARD: the new schema reads old data, so upgrade consumers first. FORWARD: the old schema reads new data, so upgrade producers first.

FULL is both, so deploy order doesn't matter. Adding a field with a default passes all three.

Read in post: Kafka serialization and Schema Registry
InterviewMidHow do you add a required field to an Avro event?

You can't add it as "required" right away: add it with a default (or optional null), have producers fill in real values, and handle the default on consumers.

Adding a field without a default is rejected under BACKWARD because the new consumer has nothing to fill in when reading old messages.

Read in post: Kafka serialization and Schema Registry
InterviewSeniorHow do you choose the compatibility mode for a topic shared by many teams?

FULL_TRANSITIVE: fewer allowed changes, but teams deploy independently, and consumers can reread every version still in the topic.

BACKWARD forces every consumer to upgrade before the producer; without transitive, data older than one version may be unreadable. Truly breaking changes go to a new topic.

Read in post: Kafka serialization and Schema Registry
InterviewSeniorWhat happens when Schema Registry goes down?

Running producers and consumers keep working with cached schemas; newly started instances, new schemas, or unseen ids fail.

So run the Registry with several instances (one leader for writes, others serving reads), and don't roll out new schemas during a Registry incident. Turning off auto-register means producers don't need to write to the Registry at runtime.

Read in post: Kafka serialization and Schema Registry
InterviewSeniorJSON or Avro for a new event platform?

If many teams read and topics live long: Avro or Protobuf with a Registry, because the contract is checked before deploy and messages are 2–3× smaller. One team, few consumers: JSON is fine.

My measurement: the same order is 85 bytes in JSON versus 29 bytes in Avro. The bigger win is that compatibility errors are stopped at the producer instead of breaking consumers at runtime.

Read in post: Kafka serialization and Schema Registry
Trade-offSeniorOver-provision partitions up front or size them just rightOver-provisioning avoids adding partitions later (so no key reshuffle) and leaves room to scale consumers. The price: each partition costs file handles and memory on brokers and clients, rebalances and leader elections get slower, and end-to-end latency rises slightly with acks=all. Just right is cheaper, but the first

Over-provisioning avoids adding partitions later (so no key reshuffle) and leaves room to scale consumers. The price: each partition costs file handles and memory on brokers and clients, rebalances and leader elections get slower, and end-to-end latency rises slightly with acks=all.

Just right is cheaper, but the first increase reshuffles keys. The course quotes Confluent's guidance: up to about 4,000 partitions per broker and 200,000 per cluster (ZooKeeper-era numbers; KRaft raises the cluster ceiling). I over-provision about 2× expected peak for keyed topics that need ordering, and size unkeyed topics just right.

Read in post: Kafka in practice (1)
Edge caseMidMore partitions don't speed up consumers when the database is the bottleneckRead-heavy topics usually bottleneck on the DB or API behind them. Adding partitions and consumers just piles more connections onto an overloaded DB: lag doesn't drop and the DB gets slower. Measure where a record's processing time actually goes before adding partitions.

Read-heavy topics usually bottleneck on the DB or API behind them. Adding partitions and consumers just piles more connections onto an overloaded DB: lag doesn't drop and the DB gets slower. Measure where a record's processing time actually goes before adding partitions.

Read in post: Kafka in practice (1)
Edge caseMidA group on a new topic has no old offsetsOffsets belong to a (group, topic, partition) triple, so the old topic's offsets mean nothing on the new one. If you don't choose a starting point deliberately, the default auto.offset.reset=latest skips everything that was copied. Write the starting point into the migration runbook.

Offsets belong to a (group, topic, partition) triple, so the old topic's offsets mean nothing on the new one. If you don't choose a starting point deliberately, the default auto.offset.reset=latest skips everything that was copied. Write the starting point into the migration runbook.

Read in post: Kafka in practice (1)
Edge caseSeniorRaising session.timeout.ms doesn't save a long taskThe slides suggest raising session.timeout.ms along with max.poll.interval.ms. Since Kafka 0.10.1 (KIP-62), heartbeats run on a background thread, so a consumer busy processing still heartbeats on time. The limit you're actually hitting is max.poll.interval.ms. A larger session.timeout.ms only makes the group slower to

The slides suggest raising session.timeout.ms along with max.poll.interval.ms. Since Kafka 0.10.1 (KIP-62), heartbeats run on a background thread, so a consumer busy processing still heartbeats on time. The limit you're actually hitting is max.poll.interval.ms. A larger session.timeout.ms only makes the group slower to notice a consumer that really died.

Read in post: Kafka in practice (1)
Trade-offSeniorTune liveness or split into a pipeline for long tasksLiveness tuning fits when processing time is stable and only slightly over the limit: set max.poll.records so that records × worst-case time per record stays well below max.poll.interval.ms. A pipeline fits when processing time varies a lot or the process has several steps calling external systems: each stage is short,

Liveness tuning fits when processing time is stable and only slightly over the limit: set max.poll.records so that records × worst-case time per record stays well below max.poll.interval.ms. A pipeline fits when processing time varies a lot or the process has several steps calling external systems: each stage is short, and a failure is retried at its own stage. Commit-first async is only for data you can afford to lose (logs, metrics).

Read in post: Kafka in practice (1)
InterviewJuniorWhat is consumer lag and how do you measure it?

It's the gap between a partition's end offset and the group's committed offset; measure it with kafka-consumer-groups --describe or the records-lag-max metric.

Also track time lag (how many seconds the consumer is behind the producer) because it's easier to put an SLO on. Lag approaching retention means data loss is coming.

Read in post: Kafka in practice (1)
InterviewJuniorCan you reduce a topic's partition count?

No. Create a smaller topic, copy the data (MirrorMaker 2), then move producers and consumers over.

When moving consumers, choose the starting point on the new topic explicitly (latest, earliest, or the cutover timestamp) and accept re-reading a stretch, so consumers must be idempotent.

Read in post: Kafka in practice (1)
InterviewMidYou need to send a 50 MB file through Kafka. How?

Use a claim check: upload the file to object storage and send a message with the object key, size and checksum.

Raising max.message.bytes to ~10 MB is still an anti-pattern: slower replication, memory-hungry consumers, big records blocking small ones behind them. Upload first, then send the message, and use a lifecycle rule to clean up orphaned files.

Read in post: Kafka in practice (1)
InterviewMidLag is growing. Do you add consumers right away?

No. Find the cause first: a produce spike, slower per-record processing, constant rebalances, GC.

More consumers only help if consumers are the bottleneck and some partitions have no reader. If the DB behind them is saturated, more consumers make it worse.

Read in post: Kafka in practice (1)
InterviewMidOne record always makes the consumer throw. What happens and how do you handle it?

With unlimited retries, that partition is stuck at that offset and lag grows forever. Retry a few times with backoff, then publish it to a dead letter topic.

Separate transient errors (retry) from permanent ones (straight to the DLT). Deserialization errors happen before the listener, so wrap the deserializer in ErrorHandlingDeserializer. The DLT needs alerts and a replay tool.

Read in post: Kafka in practice (1)
InterviewSeniorHow do you choose the partition count for a new payments topic?

Compute both directions and take the larger: write throughput / ~10 MB/s per partition, and peak TPS / one consumer's TPS measured by a load test. Then add about 2× headroom.

Payment topics usually bottleneck on reads (DB, ledger), so the load test decides. Since we need per-account ordering, I over-provision up front so we never have to add partitions later and reshuffle keys. Choose numbers like 12, 16, 24 that divide evenly across instances.

Read in post: Kafka in practice (1)
InterviewSeniorA consumer needs 6–10 minutes per record. How do you design it?

Don't make Kafka keep the consumer alive for the whole job: split it into short pipeline stages, or let Kafka carry commands while jobs run on workers with state in a DB.

Tuning max.poll.interval.ms with max.poll.records=1 works but is fragile, and blocks the whole partition while processing. Commit-first async loses at-least-once. Pausing partitions and polling regularly keeps at-least-once but needs careful revocation handling.

Read in post: Kafka in practice (1)
InterviewSeniorOne merchant is 40% of traffic and its partition always lags. What do you do?

That's a hot partition from a skewed key; more partitions won't help. Split the hot key (add a suffix to spread it) or route it to its own topic and consumers.

Spreading the key loses ordering for that merchant, so ask the business first: if ordering is needed per order rather than per merchant, change the key to order_id. Batching writes for the hot key also speeds the consumer up.

Read in post: Kafka in practice (1)
Edge caseSeniorZero-copy is disabled with TLS or when the broker has to recompresssendfile only moves bytes untouched. Two cases force data through user space, so zero-copy is lost: Client connections use TLS: the broker must encrypt inside the JVM. The broker must decompress and recompress: the topic's compression.type differs from the producer's codec (say the producer sends lz4 and the topic forc

sendfile only moves bytes untouched. Two cases force data through user space, so zero-copy is lost:

  • Client connections use TLS: the broker must encrypt inside the JVM.
  • The broker must decompress and recompress: the topic's compression.type differs from the producer's codec (say the producer sends lz4 and the topic forces zstd), or messages must be converted for old clients.

Consequences: broker CPU rises noticeably with TLS, so budget for it. Keep the topic at compression.type=producer so the broker stores batches as they arrive.

Read in post: Why Kafka is fast and durable
TILMidJava has zero-copy built in via FileChannel.transferToOn Linux the JDK implements FileChannel.transferTo(position, count, socketChannel) with the sendfile syscall, so an ordinary Java application can send a file without copying it through the heap. Kafka uses exactly this API to serve fetch requests on unencrypted connections. It's also why Kafka wants a large page cache

On Linux the JDK implements FileChannel.transferTo(position, count, socketChannel) with the sendfile syscall, so an ordinary Java application can send a file without copying it through the heap. Kafka uses exactly this API to serve fetch requests on unencrypted connections. It's also why Kafka wants a large page cache (RAM outside the JVM heap), while the broker heap itself usually needs only about 6 GB.

Read in post: Why Kafka is fast and durable
Edge caseSeniorSetting log.flush.interval.messages=1 "for durability" is usually the wrong leverAn fsync after every message makes I/O synchronous and throughput collapses, yet it still doesn't save you if the broker's disk dies. Durability should come from replication: replication.factor=3, min.insync.replicas=2, producers with acks=all, replicas across racks/AZs (broker.rack). Only consider explicit flushing wi

An fsync after every message makes I/O synchronous and throughput collapses, yet it still doesn't save you if the broker's disk dies. Durability should come from replication: replication.factor=3, min.insync.replicas=2, producers with acks=all, replicas across racks/AZs (broker.rack). Only consider explicit flushing with a single broker, or when regulations require data on disk before the ack; measure throughput before and after.

Read in post: Why Kafka is fast and durable
Trade-offSeniorA larger linger.ms: more throughput, more latencylinger.ms=0: send as soon as the I/O thread is free. Lowest latency, but small batches, many requests, more CPU and network per record. linger.ms of 5–20 ms: fuller batches, better compression, fewer requests, noticeably higher throughput; each record waits at most a few ms more. A batch that reaches batch.size is sent
  • linger.ms=0: send as soon as the I/O thread is free. Lowest latency, but small batches, many requests, more CPU and network per record.
  • linger.ms of 5–20 ms: fuller batches, better compression, fewer requests, noticeably higher throughput; each record waits at most a few ms more.
  • A batch that reaches batch.size is sent at once without waiting for linger.ms. So under heavy load linger costs almost no latency; it only matters when traffic is light.
  • Throughput-first ingestion: larger linger, 32–64 KB batch.size. Interactive flows that care about latency: small linger. Post 3 has a table of values per goal.
Read in post: Why Kafka is fast and durable
Edge caseSeniorAdding partitions moves keys and breaks per-key orderingThe partition is hash(key) % partition count, so going from 6 to 8 partitions moves most keys (in the experiment, acc-1 went from 3 to 5). Old acc-1 records stay in partition 3, new ones go to partition 5; a consumer may process the new ones before the old ones, and key-based state stores (Kafka Streams) drift. Kafka a

The partition is hash(key) % partition count, so going from 6 to 8 partitions moves most keys (in the experiment, acc-1 went from 3 to 5). Old acc-1 records stay in partition 3, new ones go to partition 5; a consumer may process the new ones before the old ones, and key-based state stores (Kafka Streams) drift. Kafka also won't let you reduce the partition count.

How to avoid it: provision partitions for the next 1–2 years. If you must grow, do it when traffic is quiet and let consumers drain the old records, or create a new topic and migrate.

Read in post: Why Kafka is fast and durable
Trade-offSeniorMore partitions: more throughput and parallelism, at a priceGain: more parallel consumers, more even writes. Rough formula: partitions ≥ max(target throughput / per-partition producer throughput, target throughput / per-consumer throughput). For 1 GB/s with consumers at 50 MB/s each → at least 20 partitions. Price: each partition means open segment and index files on the broker
  • Gain: more parallel consumers, more even writes. Rough formula: partitions ≥ max(target throughput / per-partition producer throughput, target throughput / per-consumer throughput). For 1 GB/s with consumers at 50 MB/s each → at least 20 partitions.
  • Price: each partition means open segment and index files on the broker. Followers replicate more, and commits slow down when many partitions sit between one pair of brokers. The producer keeps a batch per partition, so more memory and smaller batches. Rebalances and leader elections after a broker failure take longer.
  • You can't shrink, and growing breaks per-key ordering. Size for future load: typically a few dozen partitions for an important topic, not thousands. The detailed sizing, and how to move to a new topic when you need fewer: partition count, lag and long-running tasks.
Read in post: Why Kafka is fast and durable
Edge caseSeniormin.insync.replicas only applies to acks=allIn the experiment, topic strict (min.insync.replicas=3, 2 replicas in the ISR) still accepted writes from an acks=1 producer: the broker only checks the ISR size for acks=all requests. A topic with min.insync.replicas=2 gives a service still on acks=1 no protection at all. Three settings must go together: replication.f

In the experiment, topic strict (min.insync.replicas=3, 2 replicas in the ISR) still accepted writes from an acks=1 producer: the broker only checks the ISR size for acks=all requests. A topic with min.insync.replicas=2 gives a service still on acks=1 no protection at all. Three settings must go together: replication.factor=3, min.insync.replicas=2 on the topic/broker, and acks=all on every producer writing to the topic.

Read in post: Why Kafka is fast and durable
Edge caseSeniorThe application sees TimeoutException, not NotEnoughReplicasExceptionNotEnoughReplicasException is retriable, so the Java producer keeps retrying until delivery.timeout.ms runs out (2 minutes by default). In the experiment the callback got TimeoutException: Expiring 1 record(s) ... ms has passed since batch creation, not the root cause, so dashboards show "timeouts" and people blame the

NotEnoughReplicasException is retriable, so the Java producer keeps retrying until delivery.timeout.ms runs out (2 minutes by default). In the experiment the callback got TimeoutException: Expiring 1 record(s) ... ms has passed since batch creation, not the root cause, so dashboards show "timeouts" and people blame the network. To see the real error: watch broker metrics (UnderMinIsrPartitionCount, UnderReplicatedPartitions) and producer WARN logs. Set delivery.timeout.ms from your SLA rather than leaving the default.

Read in post: Why Kafka is fast and durable
Trade-offSeniorRF=3 with min.insync.replicas of 2 or 3min.insync.replicas=2: survives one broker failure and keeps accepting acks=all writes; every acknowledged record lives on at least 2 machines. The standard setting for important data. min.insync.replicas=3: every record is on all 3 machines, but one broker failing or lagging (even during a rolling restart for an upgra
  • min.insync.replicas=2: survives one broker failure and keeps accepting acks=all writes; every acknowledged record lives on at least 2 machines. The standard setting for important data.
  • min.insync.replicas=3: every record is on all 3 machines, but one broker failing or lagging (even during a rolling restart for an upgrade) stops the topic from accepting writes. The experiment above shows exactly that.
  • min.insync.replicas=1 with acks=all: writes always succeed while a leader exists, but an acknowledged record may live on only one machine.
  • Rule of thumb: RF 3, min ISR 2 to be durable and survive one node. To survive two nodes and still write safely: RF 5, min ISR 3.
Read in post: Why Kafka is fast and durable
Trade-offSeniorunclean.leader.election.enable: durability or availabilityfalse (default): wait for an ISR replica to come back. No committed data is lost, but the partition accepts no writes and serves no reads in the meantime. Choose this for payments, ledgers, orders. true: promote the out-of-sync replica right away. The partition comes back quickly, but records it didn't have are lost fo
  • false (default): wait for an ISR replica to come back. No committed data is lost, but the partition accepts no writes and serves no reads in the meantime. Choose this for payments, ledgers, orders.
  • true: promote the out-of-sync replica right away. The partition comes back quickly, but records it didn't have are lost forever, and consumers may see offsets go backwards. Choose this for logs, metrics, clickstream.
  • Set it as a broker default and override it per topic.
Read in post: Why Kafka is fast and durable
Edge caseSeniorRetries without idempotence reorder recordsWith enable.idempotence=false, retries 0 and max.in.flight.requests.per.connection 1: batch A sent first fails transiently, batch B sent later succeeds, then A is retried and lands after B in the log. For a "top-up" followed by a "withdrawal" on the same account, the consumer sees them in the wrong order. Don't disable

With enable.idempotence=false, retries > 0 and max.in.flight.requests.per.connection > 1: batch A sent first fails transiently, batch B sent later succeeds, then A is retried and lands after B in the log. For a "top-up" followed by a "withdrawal" on the same account, the consumer sees them in the wrong order. Don't disable idempotence (some old configs or frameworks that override acks=1 silently disable it); if you must, set max.in.flight.requests.per.connection=1.

Read in post: Why Kafka is fast and durable
InterviewJuniorWhat are topics, partitions and offsets?

A topic is a named stream of records split into partitions; an offset is a record's position within its partition.

Each partition is an ordered append-only log. A consumer group stores its read offset per partition so it knows where to resume.

Read in post: Why Kafka is fast and durable
InterviewJuniorHow does Kafka guarantee ordering?

Only within a partition; there's no order across partitions.

Records in one partition are read in the order they were written. If one entity's events must be ordered, use the entity id as the key, because the same key always goes to the same partition.

Read in post: Why Kafka is fast and durable
InterviewMidWhy does Kafka achieve high throughput even though it writes to disk?

Because everything is sequential and batched: an append-only log, zero-copy, client-side compressed batches, and partitions working in parallel.

  • The append-only log makes reads and writes sequential; writes go to the page cache without fsync.
  • Consumers are served with zero-copy sendfile.
  • Nothing is deleted on read, so there's no random I/O and only offsets are stored.
  • Clients batch and compress whole batches, so fewer requests and fewer bytes; they pick partitions themselves and send straight to the leader.
  • Partitions allow parallelism across many brokers and consumers.
Read in post: Why Kafka is fast and durable
InterviewMidHow do acks=0, 1 and all differ?

They differ in how many copies the leader waits for before acking: none, just itself, or every replica in the ISR.

0: the producer doesn't wait for a response; fastest, loses data on any failure. 1: acked once the leader has written it; lost if the leader dies before followers copy it. all: waits for every ISR replica; only lost if all of them are lost together, and paired with min.insync.replicas=2 so the ISR can't shrink to one machine. Since Kafka 3.0 the default is all.

Read in post: Why Kafka is fast and durable
InterviewMidHow do consumer groups work, and when do they rebalance?

Consumers with the same group.id share the partitions, each owned by exactly one consumer; the group rebalances when membership or the partition count changes.

Useful consumers top out at the partition count. A rebalance happens when a consumer joins or leaves, misses heartbeats for session.timeout.ms, doesn't poll within max.poll.interval.ms, or when the topic's partition count changes.

Read in post: Why Kafka is fast and durable
InterviewMidWhat goes wrong when you add partitions to a live topic?

Keys move to other partitions, so per-key ordering breaks; and you can't go back down.

A key's partition is murmur2(key) % partition count. After adding partitions, old and new records of the same key sit in different partitions, and key-based state stores drift. Over-provision from the start, or create a new topic and migrate.

Read in post: Why Kafka is fast and durable
InterviewSeniorKafka doesn't fsync before acking, so why is it called durable?

Kafka moves durability from "on one machine's disk" to "in the memory of several machines".

With acks=all a record is only acked once every ISR replica has it, and min.insync.replicas=2 guarantees at least two machines. With replicas in different racks/AZs, the chance of all of them losing power before the OS flushes is very low. Forcing an fsync per message wrecks throughput for little extra protection.

Read in post: Why Kafka is fast and durable
InterviewSeniorWhat are the ISR and the high watermark?

The ISR is the set of replicas caught up with the leader; the high watermark is the highest offset every ISR replica has.

Caught up means within replica.lag.time.max.ms; laggards are dropped and rejoin when they catch up. Leaders are only elected from the ISR (unless unclean election is enabled). Consumers only read up to the high watermark, so they never read a record that could vanish on a leader change.

Read in post: Why Kafka is fast and durable
InterviewSeniorWhat is unclean leader election and when would you enable it?

It lets an out-of-sync replica become leader when every ISR replica is dead: available again at once, but data is lost.

It's off by default. Enable it for data you can afford to lose (logs, metrics) to favour availability; keep it off for payments and orders, where stopping beats losing data.

Read in post: Why Kafka is fast and durable
InterviewSeniorHow does the idempotent producer work, and what are its limits?

A producer id plus per-partition sequence numbers let the broker drop duplicate batches and reject out-of-order ones, but only within one producer session.

Retries neither duplicate nor reorder, with up to 5 in-flight requests per connection. Limits: one session only, and only inside Kafka. A restarted producer, or an application calling send twice for the same business action, still creates duplicates; you need a transactional.id or an idempotent consumer.

Read in post: Why Kafka is fast and durable
Edge caseMidTreating the first workshop casuallyBefore trust exists, you usually get one chance. If the first workshop is dull or rambling, the best people won't come back. Prepare clear goals ("understand the treatment process end to end", "a shared map and a list of open questions"), warm up with a process everyone knows, and keep the pace.

Before trust exists, you usually get one chance. If the first workshop is dull or rambling, the best people won't come back. Prepare clear goals ("understand the treatment process end to end", "a shared map and a list of open questions"), warm up with a process everyone knows, and keep the pace.

Read in post: Discover the domain before you design
TILSeniorA hard-to-reverse pivotal event is handled in code by compensation, not rollback"Invoice sent" or "Records sent to the national system" have left your system. No transaction pulls them back. The design needs a compensating action (a correcting invoice, a records update) and stores both events. These are also the events worth publishing outside the module (via an outbox), because other modules need

"Invoice sent" or "Records sent to the national system" have left your system. No transaction pulls them back. The design needs a compensating action (a correcting invoice, a records update) and stores both events. These are also the events worth publishing outside the module (via an outbox), because other modules need to react to them.

Read in post: Discover the domain before you design
Edge caseMidA command that's just the event rewritten as an order"Prepare treatment plan" → "Treatment plan prepared" repeats the same information and adds no insight. A good command names the real action: "Analyse exam results and existing records" leads to the event "Treatment plan prepared". Likewise, if a command already describes what the doctor does, drop the event that means

"Prepare treatment plan" → "Treatment plan prepared" repeats the same information and adds no insight. A good command names the real action: "Analyse exam results and existing records" leads to the event "Treatment plan prepared". Likewise, if a command already describes what the doctor does, drop the event that means the same thing.

Read in post: Discover the domain before you design
Edge caseSeniorThe overview story misses a whole business areaThe story above never mentions prescriptions or medical records management, though both are big areas. The storyteller found them obvious, so didn't say, and the interviewer didn't ask enough. The fix: after each step ask "which documents or data are created or sent?", "who else needs to know?", "which rule is mandator

The story above never mentions prescriptions or medical records management, though both are big areas. The storyteller found them obvious, so didn't say, and the interviewer didn't ask enough. The fix: after each step ask "which documents or data are created or sent?", "who else needs to know?", "which rule is mandatory?". Then cross-check against the list of areas from the first meeting.

Read in post: Discover the domain before you design
Trade-offSeniorEvent Storming or Domain Storytelling for a discovery workshopEvent Storming: many people, high energy, surfaces conflicts and open questions fast; fits when the system will be event-driven since events already have names. Can turn chaotic with a weak facilitator; needs a long wall or an online whiteboard. Domain Storytelling: few people, slower pace, precise about who does what

Event Storming: many people, high energy, surfaces conflicts and open questions fast; fits when the system will be event-driven since events already have names. Can turn chaotic with a weak facilitator; needs a long wall or an online whiteboard.

Domain Storytelling: few people, slower pace, precise about who does what with which document; easy for non-technical people to follow. Misses areas obvious to the storyteller, and surfaces fewer business rules.

Combine: send participants a domain story before the Event Storming session. Everyone arrives knowing the main flow, so the time goes into events, policies and debate.

Read in post: Discover the domain before you design
InterviewJuniorHow are events named in Event Storming, and why?

In the past tense, in business language: "Appointment scheduled", not "Schedule appointment" or "Button clicked".

An event is a fact that already happened and can't change. Technical events (API called, PDF exported) are removed because they say nothing about the business.

Read in post: Discover the domain before you design
InterviewJuniorWhat's the difference between as-is and to-be?

As-is is the current process, to-be is the desired process once the software exists.

Model as-is first to understand reality, including manual work (notebooks, spreadsheets). To-be is a wish and will keep changing during delivery.

Read in post: Discover the domain before you design
InterviewMidWhat is a pivotal event and why does it matter?

An event that marks a milestone, is hard to reverse, and often switches actor or starts a subprocess. It hints at the boundary between subprocesses.

Example: "Invoice sent" can only be fixed with a correcting invoice. In the design, pivotal events are usually integration events between modules, and need compensation instead of rollback.

Read in post: Discover the domain before you design
InterviewMidAt Process level, what is a policy and how does it become code?

A policy is a business rule: under which conditions something must or must not happen.

Two forms: a blocking rule ("no insurance, no appointment") lives in the aggregate/service and runs synchronously; a reactive rule ("treatment completed, so prepare the invoice") is a listener that runs after commit and must be idempotent.

Read in post: Discover the domain before you design
InterviewMidYou join a company and are told "the requirements are all in the documents". What do you do?

Still read them, but propose a few workshops with domain experts, because documents don't replace walking the process yourself.

Start with informal coffee, then a Why/What/How meeting. Pick the most critical process for the first workshop and prepare it well, since you usually get one chance to build trust.

Read in post: Discover the domain before you design
InterviewSeniorCompare Event Storming and Domain Storytelling. When do you use which?

Event Storming finds "what happened" and suits big groups and event-driven systems; Domain Storytelling finds "who does what with what" and suits small groups and non-technical people. Best is to combine them.

Send a domain story first so everyone shares the flow, then Event Storm to find events, policies, hot spots and boundaries. Domain Storytelling misses obvious areas; Event Storming turns chaotic with a weak facilitator.

Read in post: Discover the domain before you design
InterviewSeniorFrom an Event Storming result, how do you split modules or services?

Take the highly cohesive groups as module candidates, check them against pivotal events, actor switches and changes in word meaning, then let each module own its data and exchange only events or APIs.

  • The same word meaning different things in two groups signals two bounded contexts.
  • Pivotal events crossing a boundary become integration events (an outbox so none are lost).
  • Reactive policies between groups become idempotent listeners.
  • Start as modules in one deployment unit; extract services only when a driver demands it.
Read in post: Discover the domain before you design
InterviewSeniorHow do you handle hot spots still on the wall after the workshop?

Each hot spot is an unsettled risk: give it an owner and an answer-by date, and record the decision when it comes.

Hot spots that affect boundaries or invariants must be settled before coding that area. Ones that can't be settled yet get a design that's easy to change: wrap the assumption in one place and note it in an ADR.

Read in post: Discover the domain before you design
Trade-offMidDependency Inversion is not Dependency InjectionDependency Inversion (a design principle): high- and low-level modules both depend on an abstraction, and the abstraction belongs to the high-level side. It answers "where does the interface live, and who imports whom". Dependency Injection (a technique): an object receives its dependencies from outside (through the co
  • Dependency Inversion (a design principle): high- and low-level modules both depend on an abstraction, and the abstraction belongs to the high-level side. It answers "where does the interface live, and who imports whom".
  • Dependency Injection (a technique): an object receives its dependencies from outside (through the constructor) instead of calling new itself. It answers "who creates and wires the objects".
  • DI without DIP: Spring injects JpaOrderRepository (a concrete class) into a service, and the service still depends on infrastructure. DIP without a container: new the adapter in main and pass it in.
  • In practice they go together: DIP decides the shape of the dependencies, DI (Spring) assembles them at the composition root (the one place that creates and wires every object).
Read in post: Codebase architecture
Edge caseMid"Layered" in Spring often has no real isolation because JPA entities travel through every layerThe controller receives and returns @Entity objects, the service modifies them, the repository saves them: all three layers depend on one class tied to the database schema. Consequences: Adding a column changes the API JSON; renaming a JSON field renames a column. Serialising an entity with lazy relations triggers Lazy

The controller receives and returns @Entity objects, the service modifies them, the repository saves them: all three layers depend on one class tied to the database schema. Consequences:

  • Adding a column changes the API JSON; renaming a JSON field renames a column.
  • Serialising an entity with lazy relations triggers LazyInitializationException or leaks data (passwords, internal relations).

At a minimum: controllers only accept and return DTOs (objects that only carry data, written as records), mapped at the boundary; entities never leave the service layer.

Read in post: Codebase architecture
Edge caseMidThe slides say "use DTOs in the domain layer": DTOs belong to the use case boundary, not the domain modelThe domain model (entities, value objects, aggregates) shouldn't know that any DTO exists. If DTOs live in the domain package, the domain starts being shaped by the API's display needs. Use case commands/results live in the application layer (inbound ports); JSON requests/responses live in the web adapter. There are tw

The domain model (entities, value objects, aggregates) shouldn't know that any DTO exists. If DTOs live in the domain package, the domain starts being shaped by the API's display needs.

  • Use case commands/results live in the application layer (inbound ports); JSON requests/responses live in the web adapter.
  • There are two mappings: HTTP ↔ command/result in the controller, and command ↔ domain in the use case.

The course's sample repo puts dto/request and dto/response under domain/...: it works, but it's the first thing to move as the codebase grows.

Read in post: Codebase architecture
Trade-offSeniorA domain model separate from the JPA entity, or one shared classSeparate (a plain domain Booking + BookingJpaEntity + a mapper): the domain carries no annotations and isn't forced into a no-arg constructor, setters or mutable fields; schema changes don't touch the domain. The price: a mapper per aggregate, losing dirty checking (JPA detecting changed fields by itself) and natural l
  • Separate (a plain domain Booking + BookingJpaEntity + a mapper): the domain carries no annotations and isn't forced into a no-arg constructor, setters or mutable fields; schema changes don't touch the domain. The price: a mapper per aggregate, losing dirty checking (JPA detecting changed fields by itself) and natural lazy loading, and carrying the optimistic-lock version through the mapper yourself.
  • Shared (the domain class carries @Entity): less code and full use of JPA. The price: the domain depends on jakarta.persistence, and JPA's rules (proxies, equals/hashCode, a no-arg constructor) leak into the domain design.
  • Pragmatically: share when the domain is thin and stable; separate for aggregates with many business rules or when the schema and the model differ a lot. More important than either is that the repository interface lives on the inside, even when the entity is shared.
Read in post: Codebase architecture
Trade-offMidShould this project adopt clean/hexagonal architecture?Yes: apps with many business rules (booking, payments, insurance, pricing) that will live for years, with a large team or several teams, many entry and exit points (REST, Kafka, batch), or external providers that may need to be swapped. No: small projects, teams of 1–3 people, short lifetimes; internal tools, core libr
  • Yes: apps with many business rules (booking, payments, insurance, pricing) that will live for years, with a large team or several teams, many entry and exit points (REST, Kafka, batch), or external providers that may need to be swapped.
  • No: small projects, teams of 1–3 people, short lifetimes; internal tools, core libraries, services that are almost pure CRUD or just move data around. A tidy layered architecture with DTOs at the boundary is enough.
  • In between: start with packages by feature + repository interfaces on the inside + DTOs at the boundary. These three habits are cheap, and when one module grows you can upgrade it to ports and adapters without a rewrite.
  • A concrete yardstick: if unit testing your most important business rule requires starting Spring or a database, your current architecture is getting in your way.
Read in post: Codebase architecture
TILMidPassing a Clock instead of calling Instant.now() is the first step towards a pure coreA business rule that calls LocalDate.now() or Instant.now() internally has a hidden dependency on the system clock (and the server's time zone). You can't test "expires after 10 minutes" without actually waiting or using a static-mocking library. The fix: take the current time as a parameter (decide(ride, now)), or inj

A business rule that calls LocalDate.now() or Instant.now() internally has a hidden dependency on the system clock (and the server's time zone). You can't test "expires after 10 minutes" without actually waiting or using a static-mocking library.

The fix: take the current time as a parameter (decide(ride, now)), or inject a java.time.Clock into the shell and use Clock.fixed(...) in tests.

The course's sample repo has a DateUtil in the infrastructure package that 5 domain services import directly: it is both an outward dependency and a hidden clock.

Read in post: Codebase architecture
Edge caseMidArchUnit's onion rule fails on the composition root unless you exclude itOn the first run, the onionArchitecture() rule failed on the Main class (where the controller, services and adapters are created with new and wired together), because it sits outside every ring and depends on all of them. The composition root (in Spring, the @Configuration classes and the @SpringBootApplication class)

On the first run, the onionArchitecture() rule failed on the Main class (where the controller, services and adapters are created with new and wired together), because it sits outside every ring and depends on all of them.

The composition root (in Spring, the @Configuration classes and the @SpringBootApplication class) is allowed to know everything; it is the only place that does this job. Put it in its own package (..config..) and exclude it with ignoreDependency(...); don't loosen the rule for the whole codebase.

Read in post: Codebase architecture
InterviewJuniorWhat is layered architecture? What does "closed layer" mean?

Code is split into horizontal layers by responsibility (controller, service, repository), and requests flow from top to bottom. A closed layer means a request can't skip it.

The controller must go through the service and can't call the repository directly. That way a change in one layer has little impact on the others.

Read in post: Codebase architecture
InterviewJuniorWhy shouldn't you return JPA entities directly from an API?

Because the API gets tied to the database schema: adding a column changes the JSON.

Sensitive fields also leak easily, lazy relations cause errors on serialisation or unexpected extra queries, and bidirectional relations create cycles. Use DTOs (records) at the boundary, mapped in the controller or the use case.

Read in post: Codebase architecture
InterviewMidWhat are ports and adapters in hexagonal architecture?

Ports are interfaces defined by the application; adapters are implementations tied to a specific technology.

  • An inbound port is a use case the outside world calls (PlaceOrderUseCase); a REST controller is the adapter that calls it.
  • An outbound port is something the application needs (OrderRepository, PaymentGateway); a JPA class or HTTP client is the adapter that implements it.

The core only knows the ports, so swapping an adapter doesn't touch the core and the core can be tested with fake adapters.

Read in post: Codebase architecture
InterviewMidHow does Dependency Inversion differ from Dependency Injection?

Dependency Inversion is a principle about dependency direction; Dependency Injection is the technique of supplying dependencies from outside.

DIP: high- and low-level modules both depend on an abstraction, and the abstraction belongs to the high-level side (the repository interface lives next to the domain). DI: dependencies are passed in, usually through the constructor, by a container like Spring. You can use DI and still violate DIP (injecting a concrete JPA class into a service).

Read in post: Codebase architecture
InterviewMidWhat is the core difference between onion/clean architecture and layered architecture?

The dependency direction.

Layered: business logic depends on persistence, with the database at the bottom. Onion/clean: the domain at the centre depends on nothing, and the database is a detail in the outer ring. Repository interfaces are declared inside and implemented outside, so calls still reach the database but source-code dependencies only point inwards.

Read in post: Codebase architecture
InterviewMidThe domain needs to persist data without depending on the database. How?

Declare a repository interface on the inside (the domain or the application layer), implement it in an infrastructure adapter, and let Spring inject the adapter at runtime.

The interface only has the methods the business needs; the adapter implements them with JPA/JDBC. The domain only knows the interface. If the JPA entity is separate from the domain model, the adapter is responsible for mapping.

Read in post: Codebase architecture
InterviewSeniorWhen would you not use clean architecture?

When the cost of the extra interfaces, mappers and layers isn't paid back: small projects, teams of 1–3 people, short lifetimes; services that are almost pure CRUD or just move data; internal tools and libraries.

I still keep three cheap habits: packages by feature, DTOs at the boundary and repository interfaces on the inside, so any module that becomes complex can be upgraded later.

Read in post: Codebase architecture
InterviewSeniorHow do you keep architecture rules in place as the team grows?

Turn the rules into tests that run in CI, so violating PRs are blocked.

  • ArchUnit: the domain doesn't import adapters or frameworks, onion checks, no dependency cycles between modules.
  • Spring Modulith for module boundaries.
  • Record decisions in ADRs. Deliberately exclude the composition root.

Reviews are then left to discuss only the justified exceptions.

Read in post: Codebase architecture
InterviewSeniorIs it worth separating the domain model from the JPA entity?

It depends on how complex the aggregate is: separate when it has many business rules, share the class when the domain is thin.

Separating gives a pure domain that JPA doesn't constrain (no-arg constructors, proxies, setters), with the schema and the model evolving independently. The price is mappers, losing natural dirty checking and lazy loading, and carrying the optimistic-lock version yourself. What's non-negotiable is that the repository interface lives on the inside and entities never leave through the API.

Read in post: Codebase architecture
InterviewSeniorHow does a functional core with an imperative shell help testing?

Business rules become pure functions, so unit tests are just input/output with no mocks; the shell needs only a few integration tests.

Pure functions take data (including the current time) and return decisions, so tests are very fast and cover every branch. The shell only reads, calls the core and writes, so it needs only a few I/O scenarios. The line between unit and integration tests becomes clear.

Read in post: Codebase architecture
TILMidFunctional requirements tell you which modules you need, quality attributes decide the shapeThe exact same ten features can run on one monolith on one server, or need three active-active regions. The difference isn't in the features but in the numbers: 99% or 99.99%, 50 or 50,000 requests per second, whether data may leave the EU. So the first meeting with stakeholders should ask for numbers, not just a featu

The exact same ten features can run on one monolith on one server, or need three active-active regions. The difference isn't in the features but in the numbers: 99% or 99.99%, 50 or 50,000 requests per second, whether data may leave the EU. So the first meeting with stakeholders should ask for numbers, not just a feature list.

Read in post: Pragmatic software architecture
Edge caseSeniorSaying yes to "just one more nine" without changing the deadline or scopeGoing from 99% to 99.9% isn't "try a bit harder". It changes the architecture: several instances, no session stuck to one machine, backward-compatible DB migrations for zero-downtime deploys, database failover, and monitoring with alerts. When asked, answer with the consequence table: "yes, but it needs X more weeks an

Going from 99% to 99.9% isn't "try a bit harder". It changes the architecture: several instances, no session stuck to one machine, backward-compatible DB migrations for zero-downtime deploys, database failover, and monitoring with alerts. When asked, answer with the consequence table: "yes, but it needs X more weeks and Y in infrastructure, or we drop feature Z from the MVP".

Read in post: Pragmatic software architecture
Trade-offSeniorSimple architecture from day one or ready for large scale up frontSimple first (one deployment unit, one database, few components): fast to market, few people to run it, cheap. Risk: left too long, modules tangle and you can't split when you need to scale. Ready for scale now (microservices, a broker, orchestration): each part can scale on its own. Price: slower MVP, a team that must

Simple first (one deployment unit, one database, few components): fast to market, few people to run it, cheap. Risk: left too long, modules tangle and you can't split when you need to scale.

Ready for scale now (microservices, a broker, orchestration): each part can scale on its own. Price: slower MVP, a team that must already know how to run distributed systems, high cloud bills, and quite possibly optimising for load that never arrives.

The middle ground is usually right: one deployment unit, but modules split strictly by business area, each owning its data. Any decision to extract a module is recorded with a trigger threshold (e.g. "when scheduling needs to scale on its own because its load is 10x the rest").

Read in post: Pragmatic software architecture
Edge caseMidTreating a good pattern as right everywhereClean/Hexagonal for every service, microservices for every application, Kubernetes for tiny apps, cache everywhere. Each one is right sometimes, but applied unconditionally it adds complexity without solving any problem. Before each pattern, ask: which driver demands it? If you can't name one, don't add it. See the pos

Clean/Hexagonal for every service, microservices for every application, Kubernetes for tiny apps, cache everywhere. Each one is right sometimes, but applied unconditionally it adds complexity without solving any problem. Before each pattern, ask: which driver demands it? If you can't name one, don't add it. See the post on codebase architecture for when layered is enough.

Read in post: Pragmatic software architecture
Trade-offSeniorPick technology the team knows or technology that fits the problem betterMost systems are ordinary business applications, so the technology the team already knows usually wins: fewer operational mistakes, faster delivery. New technology is worth it when a specific driver can't be met by the current stack (e.g. you need a replayable event stream and only have RabbitMQ). When you do pick some

Most systems are ordinary business applications, so the technology the team already knows usually wins: fewer operational mistakes, faster delivery. New technology is worth it when a specific driver can't be met by the current stack (e.g. you need a replayable event stream and only have RabbitMQ). When you do pick something new, count learning, hiring and operations in the decision, and try it on a low-risk module first.

Read in post: Pragmatic software architecture
InterviewJuniorWhat is the difference between functional and non-functional requirements?

Functional says what the system does; non-functional (quality attributes) says how well it must do it.

"Users search products by keyword" is functional. "Search returns within 300 ms at p95 under 100 requests per second" is non-functional. A non-functional requirement needs a number to be testable.

Read in post: Pragmatic software architecture
InterviewJuniorHow much downtime does 99.9% availability allow?

About 8.8 hours a year, roughly 43 minutes a month.

Formula: (1 − 0.999) × 8,760 h = 8.76 h. At 99.99% you get about 53 minutes a year, 4 minutes a month: too short for a human to react, so failover must be automatic.

Read in post: Pragmatic software architecture
InterviewMidWhat are architectural drivers? Name the four groups.

They're what forces the architecture into a specific shape: functional requirements, business constraints, technical constraints and quality attributes.

Business constraints cover time, people, budget and law (GDPR). Technical constraints are mandated technologies. Quality attributes are the "-ilities" with numbers. You choose the architecture from these drivers rather than gut feeling or what another company uses.

Read in post: Pragmatic software architecture
InterviewMidThe PM wants the MVP a month earlier. How do you respond?

It's possible, but at least one other driver must change: cut scope, temporarily lower a quality target, or add resources (rarely faster).

Rank features by value and cut from the bottom; say clearly what can't be cut (security, never losing customers' money); record the technical debt created.

Read in post: Pragmatic software architecture
InterviewMidWhy does the business often see architecture as waste, and how do you convince them?

Because the cost is visible now and the benefit only shows after a few years. You convince them by turning the deferred cost into numbers tied to business goals.

For example: lead time for a small change, regressions per release, manual testing time. Compare "save 50k now, pay 1 million in two years". And propose just enough investment (module boundaries, automated tests), not a grand platform.

Read in post: Pragmatic software architecture
InterviewSeniorHow do you keep an architecture simple without closing off the future?

Start with the fewest components the drivers require, but invest in boundaries: modules by business area, data owned by one module, one-way dependencies, and a recorded threshold for revisiting the decision.

  • Wrap unsure assumptions in their own module so a change touches one place.
  • Enforce boundaries automatically (ArchUnit) instead of relying on review.
  • Write ADRs with "assumed limits" and an "evolution path".
  • Optimise for removability: a bad idea should be cheap to remove.
Read in post: Pragmatic software architecture
InterviewSeniorWhat do you think the architect's role is in a modern team?

More a function inside the team than a title: understand the domain, connect business and engineering, decide with the team, live with the consequences together, and mentor others.

They still code and review. They're a generalist broad enough (business, infrastructure, solution, security, soft skills) to fit the pieces together, and they dare to say "stop" when needed. Hohpe's elevator picture: riding between the engine room and the boardroom, translating strategy into engineering and back.

Read in post: Pragmatic software architecture
InterviewSeniorHow does Conway's law affect architectural decisions?

A system takes the shape of the organisation's communication paths, so module or service boundaries only last when they match team boundaries.

Two teams changing one module conflict constantly; one team owning five services pays the cost of distribution without the autonomy benefit. Either split modules along teams, or reshape teams to fit the target architecture (the inverse Conway maneuver).

Read in post: Pragmatic software architecture
Edge caseSeniorAn AI-generated user delete endpoint looks right but misses business rulesThe classic example from the course material: AI generates @PreAuthorize("hasRole('ADMIN')") on DELETE /users/{id} and calls deleteById. Technically it works. But it never asks: can an admin delete themselves, can a super admin be deleted, does deleting a user cascade into important data, is there an audit record of wh

The classic example from the course material: AI generates @PreAuthorize("hasRole('ADMIN')") on DELETE /users/{id} and calls deleteById. Technically it works. But it never asks: can an admin delete themselves, can a super admin be deleted, does deleting a user cascade into important data, is there an audit record of who deleted whom and when.

The lab behind this post adds a rule AI didn't guess: you can't delete your own account, with tests for it (admin deleting someone else gets 204, deleting themselves gets 400). The right question when reviewing security code is not "does it run" but "who can abuse it, and how".

Read in post: Working with AI coding agents as a backend engineer
Edge caseMidRules file names change between tool versionsThe course material lists .cursorrules, .windsurfrules and .gemini/styleguide.md. Some of those are now legacy: Cursor moved to a .cursor/rules/ folder, Windsurf to .windsurf/rules/, Gemini CLI reads GEMINI.md, and many tools also read AGENTS.md. Don't memorize file names; check the docs of the tool you use. The idea d

The course material lists .cursorrules, .windsurfrules and .gemini/styleguide.md. Some of those are now legacy: Cursor moved to a .cursor/rules/ folder, Windsurf to .windsurf/rules/, Gemini CLI reads GEMINI.md, and many tools also read AGENTS.md.

Don't memorize file names; check the docs of the tool you use. The idea doesn't change: one conventions file, read first by the agent, kept in Git so the whole team and every session share it.

Read in post: Working with AI coding agents as a backend engineer
Trade-offMidOne long session or many short onesLong session: the agent remembers what was discussed. But after a few dozen turns, the beginning falls out of context or gets summarized away, and the code drifts into contradictions. Short sessions, one task each: clean context, easy to review, easy to throw away if it goes wrong. The cost: you must write what needs r
  • Long session: the agent remembers what was discussed. But after a few dozen turns, the beginning falls out of context or gets summarized away, and the code drifts into contradictions.
  • Short sessions, one task each: clean context, easy to review, easy to throw away if it goes wrong. The cost: you must write what needs remembering into files (rules, ADRs, progress notes).
  • Suggestion: one feature per session, start in plan mode (the agent proposes, you approve before any file changes), finish with green tests and one commit.
Read in post: Working with AI coding agents as a backend engineer
Edge caseSeniorGreen tests that check nothingAI writes tests very fast and very easily writes meaningless ones: mock everything then verify the exact call that was just stubbed, assert back the value that was just passed in, or change the assertion to match buggy code so "the test passes". Tell an agent "make the tests green" and it may fix the test instead of th

AI writes tests very fast and very easily writes meaningless ones: mock everything then verify the exact call that was just stubbed, assert back the value that was just passed in, or change the assertion to match buggy code so "the test passes". Tell an agent "make the tests green" and it may fix the test instead of the code.

To prevent it: put "never change assertions or @Disabled tests to get a green build without asking" in the rules; when reviewing, ask "would this test fail if I deleted the logic in the service"; for important code, break it on purpose and see whether a test catches it (the idea behind mutation testing).

Read in post: Working with AI coding agents as a backend engineer
TILMidAn agent can only verify itself if it has a test command and an environment that runsWhat separates an agent from chat is that it can run ./mvnw test, read the failures and fix them. But only if the environment allows it: if tests need Docker (Testcontainers) and Docker isn't running, the agent either skips the tests or "fixes" them by disabling them. In this lab, the PostgreSQL Testcontainers test is

What separates an agent from chat is that it can run ./mvnw test, read the failures and fix them. But only if the environment allows it: if tests need Docker (Testcontainers) and Docker isn't running, the agent either skips the tests or "fixes" them by disabling them.

In this lab, the PostgreSQL Testcontainers test is marked disabledWithoutDocker = true: on a machine without Docker the test is skipped and reported as such (29 tests, 28 passed, 1 skipped), not silently green. Write the test commands and their environment requirements into the rules file so the agent knows when the results can be trusted.

Read in post: Working with AI coding agents as a backend engineer
InterviewMidHow do you verify AI-generated code?

Run real tests (including integration tests with real security and transactions), then read the diff and the tests like a reviewer.

Checklist: N+1 and fetching, transaction boundaries, authorization and input validation, swallowed exceptions, scope of the change. Ask "would this test fail if the logic were deleted".

Read in post: Working with AI coding agents as a backend engineer
InterviewMidWhen do you not use AI to write code?

When learning a new concept, writing security code or core business logic, practising for interviews, and debugging complex incidents that need runtime context.

There AI is still useful as a thinking partner (listing hypotheses, explaining), but the decisions and the verification are mine.

Read in post: Working with AI coding agents as a backend engineer
InterviewMidWhat should a project rules file for a coding agent contain?

The stack and versions, build/test commands, package structure, coding conventions, prohibitions, and links to settled decisions (ADRs).

Keep it short and checkable, in Git. Agents forget between sessions, so this file is the shared long-term memory of every session and every teammate.

Read in post: Working with AI coding agents as a backend engineer
InterviewMidWhy put acceptance criteria in the prompt?

They narrow the solution, become tests the agent checks itself against, and are your checklist when reviewing.

If you can't write Given/When/Then for a task, the requirement is still vague; clarify it before handing it to an agent.

Read in post: Working with AI coding agents as a backend engineer
InterviewSeniorTell me about an AI-introduced bug you caught. What did you learn?

The agent's code read very plausibly, but integration tests exposed three bugs: a LazyInitializationException when the controller read a lazy collection after the transaction, a test expecting a UNIQUE error at flush while IDENTITY throws at save, and a catch-all that turned @PreAuthorize's 403 into a 500.

The lesson: AI bugs are usually integration bugs, not syntax, so file-by-file review isn't enough; you need tests that run the whole chain and someone who knows the framework reading the results.

Read in post: Working with AI coding agents as a backend engineer
InterviewSeniorHow do you know whether AI really makes the team faster?

Measure lead time, review time, change failure rate and rework before and after, per kind of task.

Perception is unreliable: a 2025 randomized trial found experienced developers were slower with AI while believing they were faster. Lines of code is the wrong metric because AI inflates it effortlessly.

Read in post: Working with AI coding agents as a backend engineer
InterviewSeniorA colleague wants an agent to write the whole authorization layer. What do you say?

Use the agent for scaffolding, but the authorization model, the rules and the attack-scenario tests must be designed and reviewed line by line by someone who understands security.

Concretely: use Spring Security instead of a hand-written filter, list the business rules (self-deletion, super admin, audit), write 401/403 and abuse tests first, and require a second reviewer.

Read in post: Working with AI coding agents as a backend engineer
InterviewSeniorWhat are the security and data risks of running an agent in a company repo?

Code and secrets leaking to an outside service, and the agent running harmful commands on a machine with credentials.

Mitigate with an approved enterprise plan, secrets in environment variables and out of the agent's reach, restricted commands (no push, no deletes, no production credentials), and reviewing every diff before merging.

Read in post: Working with AI coding agents as a backend engineer
TILMidDeleting a file only removes a name; data is freed when the link count is 0 and nobody has it openrm calls unlink: it removes one directory entry and decrements the link count. The kernel frees the blocks only when the link count is zero and no process holds a file descriptor to that inode. So a process writing a log keeps writing after the file is rm-ed; there's just no name left to find it by. It's also how "safe

rm calls unlink: it removes one directory entry and decrements the link count. The kernel frees the blocks only when the link count is zero and no process holds a file descriptor to that inode.

So a process writing a log keeps writing after the file is rm-ed; there's just no name left to find it by. It's also how "safe while running" installs work: mv the new binary over the old name and running processes keep using the old inode.

Read in post: Linux for backend engineers
Edge caseMidYou rm-ed the log file but df still says the disk is fullDelete a 50 GB log that a service still has open: df doesn't move and du finds nothing big. The inode is alive because the JVM holds an fd. Find it: lsof +L1 (open files with a link count below 1). I created a 50 MB file and deleted it while it was open; lsof +L1 showed app.log with NLINK 0. Reclaim it: restart the pro

Delete a 50 GB log that a service still has open: df doesn't move and du finds nothing big. The inode is alive because the JVM holds an fd.

  • Find it: lsof +L1 (open files with a link count below 1). I created a 50 MB file and deleted it while it was open; lsof +L1 showed app.log with NLINK 0.
  • Reclaim it: restart the process, or empty the file through the open fd with : > /proc/<pid>/fd/<n>.
  • Prevent it: don't rm a log that's being written; use truncate -s 0 app.log.
Read in post: Linux for backend engineers
Trade-offMidRotate logs with logrotate or let the application rotate themlogrotate create + signal: no lost lines, but the application must reopen its file on a signal. The JVM has no built-in hook for this with Logback. logrotate copytruncate: needs no cooperation from the app; may drop a few lines at rotation time and costs I/O to copy large files. Logback/Log4j2 RollingFileAppender: the
  • logrotate create + signal: no lost lines, but the application must reopen its file on a signal. The JVM has no built-in hook for this with Logback.
  • logrotate copytruncate: needs no cooperation from the app; may drop a few lines at rotation time and costs I/O to copy large files.
  • Logback/Log4j2 RollingFileAppender: the app closes the old file and opens a new one by date or size, with a total size cap (totalSizeCap). Don't also run logrotate create on the same file.
  • In containers: write to stdout and let the runtime (Docker log driver, Kubernetes) and your log pipeline handle it, the 12-factor way.
Read in post: Linux for backend engineers
Edge caseMidThe right to delete a file lives on the directory, not the fileDeleting or renaming a file modifies a directory entry, so it needs w (and x) on the containing directory and nothing on the file itself. A chmod 444 file can still be deleted by anyone who can write to its directory; a 666 file inside a 555 directory can't. That's why /tmp needs the sticky bit, and why "make the confi

Deleting or renaming a file modifies a directory entry, so it needs w (and x) on the containing directory and nothing on the file itself. A chmod 444 file can still be deleted by anyone who can write to its directory; a 666 file inside a 555 directory can't.

That's why /tmp needs the sticky bit, and why "make the config read-only" protects nothing if the directory is writable.

Read in post: Linux for backend engineers
Edge caseMidA non-root container gets "Permission denied" writing to its volumeA volume mounted into a container keeps the UID/GID ownership it has on disk. If the directory belongs to root (or UID 999 from the MySQL image) and the app runs as UID 1001, every write is denied. A chown in the Dockerfile doesn't help: it ran at build time and doesn't apply to a volume mounted at run time. Fix it wit

A volume mounted into a container keeps the UID/GID ownership it has on disk. If the directory belongs to root (or UID 999 from the MySQL image) and the app runs as UID 1001, every write is denied. A chown in the Dockerfile doesn't help: it ran at build time and doesn't apply to a volume mounted at run time.

Fix it with fsGroup in the Pod's securityContext so Kubernetes adjusts the volume's group, or set permissions in an init container. Don't "fix" it by going back to root or chmod 777.

Read in post: Linux for backend engineers
Edge caseJuniortail -f loses track of the file after log rotationtail -f app.log follows the file descriptor, that is, the inode. When the log is rotated with create, tail -f keeps reading the old file (now app.log.1): the screen freezes while new lines go to a different file. Use tail -F (--follow=name --retry): it follows the name, notices the file was replaced and reopens it.

tail -f app.log follows the file descriptor, that is, the inode. When the log is rotated with create, tail -f keeps reading the old file (now app.log.1): the screen freezes while new lines go to a different file.

Use tail -F (--follow=name --retry): it follows the name, notices the file was replaced and reopens it.

Read in post: Linux for backend engineers
Edge caseMidset -e doesn't catch every failureset -e won't stop the script when the failing command is inside an if condition, part of &&/||, or on the left of a pipe (unless pipefail is set). local out=$(cmd) also swallows cmd's exit code, because the status is local's; split it into local out; out=$(cmd). An unquoted variable (rm -rf $DIR/) with an empty DIR is

set -e won't stop the script when the failing command is inside an if condition, part of &&/||, or on the left of a pipe (unless pipefail is set). local out=$(cmd) also swallows cmd's exit code, because the status is local's; split it into local out; out=$(cmd).

An unquoted variable (rm -rf $DIR/*) with an empty DIR is a classic disaster. Always double-quote, use "${DIR:?}" to stop when it's empty, and run shellcheck in CI.

Read in post: Linux for backend engineers
Trade-offMidShell script or a real language (Python, Java) for automationShell script: available everywhere, glues commands together with pipes very concisely; good for anything under about 100 lines: wrapping commands, CI steps. Python/Java/Go: types, error handling, tests, real JSON/YAML/HTTP libraries. Worth switching to once the branching grows or you need to parse structured data. The
  • Shell script: available everywhere, glues commands together with pipes very concisely; good for anything under about 100 lines: wrapping commands, CI steps.
  • Python/Java/Go: types, error handling, tests, real JSON/YAML/HTTP libraries. Worth switching to once the branching grows or you need to parse structured data.
  • The tell-tale sign: you're writing a JSON parser in sed, or nobody dares touch the script because it has no tests.
Read in post: Linux for backend engineers
Edge caseJuniorsed -i differs between GNU (Linux) and BSD (macOS)GNU sed accepts sed -i 's/a/b/' f. BSD sed on macOS requires a backup suffix argument: sed -i '' 's/a/b/' f. The GNU form on a Mac treats your expression as the suffix and fails with a confusing error. Portable options: sed -i.bak '...' f (suffix glued to -i) and delete the .bak, or write to a new file and mv it. Scrip

GNU sed accepts sed -i 's/a/b/' f. BSD sed on macOS requires a backup suffix argument: sed -i '' 's/a/b/' f. The GNU form on a Mac treats your expression as the suffix and fails with a confusing error.

Portable options: sed -i.bak '...' f (suffix glued to -i) and delete the .bak, or write to a new file and mv it. Scripts that run on macOS laptops and Linux CI have to handle this.

Read in post: Linux for backend engineers
InterviewJuniorWhat is an inode? Where is the file name stored?

An inode is the structure describing a file; the name lives in a directory entry of the containing directory.

The inode holds the inode number, size, owner, permissions, timestamps, link count and pointers to the data blocks. The directory maps name → inode number, so one inode can have several names (hard links).

Read in post: Linux for backend engineers
InterviewJuniorHow do hard links and soft links differ?

A hard link is another name for the same inode; a soft link is a separate file holding the target's path.

Hard link: deleting the original name keeps the data, but it can't cross file systems or point to a directory. Soft link: it can cross file systems and point to directories, but it breaks when the target is deleted, renamed or moved.

Read in post: Linux for backend engineers
InterviewJuniorWhat does chmod 750 mean, and why are permissions 4, 2, 1?

User rwx (7 = 4 + 2 + 1), group r-x (5 = 4 + 1), others nothing (0).

4, 2 and 1 are the three bits of a three-digit binary number, so every combination sums to a unique value from 0 to 7 that decodes back unambiguously.

Read in post: Linux for backend engineers
InterviewMidYou deleted a huge log file but the disk is still full. Why, and what do you do?

The service still holds an fd to the file, so the inode and its blocks haven't been freed.

rm only removes a name; data is freed only when the link count is zero and no process has the file open. So du can't see it but df is still full. Find it with lsof +L1 and reclaim the space by restarting the process or running : > /proc/<pid>/fd/<n>.

Read in post: Linux for backend engineers
InterviewMidWhat's the difference between logrotate's create and copytruncate?

create renames the old file and creates a new one; copytruncate copies the content elsewhere and truncates the original to zero.

With create, the process keeps writing to the old inode until it's told to reopen. With copytruncate, the process needn't know, but lines written between the copy and the truncate can be lost, and without O_APPEND you get a zero-filled region.

Read in post: Linux for backend engineers
InterviewMidWho can delete a read-only (444) file?

Anyone with w and x on its directory, because deleting modifies the directory entry, not the file.

Shared directories like /tmp set the sticky bit so only a file's owner (and root) can delete it.

Read in post: Linux for backend engineers
InterviewMidWhy shouldn't containers run as root, and how do you fix volume write errors?

If the app is exploited the attacker is root in the container; fix volume write errors with fsGroup or an init container, not by going back to root.

Root inside the container can write anywhere in the image and gets closer to the host when the setup is loose. Use USER in the Dockerfile and runAsNonRoot plus readOnlyRootFilesystem in Kubernetes. Volumes keep their on-disk UID/GID, so a non-root user may not be able to write; never "fix" that with chmod 777.

Read in post: Linux for backend engineers
InterviewSeniorA deploy script uses sed to replace the image tag. How do you review it?

sed can match the wrong thing, doesn't understand YAML and stays silent when nothing matches; at minimum anchor and verify, better use yq, kustomize or Helm.

  • Risks: matching other strings ($IMAGE_TAG_SUFFIX), no YAML awareness (several containers, indentation), exit code 0 when nothing was replaced, and sed -i differs between macOS and Linux.
  • At minimum: anchor the pattern and verify with grep -q, failing if nothing was replaced.
  • Better: envsubst with an explicit variable list, yq, or kustomize/Helm; pin images by digest so deploys are reproducible.
Read in post: Linux for backend engineers
InterviewSeniorIs set -euo pipefail enough to make a script safe?

No. -e ignores failures inside if conditions and &&/||, and local x=$(cmd) swallows cmd's exit code.

You still need to quote every variable, use ${VAR:?} for required variables before dangerous commands like rm -rf, put -- before file names, run shellcheck in CI, and provide a dry-run mode.

Read in post: Linux for backend engineers
InterviewSeniorHow do you safely replace a binary or config file that's in use?

Write the new version to a temp file on the same file system, then mv it into place, because rename is atomic.

Readers see either the old or the new version, never a half-written file, and running processes keep the old inode. Overwriting in place can cause Text file busy or mixed content. Deploying into versioned directories and switching a current symlink follows the same principle; rollback is just pointing the symlink back.

Read in post: Linux for backend engineers
Edge caseJuniorReaching for lsof -ti:PORT | xargs kill -9 by defaultThe course notes give kill -9 as the main fix. SIGKILL ends the process at once and skips graceful shutdown: in-flight requests are cut, half-done transactions must roll back, files and connections aren't closed cleanly. For your own app, send SIGTERM (kill PID) first, wait a few seconds, and use -9 only if it hangs. "

The course notes give kill -9 as the main fix. SIGKILL ends the process at once and skips graceful shutdown: in-flight requests are cut, half-done transactions must roll back, files and connections aren't closed cleanly. For your own app, send SIGTERM (kill PID) first, wait a few seconds, and use -9 only if it hangs.

"Restart your computer" also works, but it never tells you which process held the port. Finding it (usually an old run inside the IDE) is what stops it happening again.

Read in post: Common Spring Boot errors and how to debug them
Edge caseMidMixing Spring Boot 3 and 4 starters in one pomSpring Boot 4 renamed some starters (spring-boot-starter-web became spring-boot-starter-webmvc) and split test starters per technology. Copying a pom snippet from an old tutorial, or letting an AI generate dependencies with hard-coded versions, easily pulls in two generations of libraries at once. Symptoms are NoSuchMe

Spring Boot 4 renamed some starters (spring-boot-starter-web became spring-boot-starter-webmvc) and split test starters per technology. Copying a pom snippet from an old tutorial, or letting an AI generate dependencies with hard-coded versions, easily pulls in two generations of libraries at once. Symptoms are NoSuchMethodError or auto-config that never switches on. Always let the spring-boot-starter-parent manage versions and check dependency:tree when something looks odd.

Read in post: Common Spring Boot errors and how to debug them
Trade-offMidTurn on open-in-view to make LazyInitializationException go away?spring.jpa.open-in-view=true (Boot's default, with a warning) keeps the session open until the view/JSON is rendered, so the error disappears. Gain: simpler code, no thinking about transaction boundaries. Cost: a DB connection is held for the whole request, including JSON serialization or calls to external APIs; lazy q

spring.jpa.open-in-view=true (Boot's default, with a warning) keeps the session open until the view/JSON is rendered, so the error disappears.

  • Gain: simpler code, no thinking about transaction boundaries.
  • Cost: a DB connection is held for the whole request, including JSON serialization or calls to external APIs; lazy queries fire silently from the controller and cause hard-to-see N+1.

For REST APIs, turn it off and decide in the service what data to load (JOIN FETCH, @EntityGraph, DTO projections). See persistence context and N+1.

Read in post: Common Spring Boot errors and how to debug them
Edge caseMidA catch-all exception handler turns @PreAuthorize's 403 into a 500The lab has @ExceptionHandler(Exception.class) returning a 500 "Unexpected error" (right in principle: never leak stack traces). After adding @PreAuthorize("hasRole('ADMIN')") to the delete-user endpoint, a non-admin got 500 instead of 403. Why: errors in the filter chain (URL-level 401/403) happen before the Dispatche

The lab has @ExceptionHandler(Exception.class) returning a 500 "Unexpected error" (right in principle: never leak stack traces). After adding @PreAuthorize("hasRole('ADMIN')") to the delete-user endpoint, a non-admin got 500 instead of 403.

Why: errors in the filter chain (URL-level 401/403) happen before the DispatcherServlet, so @RestControllerAdvice never sees them. But @PreAuthorize throws AccessDeniedException inside the controller call, so the advice catches it, and the Exception handler is the only one that matches. Verified: remove the dedicated handler and the test expecting 403 gets 500.

Fix it by handling it separately and re-throwing so Spring Security returns 403:

@ExceptionHandler(AccessDeniedException.class)
void accessDenied(AccessDeniedException ex) {
    throw ex;
}

Alternatively, return a 403 ProblemDetail right there. Handler design is covered in error handling in Spring Boot.

Read in post: Common Spring Boot errors and how to debug them
InterviewJuniorThe app says "Port 8080 was already in use". What do you do?

Find the process holding the port (lsof -i :8080 or netstat -ano), stop it with SIGTERM, or change server.port.

It's usually an old copy of the same app still running in the IDE. Use kill -9 only if the process won't stop, because it skips graceful shutdown.

Read in post: Common Spring Boot errors and how to debug them
InterviewJuniorWhat's the difference between 401 and 403?

401: the server can't tell who you are (token missing, invalid or expired). 403: it knows who you are, but you lack permission.

On 401 the client should log in again or refresh the token. On 403 logging in again doesn't help; you need to be granted access.

Read in post: Common Spring Boot errors and how to debug them
InterviewMidWhat is LazyInitializationException and how do you fix it?

It's thrown when a lazy relation (a proxy) is touched after the Hibernate session closed; fix it by loading what you need inside the transaction and returning a DTO.

Use JOIN FETCH, @EntityGraph, or map to a DTO right in the service. Enabling open-in-view hides the error but holds a connection for the whole request and hides N+1.

Read in post: Common Spring Boot errors and how to debug them
InterviewMidThe app won't start: "required a bean of type X that could not be found". What could cause it?

Class X is outside the scanned packages, it lacks a stereotype annotation, or the bean is switched off by a profile or condition.

Check the package of the @SpringBootApplication class, the annotation on X, the active profiles, and the condition report (--debug) if X should come from an auto-config.

Read in post: Common Spring Boot errors and how to debug them
InterviewMidAn endpoint with @PreAuthorize returns 500 instead of 403. Why?

Because the AccessDeniedException thrown inside the controller call is caught by an @ExceptionHandler(Exception.class) in the @RestControllerAdvice, which returns 500.

Authorization failures in the filter chain never reach the advice; method security does. Add a dedicated handler for AccessDeniedException (re-throw it or return 403).

Read in post: Common Spring Boot errors and how to debug them
InterviewMidNoSuchMethodError at runtime although the code compiles. How do you investigate?

It's a sign of two versions of one library: compiled against one, running with the other. Use mvn dependency:tree to find the extra one.

Fix it by letting the Spring Boot BOM manage versions, removing hand-written versions, or excluding the transitive dependency with the wrong version. Then clean to drop old classes.

Read in post: Common Spring Boot errors and how to debug them
InterviewSeniorA bug only happens on staging and you can't reproduce it locally. How do you approach it?

Compare the environments first (profiles, environment variables, versions, data), gather evidence from logs and traces, then reproduce it in a test under staging-like conditions.

  • Check actual properties via /actuator/env and the profiles in the startup log.
  • Raise log levels for one package for a short time via /actuator/loggers, without redeploying.
  • Use the trace id to join logs across services.
  • Remote debug only where there's no real data and access is controlled.
  • Reproduce with Testcontainers on the same DB version as staging.
Read in post: Common Spring Boot errors and how to debug them
Edge caseMid"Bcrypt is legacy" is wrong, and scrypt doesn't make brute force "impossible"The slide calls bcrypt legacy and says scrypt makes brute force impossible; neither is true. OWASP's order (Password Storage Cheat Sheet): Argon2id: e.g. 19 MiB memory, 2 iterations, 1 lane. scrypt: N=2^17, r=8, p=1. bcrypt: cost 10 or more, for legacy systems. Still acceptable and the Spring Security default. PBKDF2-H

The slide calls bcrypt legacy and says scrypt makes brute force impossible; neither is true. OWASP's order (Password Storage Cheat Sheet):

  • Argon2id: e.g. 19 MiB memory, 2 iterations, 1 lane.
  • scrypt: N=2^17, r=8, p=1.
  • bcrypt: cost 10 or more, for legacy systems. Still acceptable and the Spring Security default.
  • PBKDF2-HMAC-SHA256: 600,000 iterations, when FIPS-140 (the US government crypto standard) is required.

A slow function only makes each guess more expensive: 123456 still falls on the first try. You also need login attempt limits, a breached-password check, a minimum length and MFA (multi-factor authentication).

Read in post: Storing passwords and encrypting personal data
Edge caseSeniorBcrypt only uses the first 72 bytes, and slow hashing can be abused for DoS72 bytes: two long passwords sharing the first 72 bytes count as the same one. Easy to hit with Vietnamese passphrases (accented characters take 2–3 bytes in UTF-8). Don't "fix" it by feeding a raw binary SHA-256 digest to bcrypt (a zero byte can terminate the string); if you must pre-hash, Base64-encode the digest fir
  • 72 bytes: two long passwords sharing the first 72 bytes count as the same one. Easy to hit with Vietnamese passphrases (accented characters take 2–3 bytes in UTF-8). Don't "fix" it by feeding a raw binary SHA-256 digest to bcrypt (a zero byte can terminate the string); if you must pre-hash, Base64-encode the digest first, or use Argon2id.
  • DoS (taking a service down by piling on load): every check deliberately burns 100–300 ms of CPU, so the login endpoint is a cheap target. Cap password length (say 128 characters; for bcrypt count bytes, at most 72), rate-limit per IP and per account, and run verification in a bounded pool.
  • @Size counts characters, bcrypt counts bytes: @Size(max = 72) still lets through 72 accented characters, which can be up to 216 bytes of UTF-8. With bcrypt, check password.getBytes(UTF_8).length <= 72 (a custom validator), or use Argon2id. Recent Spring Security releases (the CVE-2025-22228 fix) make BCryptPasswordEncoder reject passwords over 72 bytes instead of silently truncating, so without an upfront check a long passphrase at sign-up becomes a 500.
Read in post: Storing passwords and encrypting personal data
Trade-offSeniorSalt, pepper and the cost parameterSalt: unique per row, stored openly. Bcrypt, scrypt and Argon2id generate it and embed it in their output string, so a separate salt column next to a bcrypt hash (as the slide illustrates) is redundant. Pepper: one shared secret kept outside the DB, in a KMS/HSM or secret manager, mixed in (usually with an HMAC before
  • Salt: unique per row, stored openly. Bcrypt, scrypt and Argon2id generate it and embed it in their output string, so a separate salt column next to a bcrypt hash (as the slide illustrates) is redundant.
  • Pepper: one shared secret kept outside the DB, in a KMS/HSM or secret manager, mixed in (usually with an HMAC before hashing): a leak of the DB alone is not brute-forceable. The cost: lose the pepper and everyone must reset their password; rotating it is awkward (you keep several versions).
  • Cost parameter: one check takes ~100–500 ms on production hardware; re-measure when hardware changes. Too high and logins get slow and DoS-prone; too low and brute force is cheap.
Read in post: Storing passwords and encrypting personal data
Trade-offSeniorEncrypt on the client, in the application server or in the database
Encrypt in Gain Lose
Client (end-to-end) server never sees plaintext, strongest protection; good for chat, private notes server can't process, search or validate; losing the key on the user's device loses the data
Application server (the course's choice) pick columns one by one, key lives outside the DB so a leaked DB or backup stays safe, less work for the DB application code owns keys, nonces, search and migrations
Database: TDE (Transparent Data Encryption, the DB encrypts files as it writes to disk) in SQL Server/Oracle/MySQL Enterprise, RDS disk encryption cheap, almost no effort; protects data at rest on disk (stolen disks, leaked snapshots) anyone with SELECT still reads plaintext: no help against SQL injection or a DB account holder
Read in post: Storing passwords and encrypting personal data
Edge caseSeniorReusing a nonce with AES-GCM loses both secrecy and integrityGCM requires that a (key, nonce) pair never repeats. Repeat it once and XOR-ing the two ciphertexts gives the XOR of the two plaintexts, and the attacker can recover the authentication key to forge data. Common causes: a fixed nonce in configuration, a counter nonce that resets on restart, nonces from Random instead of

GCM requires that a (key, nonce) pair never repeats. Repeat it once and XOR-ing the two ciphertexts gives the XOR of the two plaintexts, and the attacker can recover the authentication key to forge data.

  • Common causes: a fixed nonce in configuration, a counter nonce that resets on restart, nonces from Random instead of SecureRandom.
  • Random 96-bit nonces are safe up to ~2^32 encryptions per key; beyond that you must rotate keys. Envelope encryption, below, handles it naturally because each record or batch gets its own data key.
Read in post: Storing passwords and encrypting personal data
TILSeniorDeleting the data key is the practical way to "erase" data that sits in backupsThe right to erasure (GDPR, Decree 13/2023) is hard to honour because the data also lives in backups, replicas, snapshots and exports that nobody can edit one by one. If each customer (or small group) has its own DEK wrapped by the KMS, deleting that DEK turns every copy of the ciphertext, wherever it is, into undecryp

The right to erasure (GDPR, Decree 13/2023) is hard to honour because the data also lives in backups, replicas, snapshots and exports that nobody can edit one by one. If each customer (or small group) has its own DEK wrapped by the KMS, deleting that DEK turns every copy of the ciphertext, wherever it is, into undecryptable noise. The technique is called crypto-shredding. The cost: many DEKs to manage, and a cache so you don't hit the KMS for every row.

Read in post: Storing passwords and encrypting personal data
Trade-offSeniorA blind index buys searchability with a controlled amount of leakageEquality only: no LIKE, no full-text, no ranges, no sorting. Leakage: anyone who can read the table sees which rows share a value and how often; for low-cardinality columns (gender, province) frequency analysis gives the values away, so never build a blind index on them. Reducing the leak: truncate the HMAC so collisio
  • Equality only: no LIKE, no full-text, no ranges, no sorting.
  • Leakage: anyone who can read the table sees which rows share a value and how often; for low-cardinality columns (gender, province) frequency analysis gives the values away, so never build a blind index on them.
  • Reducing the leak: truncate the HMAC so collisions happen on purpose (each lookup returns a few candidate rows that you decrypt and filter).
  • Prefix or fuzzy search: use tokenization (a separate service that maps tokens to values), or leave that column unencrypted and protect it with access control, masking on display and audit logs.
Read in post: Storing passwords and encrypting personal data
InterviewJuniorWhy shouldn't passwords be stored with SHA-256?

SHA-256 is too fast and unsalted, so both brute force and rainbow tables are cheap.

A GPU tries billions of passwords per second, and without a salt the same password gives the same hash, so they can be reversed in bulk. Use a slow, salted password-hashing function with a cost parameter: Argon2id, scrypt, bcrypt, or PBKDF2 when FIPS is required. In Spring, use DelegatingPasswordEncoder.

Read in post: Storing passwords and encrypting personal data
InterviewJuniorWhat is a salt, and does it need to be secret?

A salt is a random value unique to each password, and it doesn't need to be secret.

It's mixed in before hashing so identical passwords give different hashes and rainbow tables become useless. It's stored right next to the hash (bcrypt and Argon2 embed it in their output string). A shared secret kept outside the DB is called a pepper.

Read in post: Storing passwords and encrypting personal data
InterviewJuniorWhy hash passwords instead of encrypting them?

Because the system never needs to read a password back; it just hashes the input again and compares.

Encryption means a decryption key exists somewhere on the server, so a server-plus-DB breach exposes every password. One-way hashing with a slow, salted function means that even with the DB in hand, an attacker must guess each password at a high cost.

Read in post: Storing passwords and encrypting personal data
InterviewMidWhat do you watch out for when encrypting a national ID column with AES in Java?

AES/GCM/NoPadding with a fresh nonce and AAD every time, the key in a KMS, stored as binary.

  • Never plain "AES" (ECB).
  • A 12-byte nonce from SecureRandom per encryption, stored with the ciphertext; never reuse a nonce under the same key.
  • AAD bound to the primary key and column name. Store as bytea/VARBINARY.
  • Keep the key out of config: envelope encryption with a KMS, and a key_id on every ciphertext for rotation.
  • If you need to search, add a blind index.
Read in post: Storing passwords and encrypting personal data
InterviewMidWhich password-hashing algorithm would you pick today? Is bcrypt obsolete?

Argon2id first; bcrypt isn't obsolete and is still Spring Security's default.

Following OWASP: Argon2id (CPU- and memory-hard, which removes the GPU advantage), then scrypt, bcrypt with cost ≥ 10, and PBKDF2-HMAC-SHA256 with 600,000 iterations when FIPS is required. With bcrypt, mind the 72-byte limit. Tune parameters so a check takes ~100–500 ms on production hardware, and store algorithm-prefixed strings so you can upgrade gradually.

Read in post: Storing passwords and encrypting personal data
InterviewSeniorDesign storage and lookup for encrypted customer phone numbers.

AES-GCM in the application layer with envelope encryption, plus a blind index column for equality lookups.

  • Encrypt under a DEK wrapped by a KEK in the KMS, with the DEK cached briefly.
  • A phone_enc bytea column holds key_id, nonce, ciphertext and tag; the AAD is the customer id plus the column name.
  • phone_bidx: an HMAC-SHA256 under a separate index key over the normalized value (E.164, the international format like +84...), truncated and indexed. Equality search only; be explicit about the leakage (shared values, frequencies).
  • Rotating the KEK only re-wraps DEKs; rotating the index key means recomputing the bidx column.
  • Also enable disk encryption in the DB, mask numbers on display, and audit every decryption.
Read in post: Storing passwords and encrypting personal data
InterviewSeniorYou inherit a system that stores unsalted MD5. What's your upgrade plan?

Don't wait for logins: wrap every hash in bcrypt(md5) now, then upgrade each user when they log in.

  • Wrapping job: bcrypt(md5) (or Argon2id) under a dedicated prefix, and delete the MD5 values.
  • On login: verify through the legacy branch, then re-hash the real password with the current encoder.
  • In parallel: force resets if there's any sign the DB has already leaked, block passwords found in breach lists, rate-limit logins, and require MFA for admin accounts.
  • Measure hashing time on production hardware to choose the cost.
Read in post: Storing passwords and encrypting personal data
InterviewSeniorWhat happens if you reuse a nonce with AES-GCM, and how do you prevent it?

You lose both secrecy and integrity: the XOR of the plaintexts leaks and the attacker can forge ciphertexts.

Same key and nonce for two messages: XOR-ing the two ciphertexts yields the XOR of the plaintexts, and the authentication key can be recovered. Prevention: random 96-bit nonces from SecureRandom with a cap of ~2^32 encryptions per key, or a persistently stored counter nonce. At high volume, use per-record or per-batch DEKs (envelope encryption), or AES-GCM-SIV, which tolerates nonce reuse.

Read in post: Storing passwords and encrypting personal data
Edge caseMidA PostgreSQL timestamp column silently drops the offsetIf the application sometimes writes UTC and sometimes Vietnam time into the same timestamp column, the data becomes impossible to untangle. When you compare timestamp with timestamptz, PostgreSQL casts using the session TimeZone, so query results change with connection settings. Rule: moments always go in timestamptz;

If the application sometimes writes UTC and sometimes Vietnam time into the same timestamp column, the data becomes impossible to untangle.

When you compare timestamp with timestamptz, PostgreSQL casts using the session TimeZone, so query results change with connection settings. Rule: moments always go in timestamptz; use timestamp only for wall-clock values that have a zone id column next to them.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Trade-offMidPostgreSQL timestamptz or timestamptimestamptz: compares and sorts correctly wherever the client is; display, ::date and datetrunc depend on the session. timestamp: fits pure wall-clock data (appointments with a zone id, a train ticket printed in local time). Using it for moments means relying on an unwritten "this is UTC" assumption, which will be brok
  • timestamptz: compares and sorts correctly wherever the client is; display, ::date and date_trunc depend on the session.
  • timestamp: fits pure wall-clock data (appointments with a zone id, a train ticket printed in local time). Using it for moments means relying on an unwritten "this is UTC" assumption, which will be broken one day.

Default for every *_at column: timestamptz (the PostgreSQL wiki's "Don't Do This" page says the same). Same 8 bytes, so there's no "saving space" argument for timestamp.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Edge caseMidFiltering by day with created_at::date depends on the session and skips the indexWHERE createdat::date = '2024-06-10' is wrong twice: "10 June" is computed in the session, so a report run from the app (UTC) and from a developer machine (Vietnam time) return different numbers. Wrapping the column in an expression stops a B-tree index on createdat from being used (the predicate isn't sargable). Write

WHERE created_at::date = '2024-06-10' is wrong twice:

  • "10 June" is computed in the session, so a report run from the app (UTC) and from a developer machine (Vietnam time) return different numbers.
  • Wrapping the column in an expression stops a B-tree index on created_at from being used (the predicate isn't sargable).

Write a half-open range with explicit offsets: WHERE created_at >= '2024-06-10T00:00+07:00' AND created_at < '2024-06-11T00:00+07:00'. Whose day it is gets decided in code, not by connection settings. If you have to group by day, PostgreSQL 12+ has date_trunc('day', created_at, 'Asia/Ho_Chi_Minh') so the zone is explicit.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Trade-offMidMySQL TIMESTAMP or DATETIME for momentsTIMESTAMP: clients in other zones automatically read their own local time; 4 bytes (plus the fraction). But it runs out in 2038, and two services with different session settings see two different times for the same row. DATETIME: no 2038 limit, no implicit conversion. In exchange the database doesn't know whose clock t
  • TIMESTAMP: clients in other zones automatically read their own local time; 4 bytes (plus the fraction). But it runs out in 2038, and two services with different session settings see two different times for the same row.
  • DATETIME: no 2038 limit, no implicit conversion. In exchange the database doesn't know whose clock the value is, so every client must follow one convention (usually "always UTC"), and that convention has to be enforced in the driver/ORM.

New systems usually pick DATETIME(6) in UTC with the driver forced to UTC, because long-lived data (contracts, loans, warranties) crosses 2038 sooner than you'd think. Use TIMESTAMP only when the value is always close to now (like updated_at) and there's a plan to migrate before 2038.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Edge caseMidMySQL rounds fractional seconds, so what you read back isn't what you wroteThe default is zero fractional digits, and MySQL rounds rather than truncates: 09:20:52.6 becomes 09:20:53 (which can roll into the next second, minute or even day), and .1239 in a DATETIME(3) becomes .124. Meanwhile Instant.now() on JDK 15+ usually has microseconds. The result: save-and-reload tests fail at random, up

The default is zero fractional digits, and MySQL rounds rather than truncates: 09:20:52.6 becomes 09:20:53 (which can roll into the next second, minute or even day), and .1239 in a DATETIME(3) becomes .124. Meanwhile Instant.now() on JDK 15+ usually has microseconds.

The result: save-and-reload tests fail at random, updated_at comparisons (optimistic locking) don't match, and time-based pagination cursors skip or repeat rows.

To avoid it: declare the precision (DATETIME(6); PostgreSQL defaults to microseconds), truncate in Java before writing (instant.truncatedTo(ChronoUnit.MICROS) or MILLIS), or enable the TIME_TRUNCATE_FRACTIONAL SQL mode so MySQL truncates instead of rounding.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Trade-offSeniorFuture appointments: store an instant or wall-clock time plus zone idStore an instant (timestamptz): simple, easy to query and index, correct for anything that has happened or will happen within days. If the rules change before the appointment, the displayed time drifts. Store wall-clock time plus zone id: preserves the user's intent whatever the rules do. The price: converting when you
  • Store an instant (timestamptz): simple, easy to query and index, correct for anything that has happened or will happen within days. If the rules change before the appointment, the displayed time drifts.
  • Store wall-clock time plus zone id: preserves the user's intent whatever the rules do. The price: converting when you query by moment, handling times in DST gaps or overlaps, validating zone ids.

The usual combination: wall-clock time plus zone id as the source of truth, a precomputed instant column for indexing and scheduling, and a job that recomputes it after every tzdata update. Things that have already happened (created_at, paid_at) are always stored as instants.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Trade-offMidISO 8601 strings or epoch numbers in a JSON APIRFC 3339 strings ("2023-09-25T09:20:52.342Z"): readable when debugging and in logs, unambiguous about unit and region because they carry an offset, and sortable as text when the offset and length are the same. A few more bytes, and clients have to parse them. Epoch numbers (1695633652342): compact, fast to compare, no
  • RFC 3339 strings ("2023-09-25T09:20:52.342Z"): readable when debugging and in logs, unambiguous about unit and region because they carry an offset, and sortable as text when the offset and length are the same. A few more bytes, and clients have to parse them.
  • Epoch numbers (1695633652342): compact, fast to compare, no parsing. But the unit isn't self-describing (seconds or milliseconds?), they're unreadable to humans, and JavaScript only represents integers exactly up to 2^53: enough for today's milliseconds and microseconds, not for nanoseconds (about 1.7 × 10^18).

Default: RFC 3339 in UTC (Z) for moments and "2023-10-01" for dates. If you must use numbers (performance, IoT devices), put the unit in the field name (createdAtMs) and document it in the OpenAPI spec.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Edge caseMidJackson normalises an OffsetDateTime's offset to UTC when reading JSONDeserializationFeature.ADJUSTDATESTOCONTEXTTIMEZONE is on by default, so Jackson converts OffsetDateTime/ZonedDateTime into the context time zone (UTC unless configured): "2023-09-25T16:20:52+07:00" becomes 2023-09-25T09:20:52Z. The moment is still right, but "the customer paid at 16:20 their time" is lost, and equals

DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE is on by default, so Jackson converts OffsetDateTime/ZonedDateTime into the context time zone (UTC unless configured): "2023-09-25T16:20:52+07:00" becomes 2023-09-25T09:20:52Z.

The moment is still right, but "the customer paid at 16 their time" is lost, and equals against the original returns false. If the offset matters to the business, disable the feature (spring.jackson.deserialization.adjust-dates-to-context-time-zone=false) or keep the zone id as a separate field. If you don't need the offset, use Instant to make the intent clear.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewJuniorDoes PostgreSQL's timestamptz store a time zone?

No. It stores a UTC moment (microseconds); to remember the original zone you store the zone id in a separate column.

On write, a value with an offset is converted to UTC and a value without one is interpreted in the session TimeZone; on read, it's displayed in the session TimeZone.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewJuniorWhich column type should created_at use?

PostgreSQL timestamptz; MySQL DATETIME(6) with a UTC convention enforced in the driver; Java Instant.

MySQL TIMESTAMP(6) also works if the 2038 limit is acceptable. Not timestamp without time zone, and not DATETIME without a clear UTC convention, because nobody can tell whose clock the value is.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewJuniorWhich format should an API use for dates and times?

Moments: RFC 3339 strings with an offset, usually UTC ("2023-09-25T09:20:52.342Z"). Calendar dates: "2023-10-01".

Not display formats like 25/09/2023 or Date#toString. Displaying in the user's local time is the frontend's job.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewMidHow do MySQL TIMESTAMP and DATETIME differ?

TIMESTAMP stores UTC and converts per session time_zone, only up to 2038; DATETIME stores the value as is, from the year 1000 to 9999.

The TIMESTAMP range is 1970 to 2038-01-19 03:14 UTC. Both default to zero fractional digits and round the fraction. For data that may go past 2038, or when you want no implicit conversion, use DATETIME(6) with a UTC convention.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewMidWhy is WHERE created_at::date = '2024-06-10' a poor filter?

Because the "date" depends on the session TimeZone, and wrapping the column in an expression stops the index from being used.

PgJDBC sets the session from the JVM's zone, so the same query returns different results depending on who runs it. Write a half-open range with explicit offsets: created_at >= '2024-06-10T00:00+07:00' AND created_at < '2024-06-11T00:00+07:00'.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewMidA save-and-reload test on an Instant sometimes isn't equal. Why?

The database rounds fractional seconds, so the value read back differs from the one written.

Instant.now() may have micro- or nanoseconds; PostgreSQL keeps microseconds (rounding the nanos), and MySQL keeps whatever the column precision is (default 0) and rounds. Fix: declare column precision explicitly, truncatedTo in code before writing, and use Clock.fixed in tests.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewMidSpring Boot returns a LocalDate as [2023,10,1]. What happened?

The ObjectMapper in use has JavaTimeModule but WRITE_DATES_AS_TIMESTAMPS still enabled, usually because someone built their own mapper instead of Boot's bean.

Typical causes: new ObjectMapper(), or overriding Boot's bean without the builder; Boot disables that feature by default. Fix: use the Spring-managed ObjectMapper (or Jackson2ObjectMapperBuilder), or disable SerializationFeature.WRITE_DATES_AS_TIMESTAMPS; add a serialisation test for DTOs with dates.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewSeniorDesign storage for future appointments in a multi-country booking app.

The source of truth is the wall-clock time the user chose plus an IANA zone id, because time zone rules may change before the appointment; the instant is only a precomputed column.

  • PostgreSQL: timestamp + text. Add start_at timestamptz for indexing, reminder scheduling and time-range queries; a job recomputes it for future appointments after every tzdata update.
  • Validate zone ids on input.
  • Times in DST gaps or overlaps: an explicit policy (shift past the gap, pick the earlier offset in an overlap), and tell the user.
  • The API returns both the local time with zone and the instant.
Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewSeniorYou find a MySQL system whose DATETIME columns mix UTC and Vietnam time. What do you do?

First stop the bleeding by forcing every layer to UTC, then classify the old data and migrate with expand/contract.

  • Force the JVM and Connector/J to UTC (connectionTimeZone=UTC, forceConnectionTimeZoneToSession=true), and record when that was deployed.
  • Classify existing data by writer and by time period (which service and version wrote which zone), using reference data such as logs with instants or time-based IDs to determine the offset.
  • Migrate: a new DATETIME(6) UTC column, a batched backfill with CONVERT_TZ, dual writes, report reconciliation, then drop the old column.
  • Write an ADR for the convention and add write-then-read integration tests.
Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
InterviewSeniorWhy can Jackson lose information when reading an OffsetDateTime, and how do you decide what to do?

ADJUST_DATES_TO_CONTEXT_TIME_ZONE is on by default, so the offset is normalised to UTC: the moment is right but the original offset is gone. Decide by business need.

If you only need the moment, use Instant in the DTO to make that explicit. If the user's offset or region matters (invoices printed in local time, behaviour analysis by hour of day), disable the feature or receive the zone id as a separate field and store it separately, since timestamptz doesn't keep the offset either.

Read in post: Storing dates and times in PostgreSQL, MySQL and JSON
Edge caseMidA "choose two" question with only one correct answer is a sign the circulating set is wrongIn the question set handed out with the course, many questions mark two answers when only one is correct (the number of controllers, Streams' exactly-once, who rejects a schema). When an "official" answer contradicts the Kafka docs, trust the docs and check in a lab. The table in section 8 lists what I verified.

In the question set handed out with the course, many questions mark two answers when only one is correct (the number of controllers, Streams' exactly-once, who rejects a schema). When an "official" answer contradicts the Kafka docs, trust the docs and check in a lab. The table in section 8 lists what I verified.

Read in post: CCDAK practice part 2
InterviewJuniorHow do subscribe() and assign() differ?

subscribe() joins a consumer group, so Kafka splits partitions and rebalances; assign() picks fixed partitions yourself, with no group management.

assign() suits replay or inspection tools, or managing offsets externally. The two can't be mixed on one consumer.

Read in post: CCDAK practice part 2
InterviewJuniorHow do KStream and KTable differ?

A KStream is a sequence of events, each record something that happened; a KTable is the latest state per key, where a later record overwrites an earlier one.

Transactions are a KStream, current balances a KTable. Aggregating a KStream produces a KTable.

Read in post: CCDAK practice part 2
InterviewMidHow do RangeAssignor and CooperativeStickyAssignor differ?

Range splits per topic, so it skews when you subscribe to many topics; CooperativeSticky balances evenly, keeps the previous assignment as much as possible and rebalances incrementally without stopping the whole group.

With Range, every rebalance makes every consumer give up all its partitions (eager). Cooperative only moves the partitions that must move, so other consumers keep running.

Read in post: CCDAK practice part 2
InterviewMidHow does Schema Registry work during one produce and consume?

The serializer registers (or looks up) the schema, gets an ID and writes it into the record's first 5 bytes; the deserializer reads the ID, checks its cache or asks the Registry, then decodes.

The Registry checks compatibility at registration and stores schemas in the _schemas topic. Brokers never read payloads, so they never reject data over a schema.

Read in post: CCDAK practice part 2
InterviewSeniorA sink connector is slow. How do you scale it?

Raise tasks.max up to the source topic's partition count, add workers if their CPU or network is saturated; beyond the partition count you must add partitions.

First check whether the bottleneck is the target system (S3, Elasticsearch): more tasks just pile more load on it. Tuning the connector's batching (flush size, records per write) is often more effective than more tasks.

Read in post: CCDAK practice part 2
InterviewSeniorHow do you assess a candidate who only memorised CCDAK questions?

Ask for reasons instead of answers: why Range skews, why committing first is at-most-once, what the Registry does when it meets an unknown ID.

People who memorised usually get the letter right but can't explain it, and often carry the circulating set's wrong answers. I give a new scenario (changing the partition count, moving a service to another machine) to see whether they can reason it through.

Read in post: CCDAK practice part 2
Edge caseJuniorBase64 is not encryption: JWT payloads and Basic auth headers are readable by anyoneBase64 is undone with one command (base64 -d). An Authorization: Basic ... header contains the raw username:password; an ordinary JWT payload can be read on jwt.io. So never put sensitive data in a JWT payload because "it's encoded", and only accept Basic auth over TLS. In code review, Base64.getEncoder() called on a p

Base64 is undone with one command (base64 -d). An Authorization: Basic ... header contains the raw username:password; an ordinary JWT payload can be read on jwt.io. So never put sensitive data in a JWT payload because "it's encoded", and only accept Basic auth over TLS. In code review, Base64.getEncoder() called on a password or a card number is a red flag.

Read in post: Encoding, hashing, encryption and signatures
Edge caseMidMD5 and SHA-1 are not "strong checksums"Some material files MD5 and SHA-1 under "strong checksum". They're only fit for checksums without an adversary (a corrupted copy, partition keys, ETags). Anywhere someone deliberately forges things (signatures, certificates, packages, passwords) use SHA-256 or SHA-3/BLAKE2; Git is slowly moving to SHA-256 for this reas

Some material files MD5 and SHA-1 under "strong checksum". They're only fit for checksums without an adversary (a corrupted copy, partition keys, ETags). Anywhere someone deliberately forges things (signatures, certificates, packages, passwords) use SHA-256 or SHA-3/BLAKE2; Git is slowly moving to SHA-256 for this reason. For passwords even SHA-256 is the wrong tool (see part 2).

Read in post: Encoding, hashing, encryption and signatures
Trade-offMidSymmetric vs asymmetric: the difference is key distribution, not "which is more secure"The course slide says symmetric is "faster but less secure". The speed half is right, the security half isn't: AES-256 is not weaker than RSA-3072; strength depends on key size and correct use. The real difference is key distribution: symmetric needs both parties to hold the secret (exchanged over a safe channel, one k

The course slide says symmetric is "faster but less secure". The speed half is right, the security half isn't: AES-256 is not weaker than RSA-3072; strength depends on key size and correct use. The real difference is key distribution: symmetric needs both parties to hold the secret (exchanged over a safe channel, one key per pair), while asymmetric lets you publish the encryption or verification key.

That's why real systems are hybrid: TLS uses ECDHE (asymmetric) to agree on a session key, then encrypts the data with AES-GCM or ChaCha20-Poly1305. Same party encrypts and decrypts (a DB column): symmetric. Sender and receiver can't share a secret: asymmetric.

Read in post: Encoding, hashing, encryption and signatures
Edge caseSeniorRolling your own sha256(secret + message) instead of HMACSHA-256 and SHA-512 use the Merkle–Damgård construction: knowing sha256(secret || message) and the secret's length is enough to compute sha256(secret || message || padding || extra) without the secret. That's a length-extension attack: the attacker appends &amount=1 and computes a valid "signature" themselves. HMAC (tw

SHA-256 and SHA-512 use the Merkle–Damgård construction: knowing sha256(secret || message) and the secret's length is enough to compute sha256(secret || message || padding || extra) without the secret. That's a length-extension attack: the attacker appends &amount=1 and computes a valid "signature" themselves. HMAC (two keyed hash passes) was designed to prevent exactly this, so use Mac.getInstance("HmacSHA256") and don't invent your own.

Compare signatures with MessageDigest.isEqual, not String.equals: the latter stops at the first differing byte and leaks information through response time.

Read in post: Encoding, hashing, encryption and signatures
Trade-offSeniorHMAC or a digital signature between two partiesOne issuer, many verifiers: signatures. Two parties who trust each other and want speed: HMAC.
HMAC Digital signature
Keys Both sides share one secret Only the signer holds the private key; the public key can go to any number of verifiers
Non-repudiation No: the receiver can also produce a signature "from" the sender Yes
Speed, size Fast, short signatures, simple code Slower, longer (RSA-2048: 256 bytes, Ed25519: 64 bytes)
Operational cost One secret per partner, distributed and rotated safely Managing the public key's lifecycle
Fits One-to-one integrations: merchant and payment gateway, webhooks An identity provider's JWKS, signed e-invoices

One issuer, many verifiers: signatures. Two parties who trust each other and want speed: HMAC.

Read in post: Encoding, hashing, encryption and signatures
Edge caseMidSigning is not "encrypting the hash with the private key"Many diagrams (the course slide included) describe a signature as "encrypt the hash with the private key, decrypt with the public key". That only holds for textbook RSA: ECDSA and Ed25519 involve no "encryption" at all, and real RSA uses different padding for signing (PSS) and encryption (OAEP). Use the verbs "sign" an

Many diagrams (the course slide included) describe a signature as "encrypt the hash with the private key, decrypt with the public key". That only holds for textbook RSA: ECDSA and Ed25519 involve no "encryption" at all, and real RSA uses different padding for signing (PSS) and encryption (OAEP). Use the verbs "sign" and "verify", and the Signature API rather than Cipher with a private key.

Likewise, "SHA-256 is used for digital signatures" means SHA-256 is the hash inside a scheme such as RSA-PSS-SHA256 or ECDSA-P256-SHA256; on its own it signs nothing.

Read in post: Encoding, hashing, encryption and signatures
Edge caseMidDisabling certificate validation "to make it work" disables TLSWhen an internal API with a self-signed certificate throws PKIXPathBuildingFailedException, the quick Stack Overflow fix is a TrustManager that accepts every certificate or a HostnameVerifier that always returns true. The connection is still encrypted, but the client no longer knows who's on the other end, so anyone in

When an internal API with a self-signed certificate throws PKIXPathBuildingFailedException, the quick Stack Overflow fix is a TrustManager that accepts every certificate or a HostnameVerifier that always returns true. The connection is still encrypted, but the client no longer knows who's on the other end, so anyone in the middle (public Wi-Fi, a compromised proxy) can impersonate the server.

The proper fix: put the internal CA in an application-specific truststore (Spring Boot 3.1+ has SSL bundles: spring.ssl.bundle.pem.<name>.truststore.certificate) and keep host name verification on. Add a test or static-analysis rule that keeps empty X509TrustManagers out.

Read in post: Encoding, hashing, encryption and signatures
TILMidJava 21 ships Ed25519, ChaCha20-Poly1305 and TLS 1.3JDK 11 added TLS 1.3 and ChaCha20-Poly1305, JDK 15 added Ed25519/Ed448 signatures (Signature.getInstance("Ed25519")), JDK 17 added HexFormat: most backend crypto needs require no extra library. What's missing is Argon2id, bcrypt and scrypt: take them from Spring Security Crypto (Argon2PasswordEncoder uses Bouncy Castle

JDK 11 added TLS 1.3 and ChaCha20-Poly1305, JDK 15 added Ed25519/Ed448 signatures (Signature.getInstance("Ed25519")), JDK 17 added HexFormat: most backend crypto needs require no extra library. What's missing is Argon2id, bcrypt and scrypt: take them from Spring Security Crypto (Argon2PasswordEncoder uses Bouncy Castle) rather than implementing them. The general rule: never implement algorithms, only choose and compose vetted building blocks.

Read in post: Encoding, hashing, encryption and signatures
InterviewJuniorHow do encoding, hashing and encryption differ?

Encoding changes the format, hashing makes a one-way fingerprint, encryption keeps things secret with a key.

Encoding has no key and anyone can reverse it (Base64, URL encoding), so it has no security value. Hashing produces a fixed-length value, used for integrity checks, hash indexes, dedup. Encryption needs a key and is reversible for whoever holds it. To prove origin you add a MAC or a digital signature.

Read in post: Encoding, hashing, encryption and signatures
InterviewJuniorDoes Base64 protect data? Is a JWT payload secret?

No, anyone can read both.

Base64 is an encoding with no key, decoded with one command. An ordinary JWT payload (a JWS) is only Base64url-encoded; the signature prevents tampering, not reading. Don't put sensitive data in the payload; if it must be hidden, encrypt it (JWE) or use an opaque reference token.

Read in post: Encoding, hashing, encryption and signatures
InterviewMidHow is an HMAC different from a plain hash, and why not use sha256(secret + message)?

An HMAC is a keyed hash, so it also proves origin; concatenating the secret and the message yourself is open to length extension.

With a plain hash, whoever modifies the data simply recomputes it. With sha256(secret || message) on SHA-2, one valid signature lets an attacker compute a signature for an extended message without the secret. HMAC's two-pass construction avoids that. Compare signatures in constant time.

Read in post: Encoding, hashing, encryption and signatures
InterviewMidWhen do you use an HMAC and when a digital signature?

HMAC when two parties trust each other and share a secret; a signature when one party issues and many verify.

HMAC is fast and simple, a good fit for signing payment gateway requests or webhooks; but the receiver can also produce signatures, so there's no non-repudiation, and each partner needs its own secret. With a signature only the issuer holds the private key and the public key is published via JWKS, as with identity provider tokens or TLS certificates.

Read in post: Encoding, hashing, encryption and signatures
InterviewMidIs symmetric or asymmetric encryption more secure?

Neither family is inherently "more secure"; strength depends on key size and correct use (AES-256 is on par with or stronger than RSA-3072).

The differences are key distribution and speed: symmetric is fast but both sides must share a secret; asymmetric is slow but half the key can be public. In practice it's hybrid: TLS agrees on a session key with ECDHE and then encrypts the data with AES-GCM.

Read in post: Encoding, hashing, encryption and signatures
InterviewSeniorWhy does a payment request still need an HMAC when we already use HTTPS?

Because HTTPS protects each hop, while the request passes through the customer's browser, where the user can edit the URL.

The request goes from the backend, through the browser, and only then to the gateway; TLS also terminates at load balancers and proxies. An HMAC over the payload gives end-to-end integrity and origin regardless of the path. It doesn't stop replays: that needs a unique transaction reference, an expiry and a state machine on the receiving side.

Read in post: Encoding, hashing, encryption and signatures
InterviewSeniorWhat does TLS protect, and what doesn't it?

TLS gives confidentiality and integrity on one hop and authenticates the server through a certificate; it doesn't cover data after the termination point, in the browser, or at rest.

It also authenticates the client with mTLS. The termination point is the load balancer or proxy, and then come the logs. It's worthless if the client disables certificate or host name validation: the connection is still encrypted, just with whoever sits in the middle. For end-to-end integrity, sign the payload (HMAC, digital signature).

Read in post: Encoding, hashing, encryption and signatures
InterviewSeniorHow do you design rotation of a webhook signing secret or an encryption key without downtime?

Put a key_id on every signature, token and ciphertext, and run a transition period that accepts both the old and the new key.

  • The verifier accepts both keys, the signer switches to the new one, you wait until data signed with the old key expires (or re-encrypt it), then remove the old key.
  • Secrets live in a secret manager or KMS and can be loaded dynamically or reloaded; each service reads only its own.
  • If a secret leaks, rotate first and investigate second.
  • For large encrypted datasets, envelope encryption means rotating the KEK only re-encrypts the DEKs.
Read in post: Encoding, hashing, encryption and signatures
Edge caseSeniorThe JVM caches DNS, and an open connection never asks DNS againThe JVM cache is configured by the security property networkaddress.cache.ttl in java.security (not a -D flag). JDK 21 documents it: without a SecurityManager it caches for 30 seconds, with one it caches forever; failed lookups are cached for 10 seconds (negative.ttl). I measured 43 ms for the first lookup and 0 ms for

The JVM cache is configured by the security property networkaddress.cache.ttl in java.security (not a -D flag). JDK 21 documents it: without a SecurityManager it caches for 30 seconds, with one it caches forever; failed lookups are cached for 10 seconds (negative.ttl). I measured 43 ms for the first lookup and 0 ms for the second.

The bigger trap: DNS is only consulted when a new connection is opened. When a database fails over by changing a CNAME (as RDS does), the pool keeps connections to the old IP. You need short TTLs and the pool's maxLifetime so connections are recreated regularly.

Read in post: Networking for backend engineers
Trade-offSeniorTune the kernel for TIME_WAIT or fix the applicationnet.ipv4.tcptwreuse (reuse TIMEWAIT sockets for outgoing connections) and a wider iplocalportrange are painkillers. The disease is usually one new connection per request: share the HTTP client, enable keep-alive to upstreams (see the reverse proxy post), use a pool. Don't look for tcptwrecycle: it broke clients behind

net.ipv4.tcp_tw_reuse (reuse TIME_WAIT sockets for outgoing connections) and a wider ip_local_port_range are painkillers. The disease is usually one new connection per request: share the HTTP client, enable keep-alive to upstreams (see the reverse proxy post), use a pool. Don't look for tcp_tw_recycle: it broke clients behind NAT and was removed in Linux 4.12.

Read in post: Networking for backend engineers
Edge caseMidConnection reset right after an idle period: a stale pooled connectionThe first request after a few idle minutes fails with Connection reset (Apache HttpClient: NoHttpResponseException), and the next one works. The server or LB closed the idle keep-alive connection (after 60 seconds, say), but the client pool still held it and handed it out. Fix: have the client pool evict idle connectio

The first request after a few idle minutes fails with Connection reset (Apache HttpClient: NoHttpResponseException), and the next one works. The server or LB closed the idle keep-alive connection (after 60 seconds, say), but the client pool still held it and handed it out.

Fix: have the client pool evict idle connections before the server's keep-alive timeout, and retry idempotent requests once.

Read in post: Networking for backend engineers
Edge caseSeniorNAT and LB idle timeouts make DB connections hang for many minutesPer AWS documentation: NAT Gateway and NLB drop idle TCP connections after 350 seconds, ALB after 60 seconds by default. Linux TCP keepalive only probes after 7200 seconds, far too late. A JDBC connection idle for 10 minutes behind NAT "dies silently": the next query gets no answer, and TCP retransmits for about 15 min

Per AWS documentation: NAT Gateway and NLB drop idle TCP connections after 350 seconds, ALB after 60 seconds by default. Linux TCP keepalive only probes after 7200 seconds, far too late. A JDBC connection idle for 10 minutes behind NAT "dies silently": the next query gets no answer, and TCP retransmits for about 15 minutes (tcp_retries2=15) unless there's a read timeout.

Fix: a pool maxLifetime shorter than every timeout on the path, the pool's keepaliveTime to keep idle connections alive, and always a socket/query timeout. Details in Connection pooling and HikariCP.

Read in post: Networking for backend engineers
TILSeniorTest MTU problems with a do-not-fragment pingLinux: ping -M do -s 1472 host (1472 + 28 header bytes = 1500); macOS: ping -D -s 1472 host. Shrink the size until it passes and you know the real path MTU. I haven't tried this on a path with a real MTU fault.

Linux: ping -M do -s 1472 host (1472 + 28 header bytes = 1500); macOS: ping -D -s 1472 host. Shrink the size until it passes and you know the real path MTU. I haven't tried this on a path with a real MTU fault.

Read in post: Networking for backend engineers
Edge caseMidExpired certificates are the most common mTLS incidentWhen one expires, every call between services fails at once with certificateexpired or badcertificate. Automate rotation (cert-manager, mesh), alert weeks ahead, and check with openssl sclient -connect host:443 -servername host | openssl x509 -noout -dates.

When one expires, every call between services fails at once with certificate_expired or bad_certificate. Automate rotation (cert-manager, mesh), alert weeks ahead, and check with openssl s_client -connect host:443 -servername host | openssl x509 -noout -dates.

Read in post: Networking for backend engineers
TILMidcurl counts new connections with num_connectsAdd %{numconnects} to -w: fetch two URLs in one curl command and the first prints 1, the second 0 with DNS, connect and TLS all at zero. That's proof the connection was reused.

Add %{num_connects} to -w: fetch two URLs in one curl command and the first prints 1, the second 0 with DNS, connect and TLS all at zero. That's proof the connection was reused.

Read in post: Networking for backend engineers
InterviewJuniorWhat happens when your service calls https://api.example.com/orders?

DNS lookup to get the IP, TCP handshake (1 RTT), TLS handshake (1 RTT with TLS 1.3), send the request and wait for the response (1 RTT + server time); the connection is kept for next time.

Measured with a 48 ms RTT: 166 ms on a new connection, 52 ms on a reused one.

Read in post: Networking for backend engineers
InterviewJuniorWhat's the difference between a connect timeout and a read timeout?

A connect timeout limits how long opening the connection may take; a read timeout limits how long you wait for data on an open connection.

Set the connect timeout to 1–2 seconds and the read timeout from the peer's p99, plus an overall deadline if you retry.

Read in post: Networking for backend engineers
InterviewMidWhat is TIME_WAIT and when does it become a problem?

The state where the side that closed first keeps the socket for 2×MSL (60 seconds on Linux) so late packets can't leak into a new connection; it hurts when one client opens many short connections to the same destination.

There are only about 28,000 ephemeral ports per destination; the symptom is Cannot assign requested address. Fix it with keep-alive and connection pooling.

Read in post: Networking for backend engineers
InterviewMidHow do L4 and L7 load balancers differ, and when do you pick each?

L4 forwards TCP/UDP per connection without reading the content; L7 understands HTTP and balances and routes per request.

L4 is fast, protocol-agnostic and can pass TLS through. L7 routes by path/header, retries, and spreads HTTP/2 and gRPC load correctly.

Read in post: Networking for backend engineers
InterviewMidThe logs show Connection reset by peer. Which causes come to mind?

The peer, or a box in the middle, sent an RST: usually a reused connection that was closed for being idle, a peer process that died, or an LB/NAT that forgot the connection.

Check whether errors follow idle periods or coincide with deployments, and use tcpdump to see which IP sent the RST. Make the pool's idle timeout shorter than the peer's and retry idempotent requests.

Read in post: Networking for backend engineers
InterviewSeniorThe DB failed over, but the Java service kept failing for minutes. Why?

Open pooled connections still point to the old IP because DNS is only consulted for new connections, on top of the JVM DNS cache and the record's TTL.

You need short DNS TTLs, a low networkaddress.cache.ttl, socket timeouts to detect dead connections, and maxLifetime so connections get replaced regularly.

Read in post: Networking for backend engineers
InterviewSeniorThe first query after a quiet night hangs about 15 minutes before failing. How do you investigate?

Suspect a NAT, firewall or LB idle timeout straight away: the idle connection was dropped from a state table, packets are discarded, and TCP retransmits until it gives up.

15 minutes matches tcp_retries2=15. Check idle timeouts on the path (NAT Gateway, NLB 350 seconds); tcpdump shows retransmits with no ACK. Fix: maxLifetime shorter than that timeout, the pool's keepaliveTime, and socket timeouts.

Read in post: Networking for backend engineers
Trade-offMidMaven or GradleMaven: declarative XML, little magic, every project looks the same, IDE and CI support out of the box. The cost: customising build steps is awkward, large builds are slower. Gradle: Kotlin/Groovy scripts, incremental builds and a build cache that are clearly faster on multi-module projects, very flexible. The cost: eve
  • Maven: declarative XML, little magic, every project looks the same, IDE and CI support out of the box. The cost: customising build steps is awkward, large builds are slower.
  • Gradle: Kotlin/Groovy scripts, incremental builds and a build cache that are clearly faster on multi-module projects, very flexible. The cost: every project is different, scripts easily turn into hard-to-read code.
  • Small and medium Spring Boot projects: Maven is the safe choice. Multi-module monorepos, Android, heavily customised builds: Gradle.
Read in post: Maven and the layout of a Spring Boot project
TILJuniorCalling a phase runs every phase before itmvn package runs compile and test too, so a failing test means no jar. mvn install also copies the jar into ~/.m2 so other projects on the machine can use it. In mvn clean package, clean belongs to a separate lifecycle and runs first to delete target/. Skipping tests: -DskipTests still compiles tests but doesn't run th

mvn package runs compile and test too, so a failing test means no jar. mvn install also copies the jar into ~/.m2 so other projects on the machine can use it. In mvn clean package, clean belongs to a separate lifecycle and runs first to delete target/.

Skipping tests: -DskipTests still compiles tests but doesn't run them; -Dmaven.test.skip=true skips compiling them as well. mvn spring-boot:run calls a goal directly and doesn't go through the lifecycle.

Read in post: Maven and the layout of a Spring Boot project
Edge caseJuniormysql-connector-java has new coordinatesThe course material uses mysql:mysql-connector-java:8.0.33. Those coordinates have been relocated to com.mysql:mysql-connector-j. Adding the old ones to the lab, Maven warns: It still works, but you're pinned to 8.0.33. Declaring com.mysql:mysql-connector-j without a version makes Boot 3.5.9 pick 9.5.0, the version tes

The course material uses mysql:mysql-connector-java:8.0.33. Those coordinates have been relocated to com.mysql:mysql-connector-j. Adding the old ones to the lab, Maven warns:

[WARNING] The artifact mysql:mysql-connector-java:jar:8.0.33 has been relocated
          to com.mysql:mysql-connector-j:jar:8.0.33
\- com.mysql:mysql-connector-j:jar:8.0.33:runtime

It still works, but you're pinned to 8.0.33. Declaring com.mysql:mysql-connector-j without a version makes Boot 3.5.9 pick 9.5.0, the version tested with Boot and carrying the security fixes.

Read in post: Maven and the layout of a Spring Boot project
Edge caseMidWriting versions for libraries Spring Boot already managesThe material suggests adding hibernate-validator:8.0.1.Final by hand. No need: spring-boot-starter-validation already brings 8.0.3.Final, the version Boot was tested with. A hand-written version drifts away from Boot's table; on the next Boot upgrade you have to remember every such line, and forgetting one leaves two v

The material suggests adding hibernate-validator:8.0.1.Final by hand. No need: spring-boot-starter-validation already brings 8.0.3.Final, the version Boot was tested with. A hand-written version drifts away from Boot's table; on the next Boot upgrade you have to remember every such line, and forgetting one leaves two versions fighting.

If you must bump a library for a security fix, override Boot's property (<hibernate.version>…</hibernate.version>) instead of writing a version on the dependency. To check whether a library is managed, look it up in the "Dependency Versions" appendix of the Boot docs, or remove <version> and see whether Maven complains.

Read in post: Maven and the layout of a Spring Boot project
Edge caseJuniorWiping the whole .m2 folder on every build errorThe course material says to delete all of .m2 on a cache error. It works, but it re-downloads hundreds of MB for every project on the machine, and if the real cause is a blocked network, the new download fails again. Read the error to see which artifact is broken, delete that artifact's folder, then rerun with -U. An e

The course material says to delete all of .m2 on a cache error. It works, but it re-downloads hundreds of MB for every project on the machine, and if the real cause is a blocked network, the new download fails again. Read the error to see which artifact is broken, delete that artifact's folder, then rerun with -U.

An error caused by a library you installed yourself with mvn install (a stale -SNAPSHOT) also lives in .m2: rebuild that module instead of wiping the cache.

Read in post: Maven and the layout of a Spring Boot project
Edge caseMidA mirror is where you hand over your whole supply chainThe course material offers a third-party public mirror to work around network errors. Every jar you build will then come from that server: if it is tampered with, foreign code runs inside your application. Use only trusted mirrors (your internal repository, official mirrors), always over HTTPS (Maven 3.8.1+ already blo

The course material offers a third-party public mirror to work around network errors. Every jar you build will then come from that server: if it is tampered with, foreign code runs inside your application. Use only trusted mirrors (your internal repository, official mirrors), always over HTTPS (Maven 3.8.1+ already blocks HTTP repositories). In strict environments set <checksumPolicy>fail</checksumPolicy> or verify signatures with a plugin.

Read in post: Maven and the layout of a Spring Boot project
Edge caseMidddl-auto=update in productionThe course sets spring.jpa.hibernate.ddl-auto=update so Hibernate alters tables to match the entities. Handy while learning, dangerous in production: it never drops old columns, can't change column types safely, keeps no history, and two instances starting together may both alter the schema. Production uses versioned m

The course sets spring.jpa.hibernate.ddl-auto=update so Hibernate alters tables to match the entities. Handy while learning, dangerous in production: it never drops old columns, can't change column types safely, keeps no history, and two instances starting together may both alter the schema. Production uses versioned migrations (Flyway, Liquibase) as in the database post, with ddl-auto=validate so Hibernate only checks that entities match the tables.

Read in post: Maven and the layout of a Spring Boot project
TILJuniorDevTools is left out of the fat jar automaticallyDeclare DevTools with <optionaltrue</optional (or runtime scope). By default repackage does not put DevTools into the fat jar, and DevTools switches itself off when the app is started with java -jar. So forgetting to remove it won't make production restart itself. Don't enable spring.devtools.restart.enabled or remote

Declare DevTools with <optional>true</optional> (or runtime scope). By default repackage does not put DevTools into the fat jar, and DevTools switches itself off when the app is started with java -jar. So forgetting to remove it won't make production restart itself. Don't enable spring.devtools.restart.enabled or remote DevTools in a real environment.

Read in post: Maven and the layout of a Spring Boot project
InterviewJuniorWhat are groupId, artifactId and version for?

Together they are the unique coordinates of an artifact in a repository; Maven uses them to find and download the right file.

groupId is the organisation (reversed domain), artifactId the project name, version the release. The coordinates become a path in the repository, e.g. com/mysql/mysql-connector-j/9.5.0/. A -SNAPSHOT suffix means a work-in-progress build whose content may be replaced.

Read in post: Maven and the layout of a Spring Boot project
InterviewJuniorHow do runtime and provided scope differ?

runtime: not needed to compile but present when the app runs. provided: needed to compile but not packaged, because the runtime environment already has it.

A JDBC driver is runtime because your code only uses the JDBC interfaces. The servlet API is provided when you deploy a war to an external Tomcat, which already ships it.

Read in post: Maven and the layout of a Spring Boot project
InterviewJuniorWhat is mvnw and why should you commit it?

The Maven wrapper: a script that downloads and runs the Maven version the project declares, so every machine and CI build with the same Maven without installing it.

Commit mvnw, mvnw.cmd and the .mvn/wrapper/ folder. Upgrading Maven is then a one-line change in maven-wrapper.properties.

Read in post: Maven and the layout of a Spring Boot project
InterviewMidHow does a phase differ from a goal in Maven?

A phase is an ordered step in the lifecycle; a goal is one concrete task of a plugin. A phase does nothing by itself, it runs the goals bound to it.

Calling a phase runs every phase before it: mvn package runs compile, test, then jar:jar and spring-boot:repackage. Calling a goal (mvn spring-boot:run, mvn dependency:tree) runs only that goal.

Read in post: Maven and the layout of a Spring Boot project
InterviewMidWhy do most dependencies in a Spring Boot project have no version?

Because spring-boot-starter-parent inherits the spring-boot-dependencies BOM, whose dependencyManagement pins versions for hundreds of libraries tested together.

dependencyManagement only sets versions, it adds no libraries. A project with another parent imports the BOM with <type>pom</type><scope>import</scope>. To change a version, override a property such as hibernate.version.

Read in post: Maven and the layout of a Spring Boot project
InterviewMidTwo libraries pull in two versions of the same jar. Which one does Maven pick, and how do you handle it?

If the library is in dependencyManagement, the managed version wins; otherwise the version nearest the root wins, and on a tie the one declared first.

Inspect with mvn dependency:tree -Dverbose. Fix it by pinning the version in dependencyManagement, cutting the wrong branch with <exclusions>, and adding the enforcer's dependencyConvergence so the build fails early instead of throwing NoSuchMethodError at runtime.

Read in post: Maven and the layout of a Spring Boot project
InterviewSeniorHow does a Spring Boot fat jar run when Java cannot read nested jars?

The manifest points Main-Class at Boot's JarLauncher; the launcher builds its own class loader over BOOT-INF/classes and the jars in BOOT-INF/lib, then calls main on Start-Class.

The JDK's standard class loader can't read nested jars. layers.idx splits the content into layers so Docker images reuse cache: rarely changing libraries below, frequently changing code on top. For faster startup you can extract the jar (-Djarmode=tools extract) or use CDS/AOT.

Read in post: Maven and the layout of a Spring Boot project
InterviewSeniorHow do you protect the library supply chain of a Maven project?

Download only through a trusted repository (usually an internal proxy), pin versions through a BOM, scan for vulnerabilities automatically in CI, and keep the dependency list small.

  • An internal repository as the * mirror, no direct Internet downloads, HTTPS only, checksum policy fail.
  • Vulnerability scanning (OWASP Dependency-Check, Dependabot, Snyk) and an SBOM (CycloneDX).
  • Enforcer rules: no -SNAPSHOT in releases, banned libraries, converging versions.
  • dependency:analyze to remove declared but unused libraries.
Read in post: Maven and the layout of a Spring Boot project
Edge caseSeniorDecoupling addresses is not decoupling dataProducers and consumers don't call each other, but they still share the message format. Renaming a field or changing amount from an integer to a string breaks every consumer, and you only find out once the message is already in the topic. Treat the message schema as an API: version it, make only compatible changes (add

Producers and consumers don't call each other, but they still share the message format. Renaming a field or changing amount from an integer to a string breaks every consumer, and you only find out once the message is already in the topic.

Treat the message schema as an API: version it, make only compatible changes (add fields with defaults), and use a schema registry (Avro, Protobuf, JSON Schema) to reject breaking changes at the producer.

Read in post: Message brokers
Trade-offMidPub/sub fan-out vs calling each service directlyDirect calls (HTTP/gRPC): easy to understand and debug, results come back immediately, errors go back to the caller. But the caller must know every recipient, latencies add up, and each new recipient is a code change in the caller. Pub/sub: adding a consumer needs no change to the producer, and a slow or dead consumer
  • Direct calls (HTTP/gRPC): easy to understand and debug, results come back immediately, errors go back to the caller. But the caller must know every recipient, latencies add up, and each new recipient is a code change in the caller.
  • Pub/sub: adding a consumer needs no change to the producer, and a slow or dead consumer doesn't drag the producer down. But nobody "answers", a business flow is harder to trace, and data across services is only eventually consistent (it matches after a delay).
  • Call directly when the caller needs the result to continue (check stock before accepting an order). Use pub/sub when the caller is only announcing something that happened.
Read in post: Message brokers
Trade-offMidRate limiting vs a queue as a buffer when traffic exceeds capacityRate limiting fits when the excess can be dropped (reads, abused public APIs) or when the client needs to know immediately that it was refused (HTTP 429). Simple, no new infrastructure, but requests are lost or delayed. A queue fits when the data must be kept and late processing is acceptable (event tracking, IoT, logs
  • Rate limiting fits when the excess can be dropped (reads, abused public APIs) or when the client needs to know immediately that it was refused (HTTP 429). Simple, no new infrastructure, but requests are lost or delayed.
  • A queue fits when the data must be kept and late processing is acceptable (event tracking, IoT, logs, email). No data loss, but you run a broker, results arrive later, and the queue must hold the whole peak.
  • Usually you combine both. Size it: a 30,000/s peak lasting 10 minutes drained at 8,000/s needs room for about (30,000 − 8,000) × 600 ≈ 13 million messages, and roughly another 27 minutes to drain.
Read in post: Message brokers
Edge caseSeniorWriting to the database and then publishing is a dual write that can divergeorderRepository.save(order); kafkaTemplate.send("orders", event); has two failure modes, because there's no shared transaction between the database and the broker: The DB commit succeeds but the publish fails: other services never learn the order exists. You publish first and the DB transaction rolls back: other servic

orderRepository.save(order); kafkaTemplate.send("orders", event); has two failure modes, because there's no shared transaction between the database and the broker:

  • The DB commit succeeds but the publish fails: other services never learn the order exists.
  • You publish first and the DB transaction rolls back: other services learn about an order that doesn't exist.

The standard fix is the transactional outbox: write the event into an outbox table in the same transaction as the business data. A relay (a poller, or CDC such as Debezium reading the binlog/WAL) pushes it to the broker. Consumers still need to be idempotent because the relay is at-least-once. Why emitting first or wrapping both in a transaction still breaks, and outbox with Debezium: dual write, exactly-once and ordering. The outbox only fixes the dual write inside one service; a transaction across services needs a saga (distributed transactions).

Read in post: Message brokers
Edge caseSeniorA distributed monolith over a message busA system where service A publishes a command and then waits for service B's reply on another topic, while B waits on C, is just as coupled as HTTP — only slower and harder to debug. The signs: deploying one service means deploying another with it, one topic going down stops everything, and messages are full of fields o

A system where service A publishes a command and then waits for service B's reply on another topic, while B waits on C, is just as coupled as HTTP — only slower and harder to debug.

The signs: deploying one service means deploying another with it, one topic going down stops everything, and messages are full of fields only one consumer understands.

A broker doesn't create decoupling by itself; sound service boundaries and messages that describe business facts do. Post 4 of this series dissects exactly such a request-reply-over-Kafka design.

Read in post: Message brokers
TILSeniorKafka 4.x adds "share groups": queue-style consumption on Kafka topicsA classic consumer group assigns each partition to exactly one consumer, so parallelism is capped by the partition count and there's no per-message ack. KIP-932, "Queues for Kafka", adds share groups: many consumers can read the same partition, and each record is individually acknowledged, released or rejected, with a

A classic consumer group assigns each partition to exactly one consumer, so parallelism is capped by the partition count and there's no per-message ack.

KIP-932, "Queues for Kafka", adds share groups: many consumers can read the same partition, and each record is individually acknowledged, released or rejected, with a delivery count. It was early access in Kafka 4.0 and preview in 4.1; check its status in the version you run before using it in production.

Read in post: Message brokers
Trade-offMidWhy delivery guarantees and features come before performancePerformance is usually something you can buy more of: more nodes, more partitions, tuning. Delivery guarantees and features are architectural properties you can't buy later. Redis Pub/Sub is extremely fast, but an offline consumer loses messages, so it's unusable for payment events. Conversely, a logging pipeline at a

Performance is usually something you can buy more of: more nodes, more partitions, tuning. Delivery guarantees and features are architectural properties you can't buy later.

  • Redis Pub/Sub is extremely fast, but an offline consumer loses messages, so it's unusable for payment events.
  • Conversely, a logging pipeline at a million events per second can tolerate losing a few events but not a broker that tops out at 20,000/s.

So filter by guarantees and features first, then benchmark the survivors on your real workload.

Read in post: Message brokers
Edge caseSeniorHolding the transaction open while processing a job breaks a table-based queueIf a worker runs SELECT ... FOR UPDATE SKIP LOCKED, spends 30 seconds calling an external API, and only then runs UPDATE ... 'DONE' and commits, every worker holds a transaction and a connection the whole time. The pool runs dry quickly. In PostgreSQL, long transactions also stop VACUUM from cleaning dead tuples, so th

If a worker runs SELECT ... FOR UPDATE SKIP LOCKED, spends 30 seconds calling an external API, and only then runs UPDATE ... 'DONE' and commits, every worker holds a transaction and a connection the whole time. The pool runs dry quickly. In PostgreSQL, long transactions also stop VACUUM from cleaning dead tuples, so the queue table (updated constantly) bloats and slows down.

Do it in steps: transaction 1 marks the job IN_PROCESSING with locked_until and commits; process outside any transaction; transaction 2 marks it DONE. If the worker dies in between, the lease expires and the job is handed out again.

Read in post: Message brokers
Edge caseMidRedis Pub/Sub is not a message queueRedis Pub/Sub only delivers to subscribers that are connected at the moment of publishing. A restart, a deploy or a few seconds of network trouble and the messages from that window are gone for good — no log, no retry. It's fine for notifications you can afford to lose (local cache invalidation, live UI updates). If yo

Redis Pub/Sub only delivers to subscribers that are connected at the moment of publishing. A restart, a deploy or a few seconds of network trouble and the messages from that window are gone for good — no log, no retry.

It's fine for notifications you can afford to lose (local cache invalidation, live UI updates). If you need at-least-once in Redis, use Streams with consumer groups and XACK, and still enable AOF if you can't afford to lose data on a Redis restart.

Read in post: Message brokers
Edge caseMidSomeone else's benchmark doesn't answer your questionVendor benchmarks pick message sizes, partition counts, acks levels, fsync settings and hardware that flatter their product. "NATS is faster than Kafka" or "Pulsar is slower than Kafka" can each be true or false depending on how you measure. Write your own benchmark: your real message sizes, the guarantee you actually

Vendor benchmarks pick message sizes, partition counts, acks levels, fsync settings and hardware that flatter their product. "NATS is faster than Kafka" or "Pulsar is slower than Kafka" can each be true or false depending on how you measure.

Write your own benchmark: your real message sizes, the guarantee you actually need (e.g. acks=all, replication factor 3), p99 latency rather than just average throughput, long enough runs to get past the page cache, and include a node failure.

Read in post: Message brokers
InterviewJuniorWhat is a message broker and what problems does it solve?

An intermediary that accepts messages from producers and delivers them to consumers, so services don't call each other directly.

It solves four problems of request-response: waiting (async), knowing each other and failing together (decoupling), changing the sender for each new receiver (fan-out), and traffic spikes (load levelling).

Read in post: Message brokers
InterviewJuniorHow does a queue (point-to-point) differ from pub/sub?

Queue: each message is processed by only one consumer. Pub/sub: every subscriber group gets every message.

In a queue, consumers share the work. Kafka combines both: different consumer groups are pub/sub, consumers within one group are a queue.

Read in post: Message brokers
InterviewJuniorWhat's the difference between push and pull?

Push: the broker actively sends messages to consumers. Pull: consumers ask the broker for messages.

RabbitMQ pushes, with prefetch to cap unacked messages. Kafka pulls (poll). Pull lets consumers control their own pace and batch naturally without being overwhelmed when slow. Push gives lower latency under light load but needs a backpressure mechanism (telling the sender to slow down).

Read in post: Message brokers
InterviewJuniorWhat do at-most-once, at-least-once and exactly-once mean?

At-most-once: may be lost, never duplicated. At-least-once: never lost, may be duplicated. Exactly-once: each message takes effect exactly once.

  • At-most-once: ack first, then process.
  • At-least-once: process, then ack; a crash in between means redelivery.
  • Exactly-once: in practice you only get it within a narrow scope (such as Kafka's read-process-write transactions) or by combining at-least-once with an idempotent consumer.
Read in post: Message brokers
InterviewMidHow does an event differ from a command and a response?

An event is something that happened, immutable, for whoever is interested. A command is an instruction to a specific party. A response is the answer for exactly the party that asked.

A response is synchronous and its value can change over time. An event is named in the past tense (OrderPlaced), valuable to several services, and the publisher doesn't care who handles it. A command (ReserveStock) usually expects an outcome.

Keeping them apart shapes topic design: events can fan out freely, while a command usually goes one way to the single service that owns it.

Read in post: Message brokers
InterviewMidWhat criteria do you use to choose a message broker, and in what order?

Delivery guarantee → functionality → performance → scalability → ecosystem. Performance can be bought; guarantees and features can't.

  • Delivery guarantee: can the business tolerate loss, or duplicates.
  • Functionality: routing, delays, priority, replay, ordering, retention.
  • Performance: measured on my own workload — a vendor's benchmark is no substitute.
  • Finally scalability, the ecosystem and my team's ability to operate it.
Read in post: Message brokers
InterviewMidWhen would you use a database as a queue instead of a broker?

With moderate load, one worker pool, and a need for consistency with business data.

Moderate load means hundreds to a few thousand jobs/s. Writing the order and the job in one transaction removes the dual write. Use FOR UPDATE SKIP LOCKED, a locked_until lease to recover jobs from dead workers, and a partial index on waiting rows. Move to a broker when you need fan-out, replay, or the load strains the database.

Read in post: Message brokers
InterviewSeniorHow do you publish an event after a database write without them diverging?

Use a transactional outbox: write the event into an outbox table in the same transaction as the business data, and have a relay push it to the broker.

There's no shared transaction between the DB and the broker, so save() followed by send() is a dual write where one side can succeed and the other fail. The relay is a poller using SKIP LOCKED, or CDC such as Debezium reading the WAL/binlog; it pushes to the broker and marks the event sent.

The relay is at-least-once, so consumers must be idempotent (a processed-message table keyed by event id, or upserts on a business key). Ordering holds if the relay publishes in order and keys messages by aggregate.

Read in post: Message brokers
InterviewSeniorWhat do you pay for adding a message broker to a system?

You pay with eventual consistency, duplicates, limited ordering and operational complexity.

  • Eventual consistency the business must accept.
  • Duplicates, so consumers must be idempotent.
  • Ordering only within a partition.
  • Poison messages that need a DLQ.
  • Message schemas that become versioned APIs.
  • Debugging that needs tracing, and consumer lag to monitor.

Get the design wrong and you have a distributed monolith over a message bus.

Read in post: Message brokers
InterviewSeniorHow do RabbitMQ and Kafka differ at their core?

RabbitMQ is a smart broker with simple consumers; Kafka is a distributed log with a simple broker and smart clients.

  • RabbitMQ (classic and quorum queues): routes through exchanges, pushes messages, deletes them on ack and tracks per-message state. It shines at routing, priority, delays and task queues.
  • Kafka: messages are appended and kept per retention; consumers own their offsets and pull. It shines at throughput, replay and many independent consumer groups.

RabbitMQ Streams and Kafka share groups are bringing them closer, but their default models are still different.

Read in post: Message brokers
Trade-offSeniorModular monolith or microservicesModular monolith: one deploy, modules with clear boundaries (separate packages, calls only through interfaces, enforced with ArchUnit). Transactions, joins and refactoring all stay easy. Microservices: worth it when ≥ 3–4 teams keep stepping on each other, when one part needs a very different scaling or release rhythm,
  • Modular monolith: one deploy, modules with clear boundaries (separate packages, calls only through interfaces, enforced with ArchUnit). Transactions, joins and refactoring all stay easy.
  • Microservices: worth it when ≥ 3–4 teams keep stepping on each other, when one part needs a very different scaling or release rhythm, or when you need fault or security isolation.
  • The safe path: modular monolith first. If the module boundaries are right, turning a module into a service is just moving where it runs.
Read in post: Microservices
Edge caseMidChained synchronous calls can bring down the whole systemGateway → A → B → C. If each service has 99.9% uptime, the chain drops to ~99.7%, and latency adds up. One slow service holds threads in every service upstream. Put a timeout, circuit breaker and bulkhead on every call (see timeouts, retries and circuit breakers), and move steps that don't need an immediate answer to e

Gateway → A → B → C. If each service has 99.9% uptime, the chain drops to ~99.7%, and latency adds up. One slow service holds threads in every service upstream. Put a timeout, circuit breaker and bulkhead on every call (see timeouts, retries and circuit breakers), and move steps that don't need an immediate answer to events.

Read in post: Microservices
Trade-offSeniorPeripheral first or core firstPeripheral first (Mail, Notification, Report): low risk and quick wins, good when the team isn't used to running microservices yet. But it doesn't fix the core that's actually the bottleneck. Core first (User, Catalog): paves the way for every later split and cuts coupling early. But the risk is high because everything
  • Peripheral first (Mail, Notification, Report): low risk and quick wins, good when the team isn't used to running microservices yet. But it doesn't fix the core that's actually the bottleneck.
  • Core first (User, Catalog): paves the way for every later split and cuts coupling early. But the risk is high because everything depends on it, so you need side-by-side running and a way back.
  • Teams often do both: one peripheral service to practice the process, then the core.
Read in post: Microservices
Edge caseSeniorThe distributed monolithSigns: one feature needs four services deployed together in a specific order; services read each other's tables; a single request makes six synchronous hops; a "common" library holds shared entities. You pay every cost of microservices and get none of the benefits. The fix: merge services that always change together, a

Signs: one feature needs four services deployed together in a specific order; services read each other's tables; a single request makes six synchronous hops; a "common" library holds shared entities. You pay every cost of microservices and get none of the benefits. The fix: merge services that always change together, and move communication to events.

Read in post: Microservices
InterviewMidWhat is service discovery, and how do client-side and server-side differ?

Service discovery is how a service finds the addresses of another service's live instances, because IPs change all the time as things scale and restart.

Client-side: the client asks a registry (Eureka, Consul), then picks an instance and balances the load itself. Server-side: the client calls a fixed address (Kubernetes Service DNS, a load balancer) and the infrastructure picks the instance. On Kubernetes you usually go server-side.

Read in post: Microservices
InterviewMidWhat does an API gateway do?

It's the single entry point for clients: routing to services, authentication, rate limiting, API version switching, and sometimes aggregating several responses.

Don't put business logic in the gateway. It turns into a new monolith that every team has to edit.

Read in post: Microservices
InterviewMidWhy shouldn't several services share one database?

Because the schema becomes a hidden contract between services: changing a table needs everyone to coordinate, independent deploys are lost, and one heavy query from one service slows everyone down.

Each service owns its data; others read it through an API or through a copy built from events.

Read in post: Microservices
InterviewSeniorHow do you decide on microservice boundaries?

From the business: event storming to find subdomains, define bounded contexts, draw a context map, then start with one context per service.

To check a boundary: a business change usually touches only one service, cross-service transactions are rare, and one team owns it end to end. If a context is big, split it further by load or by team. Avoid splitting by table or by layer.

Read in post: Microservices
InterviewSeniorHow would you break up a monolith that's running in production, step by step?

Modular monolith first, then strangler fig: carve out one part at a time behind the gateway, run old and new side by side, shift traffic gradually, and always keep a way back.

Order: one peripheral service to practice the process, then a core service that many modules depend on. Data: sync with CDC at first, use shadow reads to compare results, shift reads first and writes after.

Read in post: Microservices
InterviewSeniorWhat signs tell you that you have a distributed monolith?

One feature needs several services deployed together in order, services read each other's tables, synchronous call chains are long, and a shared library holds entities.

The fix: merge services that always change together, move communication to events, give each service ownership of its data, and add contract tests so APIs can change without lockstep deploys.

Read in post: Microservices
InterviewSeniorA screen needs data from 4 services. How do you avoid 4 synchronous calls per request?

Build a read model (CQRS): one service listens to the events of all 4, stores a pre-joined table for that screen, and answers in one query.

The price is a few seconds of lag, plus handling duplicate and out-of-order events (versions, idempotency). If one part truly needs fresh data, make a separate sync call just for that part, with a timeout and a fallback value.

Read in post: Microservices
Edge caseMidThere is no "CA" distributed systemA database on one machine has no partitions between nodes, so "CA" only describes non-distributed systems. As soon as you have two or more nodes, the network between them will fail at some point and you must pick C or A for that moment. Saying "my system is CA" in an interview usually gets challenged right away.

A database on one machine has no partitions between nodes, so "CA" only describes non-distributed systems. As soon as you have two or more nodes, the network between them will fail at some point and you must pick C or A for that moment. Saying "my system is CA" in an interview usually gets challenged right away.

Read in post: Design principles
TILMidThe C in CAP is not the C in ACIDACID's C: a transaction moves the database from one valid state to another without breaking constraints (foreign keys, CHECK, non-negative balance). It's about one database and mostly defined by the application. CAP's C: every replica returns the same latest value. It's about many copies of the data. A system can satis
  • ACID's C: a transaction moves the database from one valid state to another without breaking constraints (foreign keys, CHECK, non-negative balance). It's about one database and mostly defined by the application.
  • CAP's C: every replica returns the same latest value. It's about many copies of the data.

A system can satisfy ACID's C on the primary and still violate CAP's C when reading from a lagging replica.

Read in post: Design principles
Trade-offMidScale up or scale outScale up (vertical): buy a bigger machine. No code changes, no distributed problems. But there's a hardware ceiling, price grows faster than linearly, and it's still a single point of failure. Scale out (horizontal): add machines. Practically no ceiling and better fault tolerance, but it needs statelessness, load balan
  • Scale up (vertical): buy a bigger machine. No code changes, no distributed problems. But there's a hardware ceiling, price grows faster than linearly, and it's still a single point of failure.
  • Scale out (horizontal): add machines. Practically no ceiling and better fault tolerance, but it needs statelessness, load balancing, and for data, sharding and distributed transactions.

A sensible order: scale out the stateless application tier first (cheap), scale up the database to a reasonable size, add replicas and caching, and only then shard.

Read in post: Design principles
Edge caseMid"Sequential is always faster than concurrent" only holds for pure CPU workThe slide says: on one core, running A then B is always faster than interleaving them, because interleaving costs context switches. True when A and B only use CPU. If A waits 45 ms on the database out of every 50 ms, running sequentially leaves the CPU idle 90% of the time; interleaving lets B use the CPU while A waits

The slide says: on one core, running A then B is always faster than interleaving them, because interleaving costs context switches. True when A and B only use CPU. If A waits 45 ms on the database out of every 50 ms, running sequentially leaves the CPU idle 90% of the time; interleaving lets B use the CPU while A waits, and the total time is much shorter. The right lesson: threads for CPU-bound work shouldn't exceed the core count, while I/O-bound work needs concurrency.

Read in post: Design principles
Trade-offSeniorRedundancy costs money, and "sacrifice a pawn to save the rook"Redundancy means paying for machines that wait: two availability zones nearly double the cost, and multiple regions add consistency problems on top. The course sums up the rest with a chess saying: sacrifice a pawn to save the rook. Under overload, switch off recommendations, reviews and viewing history to keep orderin

Redundancy means paying for machines that wait: two availability zones nearly double the cost, and multiple regions add consistency problems on top. The course sums up the rest with a chess saying: sacrifice a pawn to save the rook. Under overload, switch off recommendations, reviews and viewing history to keep ordering and payment alive. Decide in advance which features are the "pawns" and give them a switch (feature flag), instead of debating it mid-incident.

Read in post: Design principles
InterviewJuniorWhat's the difference between scaling up and scaling out?

Scaling up replaces the machine with a bigger one; scaling out adds more machines. Scaling out needs stateless services and a load balancer.

Scaling up is simple but has a ceiling and is still a single point of failure. Scaling out has practically no ceiling and tolerates failures better, but it's more complex for data.

Read in post: Design principles
InterviewJuniorWhy use p99 instead of average latency?

Because the average hides the slow requests, and those are exactly the ones users remember.

p99 = 300 ms means 1% of requests take longer than 300 ms. With millions of requests a day, 1% is tens of thousands of users.

Read in post: Design principles
InterviewMidState the CAP theorem. Can you choose CA?

When the network between nodes partitions, a distributed system must choose between consistent answers (C) and always answering (A). CA only exists on a single node, not in a distributed system.

PACELC adds that without a partition you still choose between low latency and consistency, for example synchronous or asynchronous replication.

Read in post: Design principles
InterviewMidHow does the C in CAP differ from the C in ACID?

ACID's C means not breaking data constraints within one database; CAP's C means every replica returns the same latest value.

You can satisfy ACID's C on the primary and still read stale data from an asynchronous replica.

Read in post: Design principles
InterviewMidA service is slow. In what order do you optimize?

Set a numeric goal (p99, QPS), measure to find the bottleneck, decide whether it's CPU or I/O, fix that spot, then measure again.

Most often it's I/O: N+1 queries, missing indexes, calling APIs sequentially instead of in parallel. Don't guess, and don't optimize what you haven't measured.

Read in post: Design principles
InterviewSeniorHow do you take a system from 99.5% to 99.95% availability?

Cut MTTR (automatic detection and failover), remove synchronous dependencies from the main path, add redundancy at single points of failure, and release safely (canary, fast rollback).

Compute the chain's availability first to find the weakest link. Add SLOs and an error budget to track progress, and chaos tests to prove failover really works.

Read in post: Design principles
InterviewSeniorWhen the system is overloaded, what keeps it from going down entirely?

Rate limiting at the entrance, degrading non-core features (sacrifice the pawn), timeouts and circuit breakers on every outbound call, and queues to absorb writes that can wait.

The list of features to switch off, and the switches themselves, must be prepared in advance and exercised in chaos tests, not decided while things are on fire.

Read in post: Design principles
InterviewSeniorWhat does R + W > N mean in a quorum?

With N replicas, writes waiting for W acknowledgements and reads asking R replicas, R + W > N guarantees the read set overlaps the write set, so a read can see the latest version.

N = 3, W = 2, R = 2 is a common setup. Lowering W or R is faster and more available but may read stale data; there are still edge cases with concurrent writes and clock skew, so a quorum is not linearizability.

Read in post: Design principles
Edge caseMidA listener unsubscribing during notification makes ArrayList skip the next listener or throw CMEThe publisher iterates an ArrayList with for-each and a listener calls unsubscribe. With two listeners: removing element 0 makes the size 1, the iterator is already at position 1, so hasNext() returns false and the loop ends silently. With three or more: next() detects the modification and throws ConcurrentModification

The publisher iterates an ArrayList with for-each and a listener calls unsubscribe. With two listeners: removing element 0 makes the size 1, the iterator is already at position 1, so hasNext() returns false and the loop ends silently. With three or more: next() detects the modification and throws ConcurrentModificationException.

The silent case is the dangerous one. Fix: iterate over a snapshot (a copy); the neatest way is CopyOnWriteArrayList: cheap for many reads and few writes, which is exactly what a listener list is.

Read in post: Observer
Edge caseMidLapsed listener: forgetting to unsubscribe is a memory leakA long-lived publisher (a singleton, a bean) holds strong references to every listener. Each listener (a lambda, an inner class) holds its enclosing object: a screen, a request, a whole object graph. If nobody unsubscribes, the GC can't collect any of it, and every notification still calls into "dead" objects. Fix: sub

A long-lived publisher (a singleton, a bean) holds strong references to every listener. Each listener (a lambda, an inner class) holds its enclosing object: a screen, a request, a whole object graph. If nobody unsubscribes, the GC can't collect any of it, and every notification still calls into "dead" objects.

Fix: subscribe returns an AutoCloseable handle, closed as part of a lifecycle (try-with-resources, @PreDestroy, onDestroy). A WeakReference is only a safety net: a lambda nobody else holds gets collected immediately, which easily becomes the opposite bug.

Read in post: Observer
TILMidJDK 21 warns about constructors that leak thisSince JDK 21, javac -Xlint:this-escape warns when the constructor of a public, extensible class may hand this to outside code before initialisation finishes, which is exactly subscribe(this). I tried it with a class that registers itself before assigning a field: javac reports [this-escape] possible 'this' escape befor

Since JDK 21, javac -Xlint:this-escape warns when the constructor of a public, extensible class may hand this to outside code before initialisation finishes, which is exactly subscribe(this). I tried it with a class that registers itself before assigning a field: javac reports [this-escape] possible 'this' escape before subclass is fully initialized. Fix: register from outside after construction (a create() factory method or the wiring code), or use @PostConstruct in Spring.

Read in post: Observer
Trade-offSeniorA listener inside the transaction or after the commit@EventListener (inside the transaction): sees uncommitted data and joins the transaction, so it fits work that must succeed with the business change (an audit row, a summary table in the same database). The price: a slow listener holds locks longer, a failing one rolls back the whole booking. @TransactionalEventListene
  • @EventListener (inside the transaction): sees uncommitted data and joins the transaction, so it fits work that must succeed with the business change (an audit row, a summary table in the same database). The price: a slow listener holds locks longer, a failing one rolls back the whole booking.
  • @TransactionalEventListener(AFTER_COMMIT): runs only once the data definitely exists, and listener failures don't affect the booking. The price: not durable (a crash at that moment loses the work), and writing to the database needs a new transaction.

Rule of thumb: work tied to data correctness goes inside the transaction; "telling the outside world" (email, cache, Kafka) goes after the commit, and through an outbox if it can't be lost.

Read in post: Observer
Edge caseSeniorAn AFTER_COMMIT listener isn't durable: a crash after commit loses its workAn AFTERCOMMIT listener runs in memory after the database has committed. If the process dies, gets replaced by a deploy, or the listener throws at that moment, its job (send an email, push to Kafka) is lost with no trace to retry from. The original transaction is also over, so writing to the database needs a new one (@

An AFTER_COMMIT listener runs in memory after the database has committed. If the process dies, gets replaced by a deploy, or the listener throws at that moment, its job (send an email, push to Kafka) is lost with no trace to retry from.

The original transaction is also over, so writing to the database needs a new one (@Transactional(propagation = REQUIRES_NEW); since Spring 6.1 a plain @Transactional on such a listener is rejected at startup). Use AFTER_COMMIT for work you can afford to lose; use an outbox for work you can't.

Read in post: Observer
Trade-offSeniorHand-written Observer, Spring events, or a message brokerHand-written Observer: a small object graph (UI, an SDK, a library), no framework needed; you own thread safety, errors and lifecycles. Spring ApplicationEvent: decoupling modules inside one service (booking doesn't need to know about the email module). Synchronous by default and can be tied to the transaction, but liv
  • Hand-written Observer: a small object graph (UI, an SDK, a library), no framework needed; you own thread safety, errors and lifecycles.
  • Spring ApplicationEvent: decoupling modules inside one service (booking doesn't need to know about the email module). Synchronous by default and can be tied to the transaction, but lives in one JVM, isn't durable and doesn't retry.
  • A message broker (Kafka, RabbitMQ) + outbox: subscribers in other services, or you need durability, retries, several independent consumers, or load buffering. The cost: infrastructure, latency, at-least-once delivery (duplicates possible) so consumers must be idempotent, harder debugging.

Rule of thumb: in-process events to decouple code, a broker to decouple systems. Don't use Kafka to let two classes in the same service talk to each other.

Read in post: Observer
InterviewJuniorWhat problem does the Observer pattern solve?

It lets one object tell several others when its state changes, without depending on each of them.

The publisher keeps a list of subscribers behind an interface and calls each one; whoever cares subscribes. Adding a subscriber doesn't touch the publisher.

Read in post: Observer
InterviewMidWhen writing an Observer publisher, what do you watch out for?

Snapshot iteration, per-listener error isolation, unsubscribing tied to a lifecycle, and never registering this in a constructor.

  • Iterate over a snapshot (CopyOnWriteArrayList) so self-unsubscribing listeners don't break anything.
  • Catch exceptions per listener so one bad listener doesn't block the rest.
  • Return an unsubscribe handle and tie it to a lifecycle to avoid leaks.
  • Notify only on change; don't rely on order; consider async delivery if listeners can be slow.
Read in post: Observer
InterviewMidHow do @EventListener and @TransactionalEventListener differ?

@EventListener runs at publish time, on the same thread and in the same transaction; @TransactionalEventListener defers to a transaction phase, AFTER_COMMIT by default.

An @EventListener exception fails the publishing method. @TransactionalEventListener only runs if the commit succeeds; good for emails and cache eviction. It isn't durable: a crash after the commit loses the listener's work.

Read in post: Observer
InterviewMidWhy shouldn't you call subscribe(this) inside a constructor?

Because the object isn't fully built yet (a this-escape): the listener may run on an object whose fields are still null.

If the publisher notifies immediately, or another thread does, a subclass (if any) hasn't run its constructor yet. Since JDK 21, javac -Xlint:this-escape warns about it. Register from outside once construction is done: a create() factory method, the wiring code, or @PostConstruct.

Read in post: Observer
InterviewSeniorFor "after a booking succeeds, do X", when do you use a Spring event and when Kafka?

A Spring event when X lives in the same service and can be lost or redone; Kafka through an outbox when X is in another service or must be durable.

Spring events fit cache eviction and metrics, where the goal is decoupling modules. Kafka fits when you need durability, retries, several independent consumers or load buffering. Never publish to Kafka directly inside the database transaction: the dual write either emits events for rolled-back bookings or loses events on a crash after commit.

Read in post: Observer
InterviewSeniorAn Observer in your app is leaking memory. How do you investigate and fix it?

Take a heap dump, follow the paths from GC roots to objects that should be dead (typically a singleton's listener list), then tie unsubscribing to the lifecycle.

  • Heap dump with jcmd <pid> GC.heap_dump, open it in Eclipse MAT, look at the dominator tree.
  • Fix: subscribe returns an unsubscribe handle, closed with the lifecycle; add a listener-count metric to catch it early.
  • WeakReference is only a safety net because lambda listeners can get collected too soon.
Read in post: Observer
InterviewSeniorA slow listener blocks the publisher. How do you notify asynchronously without losing order?

Deliver events through a single-thread executor (a FIFO queue); the publisher just enqueues and returns.

  • A multi-threaded pool is faster but reorders events.
  • Bound the queue, or coalesce undelivered changes when only the latest value matters.
  • Catch listener exceptions inside the task; on shutdown, shutdown then awaitTermination so queued events are delivered.
  • If you need ordering per key rather than globally, use one queue per key (like Kafka partitions).
Read in post: Observer
Edge caseMidMemorising dumps teaches you wrong and outdated answers tooThe course slides suggest "do the dumps first". I don't: using leaked exam questions breaks Confluent's candidate agreement and can cost you the certificate. The practical reason is just as strong: the question banks in circulation were mostly written in the ZooKeeper era, and some answers are simply wrong. Examples fr

The course slides suggest "do the dumps first". I don't: using leaked exam questions breaks Confluent's candidate agreement and can cost you the certificate.

The practical reason is just as strong: the question banks in circulation were mostly written in the ZooKeeper era, and some answers are simply wrong. Examples from the bank handed out in the course:

  • "At-most-once consumer" picks "commit offsets after processing"; it must be before.
  • "When is log compaction evaluated" also picks "whenever a partition is created".
  • "Who rejects an incompatible schema" includes the broker, which never looks at payloads.

Learn from the official docs, then verify with a lab.

Read in post: CCDAK review
TILMidKafka 4.0 has no ZooKeeper at all, not even for migrationFrom Kafka 4.0 brokers run only in KRaft mode. A ZooKeeper-based cluster must be migrated to KRaft on a 3.x release (3.9 is the last bridge release) before upgrading to 4.x. Metadata (topics, partitions, ACLs, dynamic configs, quotas) lives in the internal clustermetadata topic, written by the controller quorum via Raf

From Kafka 4.0 brokers run only in KRaft mode. A ZooKeeper-based cluster must be migrated to KRaft on a 3.x release (3.9 is the last bridge release) before upgrading to 4.x.

Metadata (topics, partitions, ACLs, dynamic configs, quotas) lives in the internal __cluster_metadata topic, written by the controller quorum via Raft. kafka-metadata-quorum describe --status shows the LeaderId, CurrentVoters and follower lag.

Read in post: CCDAK review
InterviewMid1. Where are Kafka ACLs stored?

KRaft: as metadata records in the __cluster_metadata log. ZooKeeper era: under the /kafka-acl znode.

In KRaft the records are replicated by the controller quorum and enforced by StandardAuthorizer. In neither case do they live in the broker's data directory or in a user-readable topic.

Read in post: CCDAK review
InterviewMid2. Where does a topic's dynamic config (e.g. retention.ms changed with kafka-configs) live?

In __cluster_metadata (KRaft) or the /config/topics/<topic> znode (ZooKeeper), not in server.properties.

server.properties is the broker's static config. Inspect dynamic config with kafka-configs --bootstrap-server ... --entity-type topics --entity-name <topic> --describe.

Read in post: CCDAK review
InterviewMid3. What does the controller do, and how is it chosen?

The controller manages cluster metadata; in KRaft it's the leader of the Raft quorum, elected by a majority of voters.

  • Its job: elect partition leaders when a broker dies, track brokers joining and leaving, record topic changes.
  • It does not coordinate consumer group rebalances; that's the group coordinator on the brokers.
  • ZooKeeper era: whichever broker created the /controller znode first.
  • Only one controller is active at a time, regardless of how many producers or consumers there are.
Read in post: CCDAK review
InterviewJunior4. How many nodes can a 5-node quorum lose?

Two, because a majority (3/5) must stay alive.

This holds for both a ZooKeeper ensemble and a KRaft controller quorum. That's why node counts should be odd: 4 nodes tolerate only one failure, the same as 3. In the ZooKeeper era nodes talked over 2181 (clients), 2888 (followers to leader) and 3888 (leader election); KRaft uses the CONTROLLER listener.

Read in post: CCDAK review
InterviewJunior5. With a replication factor of 3, where does each partition's data live?

On 3 different brokers, one replica each: one leader, two followers.

You can't set an RF larger than the number of brokers; creating an RF=3 topic on a 2-broker cluster is rejected. With broker.rack, Kafka also spreads replicas across racks/AZs.

Read in post: CCDAK review
InterviewSenior6. A broker's disk is wiped and the broker restarts — what happens?

It rejoins as an empty follower, re-fetches from the leaders and joins the ISR only once it has caught up; no data is lost.

  • With unclean election disabled, it can't become leader before catching up.
  • In KRaft the log directory must contain meta.properties (cluster id, node id), so you run kafka-storage format first (the Confluent image does it automatically when CLUSTER_ID is set).
  • If that node is also a controller voter, be more careful: since 3.9 (KIP-853) there is a proper procedure for replacing voters.
Read in post: CCDAK review
InterviewMid7. A client gets NOT_LEADER_OR_FOLLOWER on a fetch — what does it do?

It sends a metadata request to any broker, learns the new leader and retries against it.

Every broker can answer metadata requests; clients never ask ZooKeeper or the controller directly. The error used to be called NOT_LEADER_FOR_PARTITION. Producers handle leader changes the same way, so with RF ≥ 2 losing a leader doesn't stop a producer.

Read in post: CCDAK review
InterviewJunior8. What are the three mandatory producer settings, even without keys?

bootstrap.servers, key.serializer, value.serializer.

You still need a key serializer when you never send keys. Since Kafka 3.0 the defaults are acks=all and enable.idempotence=true, but set them explicitly anyway.

Read in post: CCDAK review
InterviewJunior9. What does producer.send() return in Java?

A Future<RecordMetadata> (topic, partition, offset, timestamp).

There's an overload taking a Callback that runs when the broker responds or the send fails. Calling .get() on every record makes the producer synchronous and kills throughput.

Read in post: CCDAK review
InterviewMid10. What's the risk of max.in.flight.requests.per.connection > 1 combined with retries?

Reordering: batch 1 fails and is resent after batch 2 succeeded, so batch 2 ends up first in the partition.

With enable.idempotence=true the broker uses the producer id and sequence numbers to keep order and drop duplicates, allowing up to 5 in-flight requests. If you disable idempotence and need ordering, set it to 1.

Read in post: CCDAK review
InterviewJunior11. What do you set to get acknowledgement from the leader only?

acks=1.

acks=0 waits for nothing, acks=all (or -1) waits for every replica in the ISR. With acks=1, if the leader dies before followers copy the record, an acknowledged record can be lost.

Read in post: CCDAK review
InterviewMid12. Which three settings give the strongest durability while still surviving one broker failure?

acks=all, replication factor 3, min.insync.replicas=2.

Every write sits on at least 2 brokers before it's acknowledged, and losing one broker still allows writes. RF=3 with min ISR 1 may let acks=all write a single copy; RF=2 with min ISR 2 stops writes when one broker dies.

Read in post: CCDAK review
InterviewMid13. Whose settings are acks and min.insync.replicas, and when does min ISR matter?

acks belongs to the producer, min.insync.replicas to the topic; min ISR only matters when the producer uses acks=all.

Min ISR defaults to the broker's value. If the ISR is smaller than this value, the broker rejects the write with NotEnoughReplicasException. With acks=0 or 1 it's ignored.

Read in post: CCDAK review
InterviewMid14. RF=3, min.insync.replicas=1, acks=all: how many brokers can be down while writes still succeed?

Two: all you need is the leader.

An ISR of 1 satisfies a min ISR of 1. The trade-off: an acknowledged record may exist on a single disk.

Read in post: CCDAK review
InterviewMid15. Batches are always full and you want more producer throughput — what do you change?

Increase batch.size and enable compression.type (lz4 or zstd).

  • Compression works per batch, so bigger batches compress better and save network and disk.
  • If batches aren't full yet, raise linger.ms to wait for more records.
  • Raise buffer.memory if the producer blocks because its buffer is full.
Read in post: CCDAK review
InterviewSenior16. Which errors can the producer retry, and which can't it?

Transient errors are retriable; errors caused by the request itself (too large, not authorised, bad config) are not.

  • Retriable: NOT_ENOUGH_REPLICAS, NOT_LEADER_OR_FOLLOWER, REQUEST_TIMED_OUT, network errors.
  • Non-retriable (retrying won't help): MESSAGE_TOO_LARGE, TOPIC_AUTHORIZATION_FAILED, INVALID_REQUIRED_ACKS, serialisation errors.
  • The producer retries transient errors on its own within delivery.timeout.ms (2 minutes by default); non-retriable errors go straight to the callback.
Read in post: CCDAK review
InterviewMid17. A record with no key, using the default partitioner — which partition does it go to?

Any partition; since 2.4 the producer fills one partition until the batch is full (sticky), then switches.

  • Before 2.4: round-robin per record.
  • From 2.4: the sticky partitioner switches when the batch is full or linger.ms expires, which gives bigger batches.
  • Since 3.3 (KIP-794): the logic is built into the producer (leave partitioner.class unset) and favours partitions on faster brokers; DefaultPartitioner is deprecated.

In my lab, 30 keyless records sent in one burst all landed in the same partition.

Read in post: CCDAK review
InterviewMid18. What happens when you add partitions to a topic that uses keys?

Old records stay where they are; new records with the same key may go elsewhere because hash(key) % partitions changes.

The log is immutable, so nothing is reshuffled. "Same key, same partition" only holds while the partition count stays the same. Changing the number of brokers, producers or the replication factor doesn't affect this mapping.

Read in post: CCDAK review
InterviewJunior19. The group committed offset 643, the partition holds offsets 45 to 2311, auto.offset.reset=latest — where does the consumer start?

At 643.

auto.offset.reset only applies when the group has no valid offset for that partition. The committed offset is still within the retained range, so it's used and latest is ignored.

Read in post: CCDAK review
InterviewMid20. The group committed offset 10 but retained data starts at 45, auto.offset.reset=none — what happens?

The consumer throws an exception: the offset is out of range and there is no reset policy.

none means "don't guess, tell me". With earliest it would jump to 45, with latest to the end of the log. This typically happens when a consumer has been stopped for longer than the retention period.

Read in post: CCDAK review
InterviewMid21. A loop calls commitSync() right after poll() and only then processes the records — what delivery guarantee is that?

At-most-once: offsets are committed before processing, so a crash midway means the remaining records are never processed.

Committing after processing gives at-least-once (a crash means reprocessing). For an effectively-once outcome, combine at-least-once with idempotent processing, or store the offsets in the same transaction as the results.

Read in post: CCDAK review
InterviewMid22. A commit of offset 2000 is lost on the network, then a commit of 3000 succeeds. What should you do?

Nothing: 3000 covers 2000.

A commit means "everything up to here is done". That's also why commitAsync doesn't retry by itself: retrying an old commit could overwrite a newer one.

Read in post: CCDAK review
InterviewJunior23. What happens if you call subscribe() and then assign() on the same consumer?

IllegalStateException ("Subscription to topics, partitions and pattern are mutually exclusive"); I ran it.

subscribe() uses the consumer group mechanism (the broker distributes partitions), assign() picks partitions manually with no rebalancing. To read exactly partitions 0 and 1, use assign() only.

Read in post: CCDAK review
InterviewMid24. Which events trigger a consumer group rebalance?

A change in group membership or in the set of subscribed partitions.

  • A consumer joins the group.
  • A consumer leaves or is considered dead: no heartbeat within session.timeout.ms, or no poll within max.poll.interval.ms.
  • A subscribed topic gains partitions.
  • A new topic matches a subscription pattern.

Producing more messages or adding producers does not.

Read in post: CCDAK review
InterviewMid25. Each batch takes about 6 minutes to process and the consumer keeps getting rebalanced. How do you fix it?

The batch exceeds max.poll.interval.ms (5 minutes by default), so the consumer is kicked out; raise the limit or do less per loop.

  • Raise max.poll.interval.ms to fit.
  • Lower max.poll.records so each loop does less.
  • Or move the heavy work to another thread and pause()/resume() the partitions.

Raising session.timeout.ms doesn't help, because heartbeats run on a separate thread.

Read in post: CCDAK review
InterviewMid26. How do you stop a consumer immediately and shut the application down cleanly?

Call consumer.wakeup() from another thread, catch WakeupException, then close() in a finally block.

For example call it from a shutdown hook; the running poll() throws WakeupException. Commit offsets if needed, then close() so the consumer leaves the group right away instead of waiting for the session timeout. KafkaConsumer isn't thread-safe; wakeup() is the only method meant to be called from another thread.

Read in post: CCDAK review
InterviewSenior27. A producer writes with acks=1 and the followers haven't replicated yet. When does a consumer see the record?

Once the high watermark moves past the record's offset, i.e. every replica in the ISR has it.

Consumers can only read up to the high watermark. So acks=1 makes the producer faster but doesn't let consumers see data sooner; it only lets the producer get an acknowledgement for a record that may later be lost.

Read in post: CCDAK review
InterviewMid28. A partition with RF=3 and min.insync.replicas=2 loses two replicas. Can consumers still read?

Yes: the remaining leader still serves fetches.

Min ISR only blocks producers using acks=all (NotEnoughReplicasException); an acks=1 producer can still write. Min ISR is a rule for writes, not for reads.

Read in post: CCDAK review
InterviewJunior29. Two applications (fulfilment and monitoring) both need every order from one topic. How do you set them up?

Give each application its own group.id.

Within a group each partition goes to one consumer, so a shared group would split the messages between the two applications. Each group has its own offsets, so they read independently.

Read in post: CCDAK review
InterviewJunior30. The target is 1 GB/s and each consumer handles 50 MB/s. What's the minimum number of partitions?

20 partitions (1000 / 50), and 20 consumers in the group to reach that rate.

One partition is read by only one consumer in a group. In practice add headroom for growth, because you can't reduce partitions and adding them changes the key mapping.

Read in post: CCDAK review
InterviewMid31. With log.retention.hours=168, log.retention.minutes=168 and log.retention.ms=168 all set, how long is data kept?

168 milliseconds, because precedence is ms > minutes > hours.

The question tests the precedence, not a setting you'd ever use. Note that deletion happens per segment: the active segment isn't deleted even if it's past retention.

Read in post: CCDAK review
InterviewMid32. A compacted topic receives a record with key K and a null value. What happens, and when does compaction run?

The record is a tombstone: when the log cleaner runs, every older value of K is removed; the tombstone is kept for delete.retention.ms (24 hours by default), then removed too.

  • The tombstone is kept so consumers can see that the key was deleted.
  • The cleaner only works on closed segments, when the dirty ratio exceeds min.cleanable.dirty.ratio (0.5 by default) or max.compaction.lag.ms has passed.
  • Written records can't be modified; to "update" one, write a new record with the same key.
Read in post: CCDAK review
InterviewJunior33. A producer writes to a topic that doesn't exist and the broker has auto.create.topics.enable=true — what happens?

The broker creates the topic with broker settings: num.partitions and default.replication.factor.

The producer can't pass a partition count. Disable this in production: a typo in a topic name creates a junk topic with default settings, often a single partition. The topic is created as soon as a client sends a metadata request for a missing topic (usually the first produce); the broker default is true, so set it to false in production.

Read in post: CCDAK review
InterviewMid34. Which Kafka Streams operators are stateful, and what does a KStream–KTable join return?

Stateful: aggregate, count, reduce, join and windowed operations; a KStream–KTable join returns a KStream.

Stateful operators need a state store (RocksDB) and a changelog topic. Stateless: map, filter, flatMap, branch, peek. In the join, each new stream record looks up the table's current value.

Read in post: CCDAK review
InterviewSenior35. A "purchase" topic has 5 partitions and a "customer" topic has 3; you want to join the stream with the customer table. How?

Use a GlobalKTable for customer, or repartition one side to match.

A KStream–KTable join requires co-partitioning (same partition count, same key partitioning).

  • GlobalKTable: every instance holds the whole table; good for small tables, no co-partitioning needed.
  • Repartition: an extra intermediate topic and more I/O.
Read in post: CCDAK review
InterviewMid36. How are Streams internal topics named, and which flow does Streams exactly-once cover?

After the application.id; exactly-once covers the Kafka → Kafka flow only.

Names look like <application.id>-<store>-changelog and -repartition, so changing application.id loses your state. Exactly-once (processing.guarantee=exactly_once_v2) wraps read, process, write and offset commit in one transaction; side effects such as HTTP calls or writes to another database aren't included.

Read in post: CCDAK review
InterviewSenior37. A Streams app on Kubernetes takes ages to restart because it rebuilds its state. How do you improve that?

Mount a persistent volume for state.dir and add standby replicas.

  • A persistent volume for the state directory (RocksDB): a restart replays only the missing part of the changelog instead of all of it.
  • num.standby.replicas: tasks can move to an instance that already has a copy of the state.

More partitions or more threads don't remove the need to replay the changelog.

Read in post: CCDAK review
InterviewMid38. Where does Schema Registry store schemas, what protocol does it speak, and who rejects an incompatible schema?

In the compacted _schemas topic, over REST (HTTP/HTTPS), and Schema Registry itself rejects incompatible schemas.

  • A producer using KafkaAvroSerializer sends an incompatible schema: the Registry refuses to register it and the serializer throws on the producer side.
  • Brokers never read payloads, so they never reject anything because of a schema.
  • The Registry stores schemas, not Avro data (data lives on the brokers).
  • A consumer that meets a schema id missing from its cache fetches it from the Registry.
Read in post: CCDAK review
InterviewSenior39. In Avro, what kind of evolution is adding a field without a default, and removing a field without a default?

Adding a field without a default is forward compatible; removing one without a default is backward compatible.

  • Adding: consumers on the old schema can read new data (ignoring the unknown field); consumers on the new schema can't read old data because the value is missing.
  • Removing: consumers on the new schema can read old data (ignoring the extra field).
  • With defaults, adding or removing is fully compatible, so always give new fields a default. The Registry's default mode is BACKWARD.

The wire format (magic byte, schema id) and a compatibility-mode table verified in code are in the serialization and Schema Registry post.

Read in post: CCDAK review
InterviewMid40. A JDBC source connector reads 3 tables with tasks.max=2 on a 3-worker cluster. How many tasks run?

Two: tasks = min(tasks.max, units of work) = min(2, 3).

The number of workers doesn't decide the task count. Likewise an S3 sink reading a 2-partition topic has work for at most 2 tasks, even on a 10-broker cluster. In distributed mode, Connect stores configs, offsets and status in three internal topics (config.storage.topic, offset.storage.topic, status.storage.topic).

Read in post: CCDAK review
InterviewJuniorHow do you prepare for CCDAK without dumps?

Learn from the official outline and docs, then verify each behaviour on a cluster running on your own machine.

Read the outline to know the scope, learn from the Apache Kafka and Confluent docs, try each behaviour (offset reset, rebalancing, acks when a broker dies), write your own questions per domain and review them repeatedly. If Confluent provides official sample questions, use them to get used to the format.

Read in post: CCDAK review
InterviewJuniorWhy are so many Kafka exam-prep answers outdated?

Because many question banks were written when Kafka still used ZooKeeper, and Kafka 4.0 removed ZooKeeper entirely.

Questions on ACLs, dynamic configs, controller election and the CLI's --zookeeper flag now have different answers: metadata lives in __cluster_metadata, managed by the KRaft controller quorum. Producer defaults also changed in 3.0 (acks=all, idempotence on).

Read in post: CCDAK review
InterviewMidExplain at-most-once, at-least-once and exactly-once on the consumer side.

Commit before processing is at-most-once, after processing is at-least-once; exactly-once exists only for Kafka → Kafka flows inside one transaction.

  • At-most-once: a crash loses records.
  • At-least-once: a crash means reprocessing, so processing must be idempotent.
  • Exactly-once: read–process–write inside one Kafka transaction (Streams exactly_once_v2). With external systems, use at-least-once plus deduplication, or store offsets in the same transaction as the results.
Read in post: CCDAK review
InterviewMidHow do acks, min.insync.replicas and unclean leader election relate?

Together (typically all, 2 on RF 3, unclean disabled) they guarantee that an acknowledged record survives the loss of one broker.

  • acks=all waits for every replica in the ISR.
  • min.insync.replicas sets the minimum ISR size for accepting acks=all writes.
  • Disabling unclean election makes sure only ISR replicas become leader.
Read in post: CCDAK review
InterviewSeniorWhat does KRaft change compared to ZooKeeper, operationally?

One system instead of two: no separate ZooKeeper ensemble to patch, monitor and secure, and faster controller failover.

Metadata is a log replicated with Raft and brokers receive changes as events, so clusters can handle more partitions. You need to plan the controller quorum (3 or 5 voters, ideally separate from brokers in production), monitor it with kafka-metadata-quorum, and migrate on 3.x before moving to 4.x.

Read in post: CCDAK review
InterviewSeniorWhat does a CCDAK certificate tell you when hiring a senior backend engineer?

It shows solid knowledge of Kafka's APIs and semantics, not the ability to design.

The candidate knows offsets, delivery guarantees and replication; the certificate says nothing about deciding whether to use Kafka at all, choosing keys, handling failures, the outbox, operations and monitoring. In interviews I still ask a real scenario, e.g. design a consumer that updates balances without losing or double-applying anything.

Read in post: CCDAK review
Trade-offSeniorOptimistic or pessimistic: choose by contention, not by tasteIn the booking lab, the flight row is a hot row: optimistic locking needed 1,028 retries and 176 of 400 requests gave up after 5 attempts; pessimistic locking needed no retries. For a counter, the best option is a conditional UPDATE.
Pessimistic (FOR UPDATE) Optimistic (version)
On conflict The second request waits The second request fails, re-reads and retries
Fits High contention, retries are expensive Low contention, read-heavy
Cost with no conflict You still pay for holding the lock Close to zero
Spans several HTTP requests No (the lock dies with the transaction) Yes (send version to the client, like an ETag)
Risks Deadlocks, pool exhaustion when locks are held long Retry storms, rejecting users while stock remains

In the booking lab, the flight row is a hot row: optimistic locking needed 1,028 retries and 176 of 400 requests gave up after 5 attempts; pessimistic locking needed no retries. For a counter, the best option is a conditional UPDATE.

Read in post: Optimistic or pessimistic locking
Edge caseSeniorOptimistic locking doesn't mean no locks and no deadlocksUPDATE ... WHERE version = ? still takes an X lock (write lock) on the row until commit. "No locks" is only true for the read-and-think phase. If two requests update several versioned rows (two legs of a connecting flight) in a different order, deadlocks still happen; the rule of locking in a fixed order still applies.

UPDATE ... WHERE version = ? still takes an X lock (write lock) on the row until commit. "No locks" is only true for the read-and-think phase. If two requests update several versioned rows (two legs of a connecting flight) in a different order, deadlocks still happen; the rule of locking in a fixed order still applies.

Read in post: Optimistic or pessimistic locking
Edge caseMidUsing a timestamp instead of a version for optimistic locking can miss conflictsThe slides say "timestamp: not recommended", because: TIMESTAMP/DATETIME columns default to one-second precision: two updates within the same second produce the same value, and the conflict slips through. If the application sets the time, clocks differ between machines and can even go backwards when NTP corrects them.

The slides say "timestamp: not recommended", because:

  • TIMESTAMP/DATETIME columns default to one-second precision: two updates within the same second produce the same value, and the conflict slips through.
  • If the application sets the time, clocks differ between machines and can even go backwards when NTP corrects them.

An ever-increasing integer version has none of these problems. A timestamp is only tolerable if the database assigns it with microsecond precision.

Read in post: Optimistic or pessimistic locking
Edge caseSenior"Subtract first, add later" does not prevent deadlocksTwo transfers in opposite directions, A→B and B→A, both "subtract first": T1 locks A, T2 locks B, then T1 asks for B and T2 asks for A. A cycle, and InnoDB rolls one back with error 1213. What prevents deadlocks is locking in a fixed order (lower id first, whatever the direction), which breaks the "circular wait" condi

Two transfers in opposite directions, A→B and B→A, both "subtract first": T1 locks A, T2 locks B, then T1 asks for B and T2 asks for A. A cycle, and InnoDB rolls one back with error 1213. What prevents deadlocks is locking in a fixed order (lower id first, whatever the direction), which breaks the "circular wait" condition. "Subtract first" is a rule about business logic and how many locks you hold, not about lock order.

Read in post: Optimistic or pessimistic locking
Trade-offSeniorSeat booking: which mechanism for the seat counterA single-row counter (seats left): a conditional UPDATE ... WHERE availableseats 0 is the default: correct, fastest, no retries. Use pessimistic FOR UPDATE when you need to read several things before deciding within the same transaction. Optimistic version: for low-contention operations (editing passenger details, chan
  • A single-row counter (seats left): a conditional UPDATE ... WHERE available_seats > 0 is the default: correct, fastest, no retries. Use pessimistic FOR UPDATE when you need to read several things before deciding within the same transaction.
  • Optimistic version: for low-contention operations (editing passenger details, changing seats within your own booking), or when a "version" must survive several HTTP requests. On a hot row it causes retry storms and false rejections.
  • Distributed lock: when the section that must be exclusive extends beyond the database. Always pair it with a fencing token (the version) where the final write happens, because a lock with a TTL will sometimes expire mid-flight.
  • When one flight's load exceeds what a single hot row can take, change the model (one row per seat, pre-holding in Redis, a virtual waiting room), not the kind of lock. The post on airline booking: holding seats under concurrency goes deep on that.
Read in post: Optimistic or pessimistic locking
InterviewJuniorWhy can't synchronized fix a race condition on database writes?

Because synchronized only locks within one JVM, while the data lives in a database shared by every instance.

Two instances behind a load balancer have two independent locks, so two requests still read and write together. Protect it in the database (conditional statements, FOR UPDATE, versions) or with a distributed lock.

Read in post: Optimistic or pessimistic locking
InterviewJuniorWhat is the core difference between pessimistic and optimistic locking?

On conflict, pessimistic locking makes the second request wait; optimistic locking makes it fail and retry.

Pessimistic locking locks before acting. Optimistic locking doesn't lock on read and only checks at write time (usually with a version column). One pays in waiting time, the other in redone work.

Read in post: Optimistic or pessimistic locking
InterviewMidHow does optimistic locking with a version column work?

Write with a condition that version still equals the value you read, and bump it; zero affected rows means someone changed it first.

On write: UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?. One row means you won; zero means re-read and retry (or tell the user). With JPA you just add @Version, and Hibernate throws OptimisticLockException when zero rows are affected.

Read in post: Optimistic or pessimistic locking
InterviewMidWhy shouldn't you use a timestamp instead of a version for optimistic locking?

Because timestamps can collide or go backwards, so conflicts slip through.

Time columns often have only one-second precision, so two updates in the same second get the same value. If the application sets the time, machine clocks differ and can go backwards. An ever-increasing integer version has none of these problems.

Read in post: Optimistic or pessimistic locking
InterviewSeniorWhen do you choose optimistic and when pessimistic? Give an example with numbers.

By contention: when it's low, optimistic is nearly free; on a hot row, use pessimistic or, better, a conditional update.

Editing a user profile: optimistic. A flight's seat counter: in my experiment with 400 requests for 100 seats, optimistic took over 1,000 retries and 176 requests gave up while seats were still available, whereas FOR UPDATE needed no retries. A single conditional update beats both.

Read in post: Optimistic or pessimistic locking
InterviewSeniorWhy do you need both a distributed lock and optimistic locking, not just one?

The lock reduces conflicts and protects work outside the database; the version rejects the write of whoever lost the lock when it expires mid-flight.

A distributed lock has a TTL, so a GC pause or a slow network can leave two parties both believing they hold it. The version in the database is a fencing token. In my experiment with a TTL shorter than the work: without a version, 311 tickets were sold for 100 seats; with a version, exactly 100.

Read in post: Optimistic or pessimistic locking
InterviewSeniorDoes the "subtract first, add later" rule for transfers prevent deadlocks?

No. Preventing deadlocks needs a fixed lock order (lower id first), plus a retry loop for error 1213.

Two transfers in opposite directions, A→B and B→A, both debiting first, each lock one account and then wait for each other. "Subtract first" only lets you stop early on insufficient funds and never shows money at the receiver before it leaves the sender.

Read in post: Optimistic or pessimistic locking
Trade-offSeniorOpen model or closed modelOpen: matches Internet traffic (users don't know the server is slow) and exposes queues and timeouts under overload. Needs enough spare VUs (virtual users) in the tool, or requests get dropped. Closed: matches systems with a fixed number of clients: queue workers, batch jobs, another service's connection pool, a bounde
  • Open: matches Internet traffic (users don't know the server is slow) and exposes queues and timeouts under overload. Needs enough spare VUs (virtual users) in the tool, or requests get dropped.
  • Closed: matches systems with a fixed number of clients: queue workers, batch jobs, another service's connection pool, a bounded set of internal users. Easy to set up but hides overload.
  • You can mix them: sessions arrive in an open model, each session is a chain of requests with think time.
Read in post: Performance testing
Edge caseSeniorA closed-model tool reports a great p99 while users wait a full secondSigns: achieved throughput is below the target while latency looks fine, or max is huge while p99 is tiny. Use an open-model executor (k6 constant-arrival-rate, Gatling injectOpen, JMeter's Open Model Thread Group) or a tool that corrects coordinated omission such as wrk2, and always compare achieved throughput with th

Signs: achieved throughput is below the target while latency looks fine, or max is huge while p99 is tiny. Use an open-model executor (k6 constant-arrival-rate, Gatling injectOpen, JMeter's Open Model Thread Group) or a tool that corrects coordinated omission such as wrk2, and always compare achieved throughput with the target.

Read in post: Performance testing
Edge caseMidAveraging the p99 of several instancesPercentiles can't be added or averaged: the average of 10 pods' p99s is not the service's p99. Merge histograms (bucket counts) first, then compute the percentile, for example Prometheus histogramquantile over summed buckets, or enable publishPercentileHistogram in Micrometer instead of per-pod precomputed percentiles.

Percentiles can't be added or averaged: the average of 10 pods' p99s is not the service's p99. Merge histograms (bucket counts) first, then compute the percentile, for example Prometheus histogram_quantile over summed buckets, or enable publishPercentileHistogram in Micrometer instead of per-pod precomputed percentiles.

Read in post: Performance testing
TILMidLittle's law cross-checks your numbersL = λ × W holds for any stable system. 400 req/s at 50 ms average latency means 20 requests in flight on average. If the server has 200 threads that are always busy, the numbers contradict each other: there is a hidden queue somewhere, or the tool is measuring wrong. It also sizes pools: connections needed ≈ query rate

L = λ × W holds for any stable system. 400 req/s at 50 ms average latency means 20 requests in flight on average. If the server has 200 threads that are always busy, the numbers contradict each other: there is a hidden queue somewhere, or the tool is measuring wrong. It also sizes pools: connections needed ≈ query rate × connection hold time.

Read in post: Performance testing
Edge caseMidThe load generator is the bottleneck, not the serverA generator that runs out of CPU or network ports caps throughput and adds its own latency. Signs: the server is idle, throughput won't grow, k6 reports droppediterations. Run it on its own machine, watch its CPU, spread it over several machines, and try an empty endpoint to learn the tool's ceiling.

A generator that runs out of CPU or network ports caps throughput and adds its own latency. Signs: the server is idle, throughput won't grow, k6 reports dropped_iterations. Run it on its own machine, watch its CPU, spread it over several machines, and try an empty endpoint to learn the tool's ceiling.

Read in post: Performance testing
Trade-offSeniorJMH or a load testJMH (Java Microbenchmark Harness) measures one method inside one JVM and handles warm-up, forking and keeping the JIT from deleting your code. Good for choosing between two implementations (a parser, an algorithm, a data structure). Blind to the network, the database, locks between requests and GC under real load. A lo
  • JMH (Java Microbenchmark Harness) measures one method inside one JVM and handles warm-up, forking and keeping the JIT from deleting your code. Good for choosing between two implementations (a parser, an algorithm, a data structure). Blind to the network, the database, locks between requests and GC under real load.
  • A load test measures the whole system under concurrent load. It answers SLO and capacity questions, but is too coarse to compare two ways of writing a method.
  • A 30% gain in JMH may not move p99 at all if that method is 2% of request time. Profile first, then microbenchmark.
Read in post: Performance testing
InterviewJuniorHow do load, stress and soak tests differ?

A load test checks that expected traffic meets the SLO, a stress test pushes past it to see how the system breaks, and a soak test holds moderate load for hours to find problems that accumulate.

A spike test adds the sudden-jump case, and a capacity test finds the highest load that still meets the SLO. It's the same script with a different load shape over time.

Read in post: Performance testing
InterviewJuniorWhy report p99 instead of average latency?

The average hides the slow tail; p99 tells you how long the slowest 1% of requests wait.

In this post's experiment, the 148 ms average matched no request: most took 2–3 ms, the rest hundreds of ms. A page that calls many APIs hits the slow tail far more often than 1% of the time.

Read in post: Performance testing
InterviewMidWhat is the difference between open and closed workload models, and which do you choose?

A closed model has a fixed number of users who wait for a response before sending again, so load drops when the server slows; an open model sends at a fixed arrival rate regardless of responses.

Public APIs should be tested with an open model because users don't know the server is slow. A closed model fits systems with a bounded number of clients, like workers or batch jobs. In a closed model, throughput = N / (response time + think time).

Read in post: Performance testing
InterviewMidWhat is coordinated omission?

A measurement error where the tool waits for a response before sending the next request: while the server is frozen, the tool stops sending, so it records one slow sample instead of hundreds.

In the experiment, a server freezing 1 s every 5 s gave a naive p99 of 2.6 ms and a p99 of 975 ms measured from the intended send time. Fix it with an open model, by measuring from the intended time, or with tools that correct for it such as wrk2 and HdrHistogram.

Read in post: Performance testing
InterviewMidHow do you set goals for a load test?

From the SLO and production traffic: peak rate times a safety factor, the real request mix, p95/p99 and error-rate thresholds per endpoint, plus resource thresholds.

Write them all into the script as thresholds so the test fails itself and can run in CI. Without numbers there is no conclusion.

Read in post: Performance testing
InterviewSeniorThroughput stops at 800 req/s while the service's CPU is at 40%. How do you investigate?

Low CPU with flat throughput means something is waiting: find the resource whose queue is growing.

  • Check the load generator first: its CPU, dropped_iterations.
  • Pools: requests waiting for a DB connection (hikaricp.connections.pending), the HTTP client pool, a full server thread pool.
  • Locks: thread dumps with many threads BLOCKED on one monitor, lock waits in the database.
  • Downstream: the database or a slow dependency (look at traces), CPU throttling from limits.
  • Little's law: 800 req/s × latency gives requests in flight; compare that with each pool's size to see which one is full.
Read in post: Performance testing
InterviewSeniorYou have the p99 of 10 pods. What is the p99 of the service?

You can't compute it from those ten numbers: percentiles can't be averaged or added. Merge histograms, then compute.

Use histogram metrics (bucket counts), sum the buckets across pods and apply histogram_quantile. The average of p99s usually understates the real p99 when one pod is much slower than the rest.

Read in post: Performance testing
InterviewSeniorWhen do you use JMH and when a load test?

JMH compares two implementations of a piece of code inside one JVM; a load test checks whether the whole system meets the SLO under concurrent load.

JMH handles warm-up, forking and dead code elimination, but can't see the database, the network or locks between requests. Profile under load first to learn which method is worth optimising, then use JMH; otherwise a 30% gain on a method that is 2% of request time won't change p99.

Read in post: Performance testing
Edge caseMidhasRole('ADMIN') checks the authority ROLE_ADMIN, not ADMINhasRole('ADMIN') adds a prefix and looks for the authority ROLEADMIN; hasAuthority('ADMIN') matches the exact string. If your converter maps the roles claim to ADMIN without the prefix, every hasRole returns 403 even though the token is fine. The resource server maps each scope to SCOPE<scope by default, so scope check

hasRole('ADMIN') adds a prefix and looks for the authority ROLE_ADMIN; hasAuthority('ADMIN') matches the exact string. If your converter maps the roles claim to ADMIN without the prefix, every hasRole returns 403 even though the token is fine.

The resource server maps each scope to SCOPE_<scope> by default, so scope checks must read hasAuthority('SCOPE_flights:create'). Pick one convention, configure JwtGrantedAuthoritiesConverter to match, and test both the allowed and the denied case.

Read in post: Authorization, SSO and OAuth2
Trade-offSeniorPermissions inside the JWT, or looked up per requestPermissions in the token: no DB call, every service can read them. The cost: tokens grow (past 8 KB of headers you hit the default limit of many proxies and Tomcat), and permissions are stale until the token expires. Token carries identity only, services look permissions up in the DB or a short-TTL cache (evicted when
  • Permissions in the token: no DB call, every service can read them. The cost: tokens grow (past 8 KB of headers you hit the default limit of many proxies and Tomcat), and permissions are stale until the token expires.
  • Token carries identity only, services look permissions up in the DB or a short-TTL cache (evicted when bindings change): small tokens, near-instant revocation, one extra lookup on the hot path.
  • Usually combined: 5–15 minute access tokens with coarse permissions, sensitive actions (moving money, deleting data) re-checked at call time, and emergency revocation through a deny list keyed by sub or jti.
Read in post: Authorization, SSO and OAuth2
Edge caseMidChanging permissions in the DB doesn't change tokens already issuedRemoving a user's role in the DB does nothing to the token they hold: it stays valid with the old permissions until exp. The classic story: someone leaves the company and can still call admin APIs for hours because access tokens live for 24 hours. The fix: short access tokens, re-check current permissions when exchangi

Removing a user's role in the DB does nothing to the token they hold: it stays valid with the old permissions until exp. The classic story: someone leaves the company and can still call admin APIs for hours because access tokens live for 24 hours.

The fix: short access tokens, re-check current permissions when exchanging a refresh token, and check sensitive operations against the source of truth.

Read in post: Authorization, SSO and OAuth2
Edge caseSeniorChecking a permission without checking ownership is an IDORhasAuthority('bookings:read') answers "may this user read bookings", not "may they read booking 42". Every endpoint that takes an id from the client must also check the user–object relationship (owner, same tenant). The safest place is the query itself (WHERE id = ? AND ownerid = ?, or Hibernate 6's @TenantId), returni

hasAuthority('bookings:read') answers "may this user read bookings", not "may they read booking 42". Every endpoint that takes an id from the client must also check the user–object relationship (owner, same tenant).

The safest place is the query itself (WHERE id = ? AND owner_id = ?, or Hibernate 6's @TenantId), returning 404 so you don't reveal that the object exists. A mandatory test: user A requests user B's id and expects 404.

Read in post: Authorization, SSO and OAuth2
Trade-offSeniorRBAC, roles + permissions, ABAC or ReBACPlain RBAC: simple, enough for internal systems with few roles; changes need a deploy and roles tend to explode. Roles + permissions: stable code, runtime changes; the default for most backends, but it can't express ownership or context by itself. ABAC (OPA, Cedar): expresses attribute-based rules; policies are hard to
  • Plain RBAC: simple, enough for internal systems with few roles; changes need a deploy and roles tend to explode.
  • Roles + permissions: stable code, runtime changes; the default for most backends, but it can't express ownership or context by itself.
  • ABAC (OPA, Cedar): expresses attribute-based rules; policies are hard to read, hard to test, and make "who can do what" hard to answer.
  • ReBAC (OpenFGA, SpiceDB): fits sharing and hierarchies; you must sync relationships into the authorization system and accept extra latency. In practice: roles + permissions for functional access plus ownership/tenant conditions in queries; move to ABAC or ReBAC only when the rules really require it.
Read in post: Authorization, SSO and OAuth2
Edge caseSeniorA parent-domain cookie makes every subdomain part of your security boundarySetting the token with Domain=example.com means any subdomain (the blog, an agency-built landing page, a CNAME pointing at a cancelled service) receives the token and can overwrite it. One taken-over subdomain (subdomain takeover) is enough to steal sessions or force a victim into the attacker's session (cookie tossing

Setting the token with Domain=example.com means any subdomain (the blog, an agency-built landing page, a CNAME pointing at a cancelled service) receives the token and can overwrite it. One taken-over subdomain (subdomain takeover) is enough to steal sessions or force a victim into the attacker's session (cookie tossing).

If you must share: limit it to tightly controlled hosts, use Secure; HttpOnly; SameSite=Lax, and audit DNS regularly. Better, use a central IdP with a host-only __Host- cookie per app.

Read in post: Authorization, SSO and OAuth2
Trade-offSeniorSSO via a parent-domain cookie, or via a central IdP with OIDCParent-domain cookie + one app acting as auth server: quick, no new component; limited to one parent domain, every subdomain inside the trust boundary, apps coupled to each other, logout and MFA are on you. IdP + OIDC: works across domains, passwords in one place, MFA and social login configured centrally, standard log
  • Parent-domain cookie + one app acting as auth server: quick, no new component; limited to one parent domain, every subdomain inside the trust boundary, apps coupled to each other, logout and MFA are on you.
  • IdP + OIDC: works across domains, passwords in one place, MFA and social login configured centrally, standard logout; the price is running an IdP (it needs HA) or paying for one, and understanding the flows properly. Two internal apps with few users can live with the first; from three apps, or as soon as external users appear, go with an IdP.
Read in post: Authorization, SSO and OAuth2
Edge caseSeniorUsing an OAuth2 access token as proof of loginAn access token only proves "someone granted some client access to an API", and it may have been issued to a different client. "Login with OAuth" implemented as "take an access token and call the profile API" has caused many account takeovers: the attacker brings a token issued to their own app and replays it into your

An access token only proves "someone granted some client access to an API", and it may have been issued to a different client. "Login with OAuth" implemented as "take an access token and call the profile API" has caused many account takeovers: the attacker brings a token issued to their own app and replays it into yours.

For login, use OIDC and validate the ID token: signature, iss, aud equal to your client id, exp, nonce. Conversely, APIs must not accept ID tokens in place of access tokens.

Read in post: Authorization, SSO and OAuth2
TILMidOAuth 2.1 bundles the best practices: PKCE everywhere, no implicit or password grantsOAuth 2.1 (an IETF draft) adds no new concepts; it turns existing advice into the standard: PKCE is required for every client including confidential ones, the implicit and password grants are removed, redirect URIs must match exactly, refresh tokens for public clients must be rotated or sender-constrained, and bearer t

OAuth 2.1 (an IETF draft) adds no new concepts; it turns existing advice into the standard: PKCE is required for every client including confidential ones, the implicit and password grants are removed, redirect URIs must match exactly, refresh tokens for public clients must be rotated or sender-constrained, and bearer tokens never go in query strings.

Read in post: Authorization, SSO and OAuth2
InterviewJuniorHow does authentication differ from authorization?

Authentication establishes who you are; authorization decides what you may do to which resource, and runs after authentication.

At the airport: the security checkpoint checks your ID, the gate checks your boarding pass. In HTTP: missing or invalid identity is 401, valid identity without the right is 403.

Read in post: Authorization, SSO and OAuth2
InterviewJuniorWhat is RBAC and where does it fall short?

Users are assigned roles and each feature allows some roles. Simple and easy to explain.

It falls short with overlapping roles, role explosion when you need fine distinctions, and, if roles are checked directly in code, every access change needs a redeploy.

Read in post: Authorization, SSO and OAuth2
InterviewJuniorWhat is SSO?

Sign in once, use many applications.

An identity provider holds a global session; a second app redirects the user to the IdP, which sees they're already signed in and returns straight away. The common protocols are OpenID Connect and SAML.

Read in post: Authorization, SSO and OAuth2
InterviewMidWhy check permissions rather than roles in code?

Permissions (flights:create) map to features, so they're stable; roles are sets of permissions stored in the DB, so they can change at runtime.

Granting a role a new right is a row of data rather than a deploy, and role explosion stays out of the code.

Read in post: Authorization, SSO and OAuth2
InterviewMidHow does OAuth 2.0 differ from OpenID Connect?

OAuth is delegation; OIDC is authentication built on OAuth. Use the ID token for login and the access token for API calls.

OAuth: a client calls an API on a user's behalf with limited scope, and gets an access token meant for the resource server. OIDC adds the openid scope and an ID token (a JWT) telling the client who the user is.

Read in post: Authorization, SSO and OAuth2
InterviewMidWhy does the authorization code flow need PKCE?

Because the code travels through a browser redirect and can be intercepted; PKCE makes an intercepted code useless.

The code can leak through a malicious app registering the same URL scheme, or through logs. PKCE makes the client send SHA256(code_verifier) up front and the verifier when exchanging the code; a stolen code without the verifier gets no token. OAuth 2.1 requires PKCE for every client.

Read in post: Authorization, SSO and OAuth2
InterviewSeniorGET /bookings/{id} already has hasAuthority('bookings:read'). What's missing?

An object-level check: a user who changes the id reads someone else's booking (an IDOR, part of A01 Broken Access Control).

Put the ownership or tenant condition into the query, return 404 when nothing matches, and keep a test where user A requests user B's id.

Read in post: Authorization, SSO and OAuth2
InterviewSeniorShould permissions live in the JWT or be looked up per request?

Combine them: 5–15 minute access tokens with coarse permissions, sensitive actions re-checked against the source of truth.

In the token there's no DB call, but tokens grow and permissions only update when the token expires. Per-request lookup (with a short-TTL cache) keeps tokens small and revocation fast, at the cost of latency. Also: re-check permissions on refresh, and keep a deny list by sub/jti for emergencies.

Read in post: Authorization, SSO and OAuth2
InterviewSeniorAssess an SSO design based on a parent-domain cookie.

It works because a Domain=domain.com cookie reaches every subdomain, but the trust boundary is too wide and it doesn't scale.

Every subdomain can read and overwrite the token (subdomain takeover, cookie tossing), it doesn't extend to other domains, the apps are coupled through a shared DB and an app doubling as auth server, and logout and MFA are home-made. The standard design: a central IdP, OIDC authorization code + PKCE, a host-only session per app, back-channel logout.

Read in post: Authorization, SSO and OAuth2
InterviewSeniorWhat does logout involve in an SSO system?

Three things: per-app sessions, the IdP's global session, and the tokens already issued.

Ending an app session without ending the IdP session just signs the user straight back in. Use RP-initiated logout for the IdP session, back-channel logout to notify the other apps, short-lived access tokens, and refresh token revocation.

Read in post: Authorization, SSO and OAuth2
Edge caseSeniorScoring options before agreeing on prioritiesA table of five options × ten criteria looks objective, but until you've settled which dimension matters most (latency? cost? time to market?), everyone silently applies different weights and the argument never ends. The right order: settle the top three dimensions and their weights, then score. Record the weights in t

A table of five options × ten criteria looks objective, but until you've settled which dimension matters most (latency? cost? time to market?), everyone silently applies different weights and the argument never ends.

The right order: settle the top three dimensions and their weights, then score. Record the weights in the ADR (Architecture Decision Record, a document capturing one architectural decision and its reasons), so that when the context changes (a startup becoming an enterprise) people can still see why the old decision made sense.

Read in post: Analysing trade-offs like a senior
Trade-offSeniorPick a sweet spot or find a way to resolve the trade-offSweet spot: fast, low risk, uses known options. But you always lose something on one dimension, and when the context changes (10× the load) the old balance point stops being right. Resolving the trade-off (a new design, separating components, changing the data model): can be better on every dimension, but costs design
  • Sweet spot: fast, low risk, uses known options. But you always lose something on one dimension, and when the context changes (10× the load) the old balance point stops being right.
  • Resolving the trade-off (a new design, separating components, changing the data model): can be better on every dimension, but costs design effort, adds components and brings harmful effects you don't know yet.

Pick a sweet spot when the problem isn't your competitive core, the deadline is close, or mistakes are cheap. Resolve it when it's a recurring bottleneck, the sacrificed dimension is something users genuinely need, and the team can run the new part. Either way, record in an ADR the point you chose, why, and when you'd revisit it.

Read in post: Analysing trade-offs like a senior
Edge caseSeniorPresenting an option with no downsides"This option has no downsides" is a red flag: listeners assume you haven't analysed it. For every choice, cover at least what it costs (money, people, complexity), how it fails (failure modes), what it locks you into, and when you'd switch. A template: "I chose X because A and B matter most; in exchange we accept C; if

"This option has no downsides" is a red flag: listeners assume you haven't analysed it. For every choice, cover at least what it costs (money, people, complexity), how it fails (failure modes), what it locks you into, and when you'd switch.

A template: "I chose X because A and B matter most; in exchange we accept C; if load goes beyond N we'd move to Y."

Read in post: Analysing trade-offs like a senior
Trade-offSeniorBoring technology vs new technologyBoring technology (PostgreSQL, Redis, a well-modularised monolith): failure modes are known and documented, hiring is easy, tooling is mature. In exchange it may not be the absolute best fit for a specific problem. New technology: may solve the problem markedly better, but carries unknown harmful effects (bugs, no oper
  • Boring technology (PostgreSQL, Redis, a well-modularised monolith): failure modes are known and documented, hiring is easy, tooling is mature. In exchange it may not be the absolute best fit for a specific problem.
  • New technology: may solve the problem markedly better, but carries unknown harmful effects (bugs, no operational experience, a small community). That cost is usually underestimated because nobody can list it.

A practical rule: default to boring technology. Choose something new only when it addresses the product's real differentiator, someone on the team owns running it, and there's a way back. Before adding a system, ask "can the PostgreSQL we already run do 80% of this?" (for example, a table as a queue with SKIP LOCKED before standing up a broker).

Read in post: Analysing trade-offs like a senior
Trade-offSeniorCQRS: separate read and write models to resolve a trade-offWhen one model serves both writes (normalisation, constraints, short transactions) and reads (pre-joined data, many indexes, full-text search), every optimisation for one side hurts the other. CQRS (Command Query Responsibility Segregation) splits it into a write model and one or more read models updated from events or

When one model serves both writes (normalisation, constraints, short transactions) and reads (pre-joined data, many indexes, full-text search), every optimisation for one side hurts the other. CQRS (Command Query Responsibility Segregation) splits it into a write model and one or more read models updated from events or CDC.

  • Benefit: each side is optimised and scaled independently.
  • Cost: reads lag behind (eventual consistency), there's a sync pipeline to monitor, and users may not immediately see their own changes (some screens need read-your-writes).

It's only worth it when read and write load differ sharply, or read queries look nothing like the write structure. For ordinary CRUD, one model and a few indexes are enough.

Read in post: Analysing trade-offs like a senior
Trade-offSeniorSidecar or an in-process libraryCross-cutting concerns (mTLS, retries, rate limiting, metrics) can live in a library inside the app or in a sidecar (a service mesh such as Istio/Linkerd, or an agent next to the app). Library (Resilience4j, Micrometer): no extra network hop, easy to debug. But one implementation per language, and changing a policy mea

Cross-cutting concerns (mTLS, retries, rate limiting, metrics) can live in a library inside the app or in a sidecar (a service mesh such as Istio/Linkerd, or an agent next to the app).

  • Library (Resilience4j, Micrometer): no extra network hop, easy to debug. But one implementation per language, and changing a policy means redeploying every service.
  • Sidecar: separation in space, language-independent, and the platform team changes policies without touching app code. In exchange there's latency on every hop (typically around a millisecond or less), extra resources per pod, and one more layer to understand when debugging.

A few services in one language: a library is usually enough. Dozens of services, several languages and uniform security requirements: a sidecar pays off.

Read in post: Analysing trade-offs like a senior
Edge caseSeniorSeparating components to resolve a trade-off creates new trade-offsSidecars, CQRS, splitting services or adding CDC all remove an old coupling, but each adds something new: a network hop, a sync pipeline to monitor, eventual consistency, one more thing that can break at 2 a.m. Before separating, rerun Seven-So-What on the new design and put the consequences in the ideality denominator

Sidecars, CQRS, splitting services or adding CDC all remove an old coupling, but each adds something new: a network hop, a sync pipeline to monitor, eventual consistency, one more thing that can break at 2 a.m.

Before separating, rerun Seven-So-What on the new design and put the consequences in the ideality denominator. If the current coupling isn't causing real, measurable pain, leaving it alone is often right.

Read in post: Analysing trade-offs like a senior
InterviewJuniorWhat is a trade-off? Give a backend example.

A trade-off is when improving one aspect means accepting something worse in another.

Caching, for instance: reads get faster and the database gets lighter, but data can be stale until the TTL expires and there's one more system to run. Or an index: faster reads, but slower writes and more storage.

Read in post: Analysing trade-offs like a senior
InterviewMidHow do dimensional and alternative trade-offs differ?

Dimensional trade-offs are between quality attributes (problem space); alternative trade-offs are between concrete options (solution space).

Dimensional: security vs performance, consistency vs availability, scalability vs cost. Alternative: SQL vs NoSQL, monolith vs microservices. Choosing an option places you at a point on the curve between attributes, so when presenting, state the attributes you prioritised before naming the technology.

Read in post: Analysing trade-offs like a senior
InterviewMidWhy do many teams choose "boring technology"?

Because familiar technology has known failure modes, while the harms of new technology usually aren't in the comparison table because nobody has hit them yet.

Familiar technology comes with documentation, tooling and people you can hire. A company only has a few "innovation tokens", so spend them on what differentiates the product. It doesn't mean never using anything new, but there should be a clear reason, an owner to run it and a way back.

Read in post: Analysing trade-offs like a senior
InterviewSeniorTwo seniors on your team disagree on Kafka vs RabbitMQ. How do you handle it?

Agree on the top three attributes for this use case first, because the disagreement usually comes from silently different priorities; then score, measure and write an ADR.

  • Example attributes: per-key ordering, replay, latency, operational simplicity.
  • Score each option on those attributes and list the harmful effects. If the argument is about numbers, run a PoC with realistic load.
  • Record the decision in an ADR with the rejected option and the conditions for revisiting it.
  • Still disagreeing: the accountable person (tech lead, architect) decides and the team disagrees and commits.
Read in post: Analysing trade-offs like a senior
InterviewSeniorGive an example of a trade-off you "resolved" rather than just picking a balance point.

Cache invalidation: instead of choosing a long or short TTL, use CDC on the WAL/binlog to evict cache entries as soon as data changes, keeping a long TTL as a safety net.

A long TTL means a light database but stale data, a short one the opposite; CDC gives both. Another example: CQRS separates the read and write models so each is optimised on its own. How to tell it: name the coupling that caused the trade-off, how you separated it (in time, in space, parts vs whole), and the new harmful effects the design brought (a CDC pipeline to monitor, eventual consistency).

Read in post: Analysing trade-offs like a senior
InterviewSeniorHow does the TRIZ ideality formula help you choose an option?

Ideality = total benefits / (total resources + total harmful effects); it forces you to look at the denominator.

An option with a moderate benefit that costs and harms almost nothing (moving a batch job, adding an index) often beats one with a big benefit that adds a whole system. The numbers aren't precise; the value is that everyone has to state their assumptions about cost and harm, especially long-term operational cost.

Read in post: Analysing trade-offs like a senior
InterviewSeniorWhich trade-off does functional core, imperative shell resolve?

The one between fast, easy-to-reason-about tests and the need to do I/O, transactions and read the clock.

The core holds only pure logic (input → output, no side effects), tested with millisecond unit tests. The thin shell handles I/O and calls the core, so it needs only a few integration tests. It's separation between parts and the whole: each part is rigid (pure, immutable), while the whole can still do stateful work. In Spring: records and static methods for the calculations, a @Service that only orchestrates, and an injected Clock instead of calling now() inside the core.

Read in post: Analysing trade-offs like a senior
InterviewSeniorIn a system design interview, how do you talk about trade-offs convincingly?

Top-down: the conclusion first, then the attributes you prioritised, the price you accept, the failure modes, and the condition that would change the decision.

For example: "I'd pick X because A and B matter most here; in exchange, C; if QPS goes past N, I'd move to Y." Always mention at least one rejected alternative and why. Never claim "no downsides", and state your assumptions so the interviewer can change one and see how you adapt.

Read in post: Analysing trade-offs like a senior
Edge caseMidA large OFFSET still reads every skipped rowOFFSET 100000 LIMIT 12 doesn't jump to row 100,001: the database still reads and discards the first 100,000 rows. Deep pages get slower, and if a row is inserted between two clicks, the next page repeats a row from the previous one. For infinite feeds or export APIs use keyset pagination (WHERE id < :lastId ORDER BY id

OFFSET 100000 LIMIT 12 doesn't jump to row 100,001: the database still reads and discards the first 100,000 rows. Deep pages get slower, and if a row is inserted between two clicks, the next page repeats a row from the previous one. For infinite feeds or export APIs use keyset pagination (WHERE id < :lastId ORDER BY id DESC LIMIT 12), measured and explained in database part 3. For a product list with page numbers OFFSET is fine, since hardly anyone clicks through to page 500.

Read in post: Pagination and dynamic filters in Spring
Edge caseJuniorA required @RequestParam int page turns the page into a 400The beginner version declares @RequestParam("page") int page. Clicking a menu link to /admin/product (no ?page=) gives 400 Required parameter 'page' is not present. The quick fix is @RequestParam(defaultValue = "1"), but ?page=abc is still a 400, and ?page=0 or ?page=-5 builds an invalid PageRequest. Taking a Pageable

The beginner version declares @RequestParam("page") int page. Clicking a menu link to /admin/product (no ?page=) gives 400 Required parameter 'page' is not present. The quick fix is @RequestParam(defaultValue = "1"), but ?page=abc is still a 400, and ?page=0 or ?page=-5 builds an invalid PageRequest. Taking a Pageable lets Spring handle it: a missing parameter uses the @PageableDefault, a non-numeric value is ignored. The test pageParamOptionalOneBasedAndCapped sends page=abc and still gets 200.

Read in post: Pagination and dynamic filters in Spring
Edge caseMidDeclaring hibernate-jpamodelgen as a dependency with a hard-coded versionThe beginner version adds hibernate-jpamodelgen:6.4.1.Final to <dependencies with provided scope. A hard-coded version drifts from the Hibernate that Spring Boot manages, and with some IDE setups the processor doesn't run, so Product never appears. Cleaner: declare it in the maven-compiler-plugin's annotationProcessorP

The beginner version adds hibernate-jpamodelgen:6.4.1.Final to <dependencies> with provided scope. A hard-coded version drifts from the Hibernate that Spring Boot manages, and with some IDE setups the processor doesn't run, so Product_ never appears. Cleaner: declare it in the maven-compiler-plugin's annotationProcessorPaths, with the version from ${hibernate.version} supplied by the Boot parent. Since Hibernate 6.3 the new artifact is hibernate-processor; hibernate-jpamodelgen is still published for compatibility.

Read in post: Pagination and dynamic filters in Spring
Edge caseMidParsing price ranges from URL strings with split and parseIntThe beginner version uses slugs like 10-toi-15-trieu and 16-toi-20trieu and cuts the string to get the numbers. An inconsistent slug (a missing dash) is a parse error; the 15–16 million gap is never matched; and anyone can send 1-toi-999999999999-trieu. Treat the slug as a key looked up in an enum: unknown slugs are dr

The beginner version uses slugs like 10-toi-15-trieu and 16-toi-20trieu and cuts the string to get the numbers. An inconsistent slug (a missing dash) is a parse error; the 15–16 million gap is never matched; and anyone can send 1-toi-999999999999-trieu. Treat the slug as a key looked up in an enum: unknown slugs are dropped and the server defines the ranges. URLs stay SEO-friendly, and the input becomes a finite set.

Read in post: Pagination and dynamic filters in Spring
Edge caseMidLIKE '%keyword%' can't use a B-tree indexlower(name) like '%tuf%' has a leading wildcard, so the database can't use a B-tree index on name and scans the table. Fine for a few thousand products; for millions of rows you need a full-text index, trigrams (pgtrgm with GIN, see index types) or Elasticsearch (the indexing post). Also: the lab doesn't escape % and i

lower(name) like '%tuf%' has a leading wildcard, so the database can't use a B-tree index on name and scans the table. Fine for a few thousand products; for millions of rows you need a full-text index, trigrams (pg_trgm with GIN, see index types) or Elasticsearch (the indexing post). Also: the lab doesn't escape % and _ in the keyword, so q=% matches every row. Escape them, or use cb.like(expr, pattern, '\\') with an escaped pattern.

Read in post: Pagination and dynamic filters in Spring
InterviewJuniorWhat are OFFSET and LIMIT? For page 3 with 10 rows per page, what's the OFFSET?

LIMIT is how many rows to return, OFFSET is how many to skip first. Page 3 (1-based), size 10: OFFSET = (3 - 1) × 10 = 20.

In Spring, PageRequest.of(2, 10) (0-based) gives the same result. Add an ORDER BY on a unique column, or the order across pages is undefined.

Read in post: Pagination and dynamic filters in Spring
InterviewJuniorA controller takes @RequestParam int page and a user opens the URL without page. What happens, and how do you fix it?

Spring returns 400 because a required parameter is missing. Fix it by taking a Pageable with @PageableDefault, or at least a defaultValue.

Pageable also deals with non-numeric values, sort and size, and honours one-indexed-parameters and max-page-size.

Read in post: Pagination and dynamic filters in Spring
InterviewMidHow do Page and Slice differ? When do you pick Slice?

Page runs an extra count(*) to know the total rows and pages; Slice fetches size + 1 rows just to know whether there's a next page.

Pick Slice for "load more" or infinite scroll, especially when counting a large table under complex conditions is expensive. Pick Page when the UI needs a page-number bar.

Read in post: Pagination and dynamic filters in Spring
InterviewMidWhy must the sort parameter from the URL be filtered?

Because it picks the ORDER BY column: an unknown column causes a 500, and sorting by a sensitive field helps outsiders probe data.

Spring Data doesn't paste raw sort strings into SQL, but it accepts any entity property. Use an allowlist, map display names (price-asc) to a Sort on the server, and always add a unique column last for a stable order.

Read in post: Pagination and dynamic filters in Spring
InterviewMidWhat is a Specification and how does it differ from a query method?

A Specification is a piece of WHERE built at runtime with the Criteria API; a query method fixes its conditions in the method name at compile time.

With three optional criteria, query methods need eight methods, while Specifications are three small functions combined with allOf, skipping any that are null. Use the metamodel (Product_) so attribute names are checked at compile time.

Read in post: Pagination and dynamic filters in Spring
InterviewMidA user picks two price ranges and two brands. What's the correct SQL condition, and where does it usually go wrong?

factory IN (a, b) AND (price BETWEEN x1 AND y1 OR price >= x2): the price ranges must be parenthesised before being AND-ed with the brands.

Chaining each range with .or() into a series of .and()s easily becomes ... AND r1 OR r2, matching every r2 product regardless of brand. Put the ranges in one Specification returning cb.or(...), then read the SQL in the log to check.

Read in post: Pagination and dynamic filters in Spring
InterviewSeniorThe list page searches names with LIKE and gets slow as the table grows. What do you do?

LIKE '%x%' can't use a B-tree, so move to a tool built for substring search: a trigram index, the database's full-text index, or a search engine; and review the count query and selected columns at the same time.

Measure with EXPLAIN first. Prefix-only search (LIKE 'x%') can use an index. On PostgreSQL, pg_trgm + GIN suits contains-search; ranked, typo-tolerant search calls for Elasticsearch. Also: use Slice if you don't need totals, a projection to skip the @Lob column, and escape % and _ in the keyword.

Read in post: Pagination and dynamic filters in Spring
InterviewSeniorA Specification joins a child table and the page returns duplicates and a wrong total. Why, and how do you fix it?

A 1-n join turns each product into several rows; add query.distinct(true) or rewrite the join as an exists subquery, and avoid fetch joins when paginating.

A collection fetch join plus pagination makes Hibernate page in memory, and the count query derived from the same Specification fails. An exists subquery often plans better than distinct on large tables. Verify with the SQL log and a test with many child rows.

Read in post: Pagination and dynamic filters in Spring
Trade-offSeniorRule hits only alert, or loop back to block transactionsA rule hit through Kafka arrives after the transaction, so on its own it blocks nothing. Alert only keeps the architecture simple and accepts that a fraudster runs a few more seconds. Loop back to block: the action service reads the rule-hit topic and writes a flag fraud:block:{A} to Redis, and the wallet does a single

A rule hit through Kafka arrives after the transaction, so on its own it blocks nothing. Alert only keeps the architecture simple and accepts that a fraudster runs a few more seconds. Loop back to block: the action service reads the rule-hit topic and writes a flag fraud:block:{A} to Redis, and the wallet does a single GET on it before each transaction (under 1 ms), so transaction 101 onwards is blocked. The price is one more synchronous dependency for the wallet, and a fail-open or fail-closed choice when Redis doesn't answer. I loop back to block, failing open for small amounts.

Read in post: Case study
Edge caseMidCounting with INCR means Kafka redelivery over-countsAn at-least-once consumer gets some events again after a crash or rebalance. With INCR, each redelivery adds one: a normal account can cross the threshold. With ZADD and the transactionid as member, adding the same member again only updates its score and the count doesn't change. Picking a naturally idempotent data str

An at-least-once consumer gets some events again after a crash or rebalance. With INCR, each redelivery adds one: a normal account can cross the threshold. With ZADD and the transaction_id as member, adding the same member again only updates its score and the count doesn't change. Picking a naturally idempotent data structure is much cheaper than building a separate dedupe table.

Read in post: Case study
Edge caseSeniorSetting the dedupe flag before sending the rule hit can lose an alertIf the detector succeeds at SET ... NX and then dies before sending the rule hit, reprocessing finds the flag set and skips: the alert is gone for good. The right order is to send the rule hit first (wait for the ack), then set the flag. A crash between the two only produces a duplicate alert, which receivers drop by h

If the detector succeeds at SET ... NX and then dies before sending the rule hit, reprocessing finds the flag set and skips: the alert is gone for good. The right order is to send the rule hit first (wait for the ack), then set the flag. A crash between the two only produces a duplicate alert, which receivers drop by hit_id (rule + account + rounded window). In fraud, a duplicate alert is far cheaper than a missed one.

Read in post: Case study
TILMidKafka retention turns external state into something you can rebuildBecause the rule only looks at the last 5 minutes and the topic keeps 7 days, all of the detector's state is a function of "the last 5 minutes of the log". No Redis backup needed: reset offsets to just before 5 minutes ago (plus the allowed lateness) and read again. That's why I prefer short-lived state derived from a

Because the rule only looks at the last 5 minutes and the topic keeps 7 days, all of the detector's state is a function of "the last 5 minutes of the log". No Redis backup needed: reset offsets to just before 5 minutes ago (plus the allowed lateness) and read again. That's why I prefer short-lived state derived from a log over state nobody can rebuild.

Read in post: Case study
Trade-offSeniorExternal Redis or Kafka Streams local stateKafka Streams (or Flink): no Redis to run, windows and grace periods built in, exactly-once from the transaction topic to the rule-hit topic, state in RocksDB backed by a changelog topic. The price: rebalances must restore state (you need standby replicas), changing rules usually means a redeploy, and count() double co

Kafka Streams (or Flink): no Redis to run, windows and grace periods built in, exactly-once from the transaction topic to the rule-hit topic, state in RocksDB backed by a changelog topic. The price: rebalances must restore state (you need standby replicas), changing rules usually means a redeploy, and count() double counts if the source emits duplicates (dedupe first). Redis: rules change by configuration, state is readable from outside (the wallet checks the flag, the risk team looks things up), the detector is stateless so scaling and recovery are simple. The price: one more system to operate, and a network round trip per event. For a few fixed rules at high volume I lean towards Kafka Streams; for many rules tuned by the risk team, I pick Redis like the slides.

Read in post: Case study
InterviewJuniorWhy use account_id as the transaction topic's key?

So all of an account's transactions land in one partition, keep their order, and only one detector handles that account at a time.

That way no two instances modify one account's state. Load still spreads evenly because there are millions of accounts.

Read in post: Case study
InterviewJuniorHow do fixed and sliding windows differ?

Fixed windows cut time into adjacent buckets (10–10, 10–10); a sliding window always looks back 5 minutes from each event.

Fixed windows miss a burst that straddles two buckets; a sliding window doesn't, at the cost of remembering each transaction.

Read in post: Case study
InterviewMidDoes adding partitions to the transaction topic break the count?

No, because state lives in Redis by account_id, not tied to a partition; whichever consumer gets the key reads the right sorted set.

Counting with Kafka Streams local state is different: state is split by partition, so adding input partitions needs a reset or a repartition. Over-provisioning partitions up front avoids the question anyway.

Read in post: Case study
InterviewMidA consumer crashes and Kafka redelivers events. Is the count wrong?

No, if you count with a sorted set whose member is the transaction_id: adding the same member again doesn't add an entry.

With INCR it would be. The general approach is a naturally idempotent operation, or dedupe by ID before adding.

Read in post: Case study
InterviewMidAn account is over the threshold and crosses it again on every transaction. How do you avoid 1,000 alerts?

Emit one rule hit per account per rule per period using a Redis SET NX PX flag, and have receivers dedupe by hit_id.

Send the rule hit first and set the flag after; the other way round, a crash between the two loses the alert.

Read in post: Case study
InterviewSeniorRedis loses all its data. How does the system recover?

Bring up a new Redis, reset the group's offsets to about 6 minutes ago and read again; the count is idempotent, so replay doesn't over-count.

The detector's state only depends on the last 5 minutes of the log and the topic keeps 7 days, so Redis needs no backup. During replay detection is a few minutes late; existing block flags are separate data that need a backup or a rebuild from the rule-hit topic.

Read in post: Case study
InterviewSeniorWhy count by event time rather than when the consumer processes it?

Because when a consumer lags and then catches up, counting by processing time squeezes 15 minutes of transactions into 5 and raises false alarms.

Event time comes from the commit time in the wallet's DB (one clock source). Add allowed lateness for late events and a metric counting events dropped for being too late.

Read in post: Case study
InterviewSeniorWould you use Kafka Streams instead of Redis?

Possibly: Streams has sliding windows, local state and Kafka-to-Kafka exactly-once built in. I decide by how often rules change and who needs to read the state.

Few fixed rules at high volume: Streams. Many rules tuned by the risk team and a wallet that reads a flag synchronously: Redis. Streams needs standby replicas so rebalances don't wait on long state restores.

Read in post: Case study
Edge caseJuniorJumping to solutions before understanding the problemOpening with "I'll use Kafka and Redis" is a bad signal. You don't yet know whether the system is read-heavy or write-heavy, whether it needs real time, or whether losing a record matters. The course's principle 1: understand the problem first, don't jump to solutions. Two minutes of good questions save twenty minutes

Opening with "I'll use Kafka and Redis" is a bad signal. You don't yet know whether the system is read-heavy or write-heavy, whether it needs real time, or whether losing a record matters. The course's principle 1: understand the problem first, don't jump to solutions. Two minutes of good questions save twenty minutes of drawing the wrong thing.

Read in post: The system design interview
TILMidAvailability and reliability are not the sameAvailability asks "is the system answering?". Reliability asks "is it doing the right thing, even when something fails?". An API that always returns 200 but occasionally charges twice is available but not reliable. For money systems reliability comes first: better to return a 503 than to write a wrong ledger entry.

Availability asks "is the system answering?". Reliability asks "is it doing the right thing, even when something fails?". An API that always returns 200 but occasionally charges twice is available but not reliable. For money systems reliability comes first: better to return a 503 than to write a wrong ledger entry.

Read in post: The system design interview
Trade-offSeniorThe NFR priority order is not fixedThe course suggests a default order: scalability → reliability → (security) → performance → availability, and says it shifts over a product's life. I read it as the order for a growing product, not a law. Money systems, exchanges: reliability and security first. Better to pause matching for a few seconds than to match

The course suggests a default order: scalability → reliability → (security) → performance → availability, and says it shifts over a product's life. I read it as the order for a growing product, not a law.

  • Money systems, exchanges: reliability and security first. Better to pause matching for a few seconds than to match wrongly.
  • Social feed: availability and latency above consistency. Nobody sues over seeing a post a few seconds late.
  • Early-stage startup: speed of shipping and cost above scalability.

The NFR order is what breaks the tie when you're stuck between two options. Stating it out loud is the fastest way to give every later trade-off a reason.

Read in post: The system design interview
Edge caseMidJustifying with "big companies use it""Netflix uses Cassandra so I'll use Cassandra" isn't evidence: their load, team and requirements differ from yours. Evidence is a mechanism: "the data is write-heavy, accessed by key, eventual consistency is fine, so an LSM tree with sequential writes fits better than a B-Tree". If you can't state the mechanism, pick t

"Netflix uses Cassandra so I'll use Cassandra" isn't evidence: their load, team and requirements differ from yours. Evidence is a mechanism: "the data is write-heavy, accessed by key, eventual consistency is fine, so an LSM tree with sequential writes fits better than a B-Tree". If you can't state the mechanism, pick the familiar technology and say that's the reason.

Read in post: The system design interview
InterviewJuniorWhat's the difference between functional and non-functional requirements?

Functional is what the system does (book a room, send a message); non-functional is how well it does it (how fast, what % availability, how much load).

FRs produce the API and the data model. NFRs drive the architecture: whether you need a cache, replicas, sharding or a queue.

Read in post: The system design interview
InterviewJuniorWhat do you do in the first ten minutes of a system design round?

Ask questions to settle at most three FRs, get numbers for the NFRs, state assumptions out loud, and only then estimate.

Example questions: "Who are the main users?", "How many DAU?", "What's the read ratio?", "Do we need real time?", "Is losing data acceptable?".

Read in post: The system design interview
InterviewMidHow do you know which NFR matters most for a system?

Ask two questions: what ruins the user experience, and what blocks the business from growing.

Slow homestay search makes guests leave (performance). A bank that miscalculates loses trust (reliability). A marketplace that can't onboard more merchants can't grow (scalability).

Read in post: The system design interview
InterviewMidAn API always returns 200 but occasionally charges twice. Which NFR is missing?

Reliability, not availability. The system answers, but answers wrong.

The usual fix is an idempotency key on the charge and a unique constraint in the database (see idempotency in distributed systems).

Read in post: The system design interview
InterviewMidHow is architecture different from design?

Architecture is global, hard to change and NFR-driven (architectural style, sync vs async). Design is local to each problem (data structures, algorithms, technology).

A low-level design decision can still force an architecture change, for example discovering that one table needs sharding changes how services are split.

Read in post: The system design interview
InterviewSeniorHow do you show your design is good before writing any code?

Check the necessary conditions (meets FRs, NFRs, constraints, explainable) and the sufficient one (mechanism-level evidence for each choice, found by asking "why" down to the fundamentals).

Add estimates with numbers to point out the bottleneck, and walk through failure scenarios in your head: a node dies, load goes 10×, one key gets too hot.

Read in post: The system design interview
InterviewSeniorThe interviewer gives a very vague prompt: "design Tinder". How do you handle it?

Narrow it: pick three FRs (location feed, swipe and match, paid plan), put chat out of scope, ask for load numbers, and state assumptions.

Then confirm: "I'll focus on the feed and matching and leave chat for later if there's time. Does that work?" Asking for confirmation keeps you both on the same problem.

Read in post: The system design interview
InterviewSeniorWhat's your NFR priority order for an e-wallet, and how does it differ from a social network?

E-wallet: reliability and security first, then availability, scalability, performance. Social network: availability and latency first; consistency only needs to be eventual.

That order drives the trade-offs: the wallet returns an error when unsure, the social network returns slightly stale data.

Read in post: The system design interview
Edge caseMidDrawing the ER diagram before listing the queries gives a schema that is only formally correctA 3NF ER diagram can still fail the product's most important query, like the Q1 feed: no single index can serve it. The list of queries with frequency and latency targets (300 req/s, p95 < 50 ms) is the schema's acceptance criteria and the input for choosing indexes.

A 3NF ER diagram can still fail the product's most important query, like the Q1 feed: no single index can serve it. The list of queries with frequency and latency targets (300 req/s, p95 < 50 ms) is the schema's acceptance criteria and the input for choosing indexes.

Read in post: The data modeling process
Trade-offSeniorStay normalized or add a redundant column for one hot queryStay normalized when the query isn't hot, filter and sort live in the same table, or the source data changes often. Add a redundant column when a hot query filters on table A and sorts on table B: only when both columns share a table can a composite index serve it end to end (PostgreSQL 16, 2 million posts: 63 ms down
  • Stay normalized when the query isn't hot, filter and sort live in the same table, or the source data changes often.
  • Add a redundant column when a hot query filters on table A and sorts on table B: only when both columns share a table can a composite index serve it end to end (PostgreSQL 16, 2 million posts: 63 ms down to 0.07 ms).
  • Safe only if: the source data rarely changes, there is one sync mechanism (same transaction, trigger or event), and a periodic reconciliation job runs.
  • The slides conclude correctly: normalize as the baseline, denormalize in a few measured places.
Read in post: The data modeling process
Edge caseMidReading the count into Java, adding one and saving it back loses updatespost.setCommentCount(post.getCommentCount() + 1); repository.save(post): two requests both read 10, both write 11, one increment is lost. Use SET commentcount = commentcount + 1 so the database locks the row, or @Version so one request fails and retries.

post.setCommentCount(post.getCommentCount() + 1); repository.save(post): two requests both read 10, both write 11, one increment is lost. Use SET comment_count = comment_count + 1 so the database locks the row, or @Version so one request fails and retries.

Read in post: The data modeling process
Edge caseSeniorIn InnoDB, inserting a child row blocks even unrelated UPDATEs of the parent rowInserting or updating a child row with a foreign key makes InnoDB put an S,RECNOTGAP lock (a shared lock on exactly that record, no gap lock, visible in performanceschema.datalocks) on the parent record until the transaction ends. Every UPDATE of the parent row, even of an unrelated column like lastloginat, waits (MySQ

Inserting or updating a child row with a foreign key makes InnoDB put an S,REC_NOT_GAP lock (a shared lock on exactly that record, no gap lock, visible in performance_schema.data_locks) on the parent record until the transaction ends. Every UPDATE of the parent row, even of an unrelated column like last_login_at, waits (MySQL 8.4: error 1205 after innodb_lock_wait_timeout). A hot parent (a merchant receiving thousands of orders a minute) becomes a source of lock waits and deadlocks. PostgreSQL only takes FOR KEY SHARE, which conflicts only with re-keying or deleting.

Read in post: The data modeling process
Trade-offSeniorKeep the foreign key constraint or check in the applicationKeep the FK when the tables share a database and are owned by one service: no orphans even with bugs, manual scripts or races. Index the foreign key column (PostgreSQL doesn't create one for you). Drop the FK when parent and child live in different shards, databases or services (an FK is impossible), when you need onli
  • Keep the FK when the tables share a database and are owned by one service: no orphans even with bugs, manual scripts or races. Index the foreign key column (PostgreSQL doesn't create one for you).
  • Drop the FK when parent and child live in different shards, databases or services (an FK is impossible), when you need online migrations with gh-ost (which doesn't support tables with FKs), or when InnoDB's parent-row lock causes measured contention.
  • If you drop it, compensate: a locking check (SELECT ... FOR SHARE), or a periodic orphan-finding job with an alert when the count isn't 0.
  • Be careful with ON DELETE CASCADE: one delete can drag millions of rows into one transaction; for large data prefer soft delete or batched deletes (deleting old data safely).
Read in post: The data modeling process
TILMidSpring Data auditing needs both @EnableJpaAuditing and an AuditorAware@CreatedDate and @LastModifiedDate are only filled when the entity has @EntityListeners(AuditingEntityListener.class) and the app enables @EnableJpaAuditing; @CreatedBy and @LastModifiedBy also need an AuditorAware<T bean. Miss a piece and the column silently stays null until a database NOT NULL catches it. Auditing on

@CreatedDate and @LastModifiedDate are only filled when the entity has @EntityListeners(AuditingEntityListener.class) and the app enables @EnableJpaAuditing; @CreatedBy and @LastModifiedBy also need an AuditorAware<T> bean. Miss a piece and the column silently stays null until a database NOT NULL catches it. Auditing only runs through the EntityManager: hand-written UPDATEs (@Modifying @Query, JDBC) don't touch updated_at, so a database trigger is a good safety net.

Read in post: The data modeling process
InterviewJuniorHow does an entity differ from a config table?

An entity has an identity and a lifecycle; a config table is rarely changing lookup data with no meaningful lifecycle.

Entities usually have a status that changes over time (orders, posts). Config tables (countries, currencies) suit natural keys and application-level caching.

Read in post: The data modeling process
InterviewJuniorHow does a foreign key differ from a reference column?

The reference column is data (it stores the parent's id); the foreign key is a database constraint on that column guaranteeing it points to an existing parent row.

Drop the constraint and the column stays, and still needs an index if queries follow it.

Read in post: The data modeling process
InterviewJuniorWhat primary key does a relation table for an N–M relationship usually have?

A composite key of the two foreign keys, e.g. post_tag (post_id, tag_id).

It prevents duplicate pairs and serves queries on the leading column. Add an index on (tag_id, post_id) if you query the other direction. Usually only created_at is added, not the full table template.

Read in post: The data modeling process
InterviewMidHow do you start designing the schema for a new feature?

I write down the main queries and writes first, each with a frequency and a latency target.

Then I group fields into entities, classify the tables (entity, relation, support, config), normalize as the baseline, and check each hot query for an index that can serve it; where none can, I consider deliberate denormalization.

Read in post: The data modeling process
InterviewMidIn a 1–1 relationship between an order and its payment transaction, which table holds the reference column?

The table created later, i.e. payment_txn.order_id, with UNIQUE to keep it 1–1.

When the order is created there is no transaction yet, so no insert-then-update. New transaction kinds (a donation with no order) don't require changing orders.

Read in post: The data modeling process
InterviewMidWhy is read-modify-write of a counter column in Java wrong?

Two requests read the same value, both add one and both write, so one increment is lost (a lost update).

Fix it with an atomic SET count = count + 1 in SQL, or optimistic locking with @Version so one side fails and retries.

Read in post: The data modeling process
InterviewMidWhen do you add a redundant column to a normalized table?

When a hot query filters on one table and sorts on another, so no composite index can serve it end to end.

Example: a feed by the author's country. Adding author_country to post with an index on (author_country, created_at) cut 125,000 buffers to 23. Conditions: the source data rarely changes, there is one sync mechanism, and a reconciliation job.

Read in post: The data modeling process
InterviewSeniorWould you drop foreign key constraints?

By default I keep them when the tables share a database and are owned by one service: the check is one index lookup, and in exchange there are never orphan rows.

I drop them across shards or services, when I need a migration tool like gh-ost, or when InnoDB's shared lock on the parent row causes measured contention. Then I add a locking check or an orphan-finding job; a non-locking SELECT then INSERT has a race condition.

Read in post: The data modeling process
InterviewSeniorWhat does inserting a child row with a foreign key do to the parent row?

InnoDB puts a shared lock on the parent record until the transaction ends, blocking every UPDATE of the parent row; PostgreSQL only takes FOR KEY SHARE.

FOR KEY SHARE blocks deletes and key changes but not updates of ordinary columns. With a hot parent row on MySQL, this is a source of lock waits and deadlocks.

Read in post: The data modeling process
InterviewSeniorShould a ledger table get the full table template?

No. A ledger is append-only: mistakes are fixed with a reversing entry, not an edit.

It only needs created_at and created_by; drop updated_* and version because they imply edits are allowed. Turn the convention into a constraint with a trigger blocking UPDATE and DELETE, and REVOKE those privileges from the application role.

Read in post: The data modeling process
Trade-offMidWhy token bucket is the usual pickSmall memory (2 numbers per key) and O(1) per request, so it scales to tens of millions of keys. Requests don't wait as with a leaky bucket, so latency stays low. It allows bounded bursts (capacity), which matches real user behavior (open the app, fire 5 requests at once). Two easy parameters: rate is the average speed
  • Small memory (2 numbers per key) and O(1) per request, so it scales to tens of millions of keys.
  • Requests don't wait as with a leaky bucket, so latency stays low.
  • It allows bounded bursts (capacity), which matches real user behavior (open the app, fire 5 requests at once).
  • Two easy parameters: rate is the average speed, capacity is the maximum burst.
  • When the backend needs perfectly even output, pick a leaky bucket instead.
Read in post: Rate limiting
Edge caseMidThinking a sliding window stops burstsEvery window-based algorithm only limits the total inside the window: 10 requests/minute can still all arrive in the first 100 ms. If the backend can't take short bursts, add a second limit at a smaller scale (say 3 requests/second) or use a leaky bucket.

Every window-based algorithm only limits the total inside the window: 10 requests/minute can still all arrive in the first 100 ms. If the backend can't take short bursts, add a second limit at a smaller scale (say 3 requests/second) or use a leaky bucket.

Read in post: Rate limiting
Edge caseSeniorWhat the rate limiter does when Redis diesDecide in advance, based on what the limit is for: Fail-open (let everything through): fits when the limit is about fairness or light abuse protection; the system doesn't go down because of Redis. Fail-closed (block everything): fits when the limit protects something expensive or dangerous (sending SMS OTPs, moving mon

Decide in advance, based on what the limit is for:

  • Fail-open (let everything through): fits when the limit is about fairness or light abuse protection; the system doesn't go down because of Redis.
  • Fail-closed (block everything): fits when the limit protects something expensive or dangerous (sending SMS OTPs, moving money).
  • Usually combined: a short Redis timeout (5–10 ms), a circuit breaker, and a fallback to an in-memory local limit when Redis errors. See timeouts, retries and circuit breakers.
Read in post: Rate limiting
InterviewMidWhat's wrong with a fixed window?

Bursts at the boundary: a client piles requests at the end of one window and the start of the next, and gets nearly double the limit through in a very short time.

A sliding window counter or a token bucket reduces the problem while still needing only a few numbers per key.

Read in post: Rate limiting
InterviewMidHow do token bucket and leaky bucket differ?

A token bucket limits the average rate but allows bursts up to capacity and never makes requests wait; a leaky bucket queues requests and drains them at a fixed rate, giving even output but higher latency.

Token bucket suits user-facing APIs. Leaky bucket suits a backend that can only take a fixed rate, for example calling a partner limited to 100 requests/s.

Read in post: Rate limiting
InterviewMidWhy is building a rate limiter with GET then SET on Redis wrong?

Two instances read the same old value, both decide to allow, and both write, so more requests get through than the limit (a read-modify-write race condition).

Use one atomic command (INCR for a fixed window) or a Lua script for multi-step algorithms; WATCH/MULTI also works but needs retries.

Read in post: Rate limiting
InterviewSeniorDesign a distributed rate limiter for an API gateway at 200K requests/s.

A token bucket per API key, state in Redis Cluster, read-compute-write in one Lua script; add token batches and local limits to depend less on Redis.

Estimate: 200K scripts/s needs 3–4 masters. Quota config is cached in the gateway. When Redis fails: short timeout, circuit breaker, fall back to local limits; choose fail-open/closed per endpoint. Return 429 with Retry-After, and measure blocked requests.

Read in post: Rate limiting
InterviewSeniorHow do you rate limit across several regions?

Don't sync across regions on every request (too slow); split the quota per region, or let each region limit on its own and sync counters asynchronously, accepting a small drift.

If the quota is a billing contract, reconcile precisely from usage logs afterwards, not with the real-time limiter.

Read in post: Rate limiting
InterviewSeniorA slow Redis rate limiter is pushing up p99 for the whole API. What do you do?

Make fewer calls and cap the wait: fetch tokens in batches, a timeout of a few ms, a circuit breaker, and a local limit when Redis doesn't answer in time.

Also check: hot keys (one API key carrying most of the load lands on one slot), heavy scripts, the network between gateway and Redis. For a hot key, give it a local limit or split its bucket.

Read in post: Rate limiting
Trade-offMidRedis or Memcached for cachingMemcached: a byte-string cache with small values, when you want many cores on one machine and can accept losing everything on restart. Simple, with little to misconfigure. Redis: when you need data structures (counters, rankings, queues, sets), replicas and failover, persistence, or one tool for many jobs. The price is
  • Memcached: a byte-string cache with small values, when you want many cores on one machine and can accept losing everything on restart. Simple, with little to misconfigure.
  • Redis: when you need data structures (counters, rankings, queues, sets), replicas and failover, persistence, or one tool for many jobs. The price is understanding eviction, persistence and cluster mode.
  • Java/Spring teams usually pick Redis because Spring Data Redis, Spring Cache and Redisson are ready to use. The usual reason to choose Memcached today is a legacy system that already uses it.
Read in post: Redis internals
Edge caseMidThe slides say "Memcached has no cluster" and "Redis gets slow past 16 GB": both need correctingMemcached has no server-side cluster, but it has long been spread across many nodes with client-side consistent hashing; Facebook runs it on thousands of servers. "No cluster" only means no built-in replication or failover, not "can't scale". 16 GB is not a hard limit in Redis either. An oversized instance hurts elsewh

Memcached has no server-side cluster, but it has long been spread across many nodes with client-side consistent hashing; Facebook runs it on thousands of servers. "No cluster" only means no built-in replication or failover, not "can't scale".

16 GB is not a hard limit in Redis either. An oversized instance hurts elsewhere:

  • fork() for snapshots and AOF rewrites costs time and copy-on-write memory (pages copied when written).
  • Restarting or syncing a new replica takes many minutes.
  • A single command thread is still a single thread.

That is why people split data into several moderately sized shards, not because RAM crosses some magic number.

Read in post: Redis internals
Edge caseMidAn O(N) command on a large collection blocks all of Redis, not just the client that called itKEYS , SMEMBERS on a million-member set, HGETALL on a giant hash, SUNION of two large sets, LRANGE 0 -1, a synchronous FLUSHALL, or a Lua script with a long loop all run on the one and only thread. Meanwhile every other request (even a tiny GET) waits, the p99 of the whole system spikes and clients may time out en mass

KEYS *, SMEMBERS on a million-member set, HGETALL on a giant hash, SUNION of two large sets, LRANGE 0 -1, a synchronous FLUSHALL, or a Lua script with a long loop all run on the one and only thread. Meanwhile every other request (even a tiny GET) waits, the p99 of the whole system spikes and clients may time out en masse.

How to avoid it: iterate in chunks with SCAN/HSCAN/SSCAN, block dangerous commands with ACLs (-@dangerous), and watch SLOWLOG GET and LATENCY DOCTOR.

Read in post: Redis internals
TILSeniorRedis 7.4 changed its license, and Valkey was bornIn March 2024, starting with 7.4, Redis moved from BSD to a dual RSALv2/SSPLv1 license, which is no longer open source by the OSI definition. The Linux Foundation, together with AWS, Google and many other companies, forked 7.2.4 as Valkey (BSD). Redis 8 (2025) added AGPLv3 as an option. Ordinary users are barely affect

In March 2024, starting with 7.4, Redis moved from BSD to a dual RSALv2/SSPLv1 license, which is no longer open source by the OSI definition. The Linux Foundation, together with AWS, Google and many other companies, forked 7.2.4 as Valkey (BSD). Redis 8 (2025) added AGPLv3 as an option.

Ordinary users are barely affected. But when you choose a managed service (ElastiCache, Memorystore) or ship Redis inside a product, the license is a real question, and senior interviews sometimes ask about it to see whether you follow the ecosystem.

Read in post: Redis internals
Edge caseMidOne field longer than 64 bytes converts the whole hash to a hashtableThe listpack threshold has two conditions: the number of elements and the length of each value. A single 65-byte field (a long description, a small JSON blob) converts the whole hash to hashtable, and it never goes back to listpack on its own, even if you delete that field. If your capacity estimate relies on "small ha

The listpack threshold has two conditions: the number of elements and the length of each value. A single 65-byte field (a long description, a small JSON blob) converts the whole hash to hashtable, and it never goes back to listpack on its own, even if you delete that field.

If your capacity estimate relies on "small hashes are compact", verify it with OBJECT ENCODING and MEMORY USAGE on real data, and don't put long values into hashes you use to save memory.

Read in post: Redis internals
Trade-offSeniorSkiplist or balanced tree for ordered dataSkiplist: short implementation, insert/delete only touch local pointers (easy to make lock-free; Java has ConcurrentSkipListMap), natural range scans. The downside: complexity is a probabilistic expectation, not a hard guarantee, and each node carries many pointers. Balanced tree (red-black, AVL): a hard O(log N) guara
  • Skiplist: short implementation, insert/delete only touch local pointers (easy to make lock-free; Java has ConcurrentSkipListMap), natural range scans. The downside: complexity is a probabilistic expectation, not a hard guarantee, and each node carries many pointers.
  • Balanced tree (red-black, AVL): a hard O(log N) guarantee and fewer pointers, but rotations are complex and hard to make concurrent.
  • B-tree: wins when data lives on disk or when you want good cache-line use (many keys per node), which is why databases use B+trees for indexes.
  • Redis picked a skiplist for its simplicity and because it needs rank by position; Java picked a red-black tree for TreeMap and a skiplist for the concurrent version.
Read in post: Redis internals
Edge caseMidThe slides say "expiring keys are stored in a ZSET" and "lazy expiration is asynchronous": neither is true for RedisRedis stores expiry times in a dict (expires), not a sorted set. The real change in Redis 7.0 is that the active cycle no longer samples purely at random but walks the buckets of expires with a cursor, so no region is skipped. A structure ordered by expiry time (ebuckets) only exists since 7.4, for per-field TTLs in ha

Redis stores expiry times in a dict (expires), not a sorted set. The real change in Redis 7.0 is that the active cycle no longer samples purely at random but walks the buckets of expires with a cursor, so no region is skipped. A structure ordered by expiry time (ebuckets) only exists since 7.4, for per-field TTLs in hashes (HEXPIRE).

Lazy expiration is synchronous on the main thread by default; it only becomes asynchronous with lazyfree-lazy-expire yes (no by default in 7.4). For large values, enable lazyfree so memory is freed on a background thread.

Read in post: Redis internals
Edge caseMidMany keys with the same TTL expiring at once make the expire cycle eat CPU and raise latencyLoad 1 million keys at midnight with the same EX 3600 and at 1 a.m. they all expire together. The active cycle sees more than 25% of each sample expired, so it runs continuously up to its time limit; every DEL generates a replication command and memory may be freed synchronously. Latency rises exactly when the cache is

Load 1 million keys at midnight with the same EX 3600 and at 1 a.m. they all expire together. The active cycle sees more than 25% of each sample expired, so it runs continuously up to its time limit; every DEL generates a replication command and memory may be freed synchronously. Latency rises exactly when the cache is empty and the database is flooded (a cache avalanche).

The fix: spread TTLs with jitter (3600 + random(0..300)) and enable lazyfree-lazy-expire. See also the cache failures post.

Read in post: Redis internals
Trade-offMidChoose maxmemory-policy based on the instance's rolePure cache: allkeys-lru (access driven by recency) or allkeys-lfu (a long-lived set of popular keys, or frequent scans). Losing a key is just a cache miss. Redis holding data that must not be lost (sessions, locks, queues, rate-limit counters): noeviction plus memory monitoring. A clear write error beats silently losin
  • Pure cache: allkeys-lru (access driven by recency) or allkeys-lfu (a long-lived set of popular keys, or frequent scans). Losing a key is just a cache miss.
  • Redis holding data that must not be lost (sessions, locks, queues, rate-limit counters): noeviction plus memory monitoring. A clear write error beats silently losing a lock or a job.
  • Mixing both on one instance: avoid it. If you must, use volatile-lru and make sure every cache key has a TTL and the data keys don't. Fragile, because one piece of code that forgets the TTL breaks it.
  • With persistence on, set maxmemory about 25–40% below the machine's RAM to leave room for copy-on-write during fork().
Read in post: Redis internals
InterviewJuniorWhat is Redis and what is it typically used for?

An in-memory key-value store whose values have types (string, list, hash, set, sorted set, stream...) with commands that run on the server.

It is used as a cache, for session storage, counters and rate limiting, leaderboards, lightweight queues and distributed locks. It has persistence and replication, but it usually isn't the primary store for critical data.

Read in post: Redis internals
InterviewJuniorWhy is Redis fast even though it is single-threaded?

Because the bottleneck is the network and memory, not the CPU: the data is in RAM, so each command costs only a few hundred nanoseconds of CPU.

  • One thread means no locks and no context switches, and every command is naturally atomic.
  • I/O multiplexing (epoll) lets one thread serve tens of thousands of connections.
  • The data structures are optimised: listpack for small collections, skiplists, a hash table that rehashes incrementally.
Read in post: Redis internals
InterviewJuniorHow do key TTLs work? Is an expired key deleted immediately?

Not immediately: Redis records the expiry time in the expires dict, then deletes keys lazily on read or actively with a sampling cycle.

Lazy: a command touches the key, finds it past its expiry and deletes it. Active: a cycle running 10 times per second samples keys with a TTL, deletes the expired ones, and repeats if more than 25% of the sample had expired. Readers never see an expired key, but its memory may not be freed right away.

Read in post: Redis internals
InterviewMidIs Redis 6 and later still single-threaded?

Command execution is still single-threaded; only socket I/O, background jobs and persistence run elsewhere.

Background threads for closing files, fsync and freeing memory (lazyfree) existed before version 6. Version 6 added optional io-threads (off by default) to read/parse requests and write replies in parallel. Persistence uses child processes via fork(), not threads. To use multiple cores for running commands, run several instances or use Cluster.

Read in post: Redis internals
InterviewMidWhat is the encoding of a Redis hash, and why does it matter?

A small hash (by default ≤ 512 fields in 7.4, each value ≤ 64 bytes) is a listpack; past the threshold it becomes a hashtable and uses 5–6 times more memory.

A listpack is a contiguous byte array, scanned linearly but very compact. I measured 5 KB → 28 KB when adding the 513th field, and the hash never converts back. Knowing this lets you group small keys into hashes to save memory and avoid putting long values into hashes.

Read in post: Redis internals
InterviewMidWhy is KEYS * banned in production? What do you use instead?

Because KEYS walks the whole keyspace in O(N) on the single command thread and can block Redis for seconds. Use SCAN instead.

SCAN with MATCH and COUNT iterates with a cursor, a little at a time; you accept that you may see duplicates or miss keys that change during the scan. Even better is a design that never needs to find keys by pattern (keep an index in a set).

Read in post: Redis internals
InterviewMidWhat happens when Redis runs out of memory?

It depends on maxmemory-policy; the default noeviction rejects writes with an OOM error while reads keep working.

With allkeys-lru/lfu, Redis evicts keys using approximate (sampled) LRU/LFU; with volatile-*, it only evicts keys that have a TTL. A cache should use allkeys-*; an instance holding data that must not be lost (locks, queues) should use noeviction and be kept separate.

Read in post: Redis internals
InterviewSeniorDesign Redis usage to keep p99 latency consistently low. What do you pay attention to?

Never let anything block the command thread: no O(N) commands, no big keys, no mass expiry, and fast fork().

  • Use SCAN, cap collection sizes, enforce with ACLs; use UNLINK/lazyfree for large keys.
  • Spread TTLs; keep instances moderately sized so fork() is fast, disable THP, leave RAM for copy-on-write; AOF everysec on a dedicated disk.
  • Pipelining/MGET instead of many round-trips; short client timeouts and a sensible pool.
  • Monitor SLOWLOG, LATENCY DOCTOR, latest_fork_usec, expired_keys, evicted_keys and mem_fragmentation_ratio.
Read in post: Redis internals
InterviewSeniorWhy do sorted sets use a skiplist instead of a balanced tree?

Because a skiplist is simpler with equivalent complexity (expected O(log N)), natural range scans and easy rank computation.

Insert/delete only change local pointers, a range scan just walks forward on the bottom level, and a "span" on each link gives you rank in O(log N). The sorted set also keeps a dict so ZSCORE is O(1). Small sets (≤ 128 members) use a listpack to stay compact.

Read in post: Redis internals
InterviewSeniorCan a replica read a key that has already expired? When is the memory on the replica freed?

No: since Redis 3.2 a replica returns nil for an expired key. But the memory is only freed when the master sends a DEL.

The replica doesn't delete it on its own; it waits for the master to generate a DEL (when the master expires the key lazily or actively) through the replication stream. So replica memory can be slightly higher than the master's, and if the clocks between machines drift a lot, results can differ.

Read in post: Redis internals
Trade-offMidStoring an object as a hash or as a JSON stringHash: when you often read or update individual fields (C1, C2), several writers change different fields, or you need counters on a field (HINCRBY). Small hashes are also more compact thanks to listpack. Limits: only one level, values are strings, no nested objects. JSON string: when you always read/write the whole obje
  • Hash: when you often read or update individual fields (C1, C2), several writers change different fields, or you need counters on a field (HINCRBY). Small hashes are also more compact thanks to listpack. Limits: only one level, values are strings, no nested objects.
  • JSON string: when you always read/write the whole object (C3 dominates), the object is deeply nested, or it is a cached copy of an already serialized response. A single SET ... EX writes and sets the TTL atomically.
  • RedisJSON (a module, included in Redis Stack and Redis 8): stores structured JSON, JSON.SET user:1 $.age 34 updates one path, JSON.GET user:1 $.username reads one. The best of both, at the cost of depending on a module.
  • For the three needs above, pick a hash; if C3 made up 99% of calls and the object were nested, pick JSON.
Read in post: Redis
Edge caseMidCaching an object as JSON and then updating one field with read-modify-write loses updatesGET → parse → change age → SET is not atomic. Two instances changing two different fields (one age, the other email) overwrite each other (a lost update), and the bug only shows up under load. If it is a cache: don't update it, delete the key after writing to the database so the next read reloads it (see cache-aside).

GET → parse → change age → SET is not atomic. Two instances changing two different fields (one age, the other email) overwrite each other (a lost update), and the bug only shows up under load.

  • If it is a cache: don't update it, delete the key after writing to the database so the next read reloads it (see cache-aside).
  • If Redis is the primary store: a hash with a per-field HSET, WATCH/MULTI/EXEC, or a Lua script so the read-modify-write runs atomically on the server.
Read in post: Redis
Edge caseMidINCR followed by a separate EXPIRE can create a key that never expiresIf the app dies or loses its connection between INCR and EXPIRE, the counter key lives forever without a TTL. A per-minute rate limiter then blocks the user permanently once they hit 100; with per-day keys, memory slowly leaks. Three atomic options: Send both inside one MULTI/EXEC (or a transactional pipeline). A Lua s

If the app dies or loses its connection between INCR and EXPIRE, the counter key lives forever without a TTL. A per-minute rate limiter then blocks the user permanently once they hit 100; with per-day keys, memory slowly leaks. Three atomic options:

  • Send both inside one MULTI/EXEC (or a transactional pipeline).
  • A Lua script: local c = redis.call('INCR', KEYS[1]) if c == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end return c.
  • Since Redis 7: EXPIRE key ttl NX (set only if there is no TTL yet); sending it in the same transaction is enough.
Read in post: Redis
Edge caseMidCrashing right after BRPOP loses the message foreverBRPOP removes the element from the list before the app processes it. If the instance is killed, redeployed or runs out of memory in between, the job vanishes and nobody knows. The classic fix is a reliable queue: BLMOVE queue processing RIGHT LEFT atomically moves the element into a processing list, and you only LREM p

BRPOP removes the element from the list before the app processes it. If the instance is killed, redeployed or runs out of memory in between, the job vanishes and nobody knows.

The classic fix is a reliable queue: BLMOVE queue processing RIGHT LEFT atomically moves the element into a processing list, and you only LREM processing 1 <job> after processing succeeds. A cleanup job pushes back elements that have sat in processing too long. But that is reimplementing half a message broker; since Redis 5, use a Stream instead.

Read in post: Redis
Trade-offMidA list, a Stream or a real message brokerList: a simple queue with one group of consumers, where losing a few jobs on a crash is fine (resending a marketing email). The lightest option. Stream: you need acks, several consumer groups, replaying recent history, at moderate volume, and you already run Redis. Limits: the data lives in RAM (you must XTRIM/MAXLEN),
  • List: a simple queue with one group of consumers, where losing a few jobs on a crash is fine (resending a marketing email). The lightest option.
  • Stream: you need acks, several consumer groups, replaying recent history, at moderate volume, and you already run Redis. Limits: the data lives in RAM (you must XTRIM/MAXLEN), and durability is only as good as Redis's persistence and asynchronous replication.
  • Kafka, RabbitMQ: high volume, long retention on disk, acknowledged messages are never lost, and an ecosystem (connectors, schema registry). See choosing a message broker.
Read in post: Redis
Edge caseMidSINTER on two follower sets with a million members blocks Redis for everyoneComputing "mutual friends" for a celebrity account with SINTER runs on the single command thread, and the result (possibly hundreds of thousands of members) still has to go over the network. Meanwhile every other small GET waits. Only count, with SINTERCARD ... LIMIT. Cap the input (only the 1,000 most recent followers

Computing "mutual friends" for a celebrity account with SINTER runs on the single command thread, and the result (possibly hundreds of thousands of members) still has to go over the network. Meanwhile every other small GET waits.

  • Only count, with SINTERCARD ... LIMIT.
  • Cap the input (only the 1,000 most recent followers).
  • Run it on a replica dedicated to analytics, or precompute and cache the result.
  • For estimates (counting millions of unique users): HyperLogLog, 12 KB for any size, 0.81% error.
Read in post: Redis
Edge caseMidOn equal scores a ZSET orders by name, and packing a timestamp into the score can exceed double precisionIf you want "on equal points, whoever got there first ranks higher", you have to encode both into the score, for example score = points × 10^10 + (9999999999 − epochSecond). But the score is a double, which only represents integers exactly up to 2⁵³ ≈ 9 × 10¹⁵. This formula is only correct while points stay below rough

If you want "on equal points, whoever got there first ranks higher", you have to encode both into the score, for example score = points × 10^10 + (9_999_999_999 − epochSecond).

But the score is a double, which only represents integers exactly up to 2⁵³ ≈ 9 × 10¹⁵. This formula is only correct while points stay below roughly 900,000; beyond that, two different players can be rounded to the same score.

What to do: work out the points limit up front, use a coarser time unit, or keep the tie-break in the app (fetch a few extra members around the boundary and re-sort them by a timestamp stored in a hash).

Read in post: Redis
Trade-offSeniorDelay queue: a Redis ZSET, a database scan or a broker with delaysDatabase scan (SELECT ... FOR UPDATE SKIP LOCKED on an (status, expiresat) index): one source of truth, nothing lost, enough for a few thousand jobs per minute. Choose this first if the load allows it. ZSET: low latency, light on the database, work naturally shared between instances. You need atomic claiming, a visibil
  • Database scan (SELECT ... FOR UPDATE SKIP LOCKED on an (status, expires_at) index): one source of truth, nothing lost, enough for a few thousand jobs per minute. Choose this first if the load allows it.
  • ZSET: low latency, light on the database, work naturally shared between instances. You need atomic claiming, a visibility timeout, an idempotent handler, and an infrequent database scan as a safety net because Redis can lose data.
  • A broker with delays (RabbitMQ delayed messages, SQS, Pulsar): acks and retries built in; more infrastructure, and cancelling an already scheduled message is often hard (so the handler still has to check the state).
  • For the ride-hailing problem, I'd choose a ZSET + UPDATE ... WHERE status = 'WAITING' + a database scan every 5 minutes as the safety net.
Read in post: Redis
Edge caseMidReading and then deleting from a ZSET in two separate commands makes several workers process the same itemsZRANGEBYSCORE followed by a ZREM whose result you don't check is check-then-act (checking, then acting, in two separate steps). A test with 4 workers and 2,000 elements produced 784 elements processed more than once. Claim atomically: a Lua script that reads and deletes in one command, or only process the elements for

ZRANGEBYSCORE followed by a ZREM whose result you don't check is check-then-act (checking, then acting, in two separate steps). A test with 4 workers and 2,000 elements produced 784 elements processed more than once. Claim atomically: a Lua script that reads and deletes in one command, or only process the elements for which your own ZREM returned 1.

Read in post: Redis
InterviewJuniorName Redis's main data types and one use for each.

Five main types: String, List, Hash, Set, Sorted set; each has its own commands that run atomically on the server.

  • String: caching JSON, counters, locks.
  • List: recent-items lists, simple queues.
  • Hash: objects by field, shopping carts.
  • Set: likes, deduplication, mutual friends.
  • Sorted set: leaderboards, delay queues.

There are also Streams (queues with acks and consumer groups), Bitmaps, HyperLogLog and Geo.

Read in post: Redis
InterviewJuniorHow do you build a shopping cart with Redis?

Each cart is a hash cart:{userId} with product IDs as fields and quantities as values.

HSET to add, HINCRBY to increase, HDEL to remove, HGETALL to fetch the whole cart, HLEN to count lines. Every operation is a single atomic command. Put a TTL on abandoned carts and don't store prices in the cart.

Read in post: Redis
InterviewMidDo you store a user object as a hash or as a JSON string?

A hash if you often read/update individual fields; a JSON string if you always read/write the whole object.

With a hash, an HSET on one field is atomic, several writers changing different fields cause no lost updates, and small hashes are more compact. A JSON string fits when the object is deeply nested or is a cache of an already serialized response. Updating JSON with read-modify-write needs Lua or WATCH; RedisJSON is a third option.

Read in post: Redis
InterviewMidWhy can using a List as a queue lose messages, and what do you use instead?

Because BRPOP removes the element before the consumer processes it, so a dying consumer loses it; use a Stream instead.

A list has no acks and no multiple consumer groups. You can patch it with BLMOVE into a processing list plus a cleanup job. Better is a Stream: consumer groups, a pending list, XACK, XAUTOCLAIM. For high volume or real durability, use Kafka/RabbitMQ.

Read in post: Redis
InterviewMidHow do you build a delay queue with Redis so multiple workers don't process the same item?

A ZSET with the due time as the score, and workers must claim atomically.

Claim with a Lua script doing ZRANGE BYSCORE ... LIMIT and then ZREM in the same call, or only process the elements for which your own ZREM returned 1. Reading and deleting in two separate commands causes duplicates (I measured 784/2,000 with 4 workers). Add a visibility timeout for crashes, and make the handler idempotent with a conditional statement in the database.

Read in post: Redis
InterviewMidHow does a pipeline differ from MULTI/EXEC?

A pipeline cuts round-trips but isn't atomic; MULTI/EXEC is a server-side transaction that runs as one block.

A pipeline is a client-side technique: send many commands in one go without waiting for each reply, so other clients' commands can still interleave. MULTI/EXEC queues the commands and runs them as one uninterrupted block, but nothing is rolled back if one command fails at runtime. They are often combined: send MULTI ... EXEC inside a pipeline.

Read in post: Redis
InterviewSeniorDesign a leaderboard for 50 million players, with the top 100 and each player's rank.

A sorted set for the top, but don't put all 50 million players in one ZSET.

A ZSET with 50 million members is a big key (several GB, on one node, with heavy forks). Keep a ZSET only for the top N (tens of thousands), trimmed periodically. The rank of players outside the top comes from the database, or approximately from the score distribution (counting by score buckets, "you're in the top 12%"). Encode the tie-break into the score while respecting the 2⁵³ limit. Split by season/region so each key stays moderately sized.

Read in post: Redis
InterviewSeniorWhen should you not use Redis for a data problem?

When Redis would be the only source of truth for data that must not be lost.

  • Acknowledged writes must never be lost (money, inventory): Redis replication is asynchronous.
  • The data doesn't fit in RAM at a reasonable cost.
  • You need flexible queries, joins or transactions across many entities.
  • You need to keep messages for a long time and replay them many times (Kafka).

Redis is at its best as an acceleration layer or for temporary state, with the source of truth somewhere else.

Read in post: Redis
InterviewSeniorA ZSET delay queue: what happens if a worker crashes right after claiming?

The element has left the ZSET, so the job is dropped, unless the claim has a visibility timeout.

Instead of deleting it outright, the claim script moves the element into a processing ZSET with the processing deadline as the score. It is deleted only when the work is done; a job returns overdue elements. The handler must be idempotent (a conditional statement on the state) because it may run again. Add an infrequent database scan as a safety net, since Redis can also lose data on failover.

Read in post: Redis
Edge caseSeniorUnlocking with a DEL that doesn't check the owner deletes other clients' locksWith a constant lock value (1) and DEL key as unlock, a client whose lock has expired (a GC pause, a slow query) deletes the lock another client just acquired, and a third client gets in. Use a random token per acquisition; unlock by comparing the token and deleting inside a Lua script (if GET == token then DEL). When

With a constant lock value (1) and DEL key as unlock, a client whose lock has expired (a GC pause, a slow query) deletes the lock another client just acquired, and a third client gets in. Use a random token per acquisition; unlock by comparing the token and deleting inside a Lua script (if GET == token then DEL). When acquiring several keys fails halfway, release only the keys you actually hold.

Read in post: Reviewing a Redis distributed lock
Edge caseMidUnitless long durations in config lead to TTLs that are off by a factor of thousandsttl: 300000 doesn't say seconds or milliseconds, and each layer guesses differently: the sample code multiplies by 1000 twice, turning 5 minutes into 9.5 years. Use java.time.Duration in @ConfigurationProperties (ttl: 30s, max-wait: 2s): Spring Boot converts it, the unit lives in the value itself, and nobody multiplies

ttl: 300000 doesn't say seconds or milliseconds, and each layer guesses differently: the sample code multiplies by 1000 twice, turning 5 minutes into 9.5 years. Use java.time.Duration in @ConfigurationProperties (ttl: 30s, max-wait: 2s): Spring Boot converts it, the unit lives in the value itself, and nobody multiplies by hand. Add @Validated with sane bounds (a TTL between 1 second and a few minutes) so nonsense config fails at startup instead of misbehaving at runtime.

Read in post: Reviewing a Redis distributed lock
Trade-offSeniorMultiple locks: sequential in sorted order or one all-or-nothing Lua scriptSequential in sorted order: works on any topology, keys can live in different slots; but costs N round-trips and holds the first locks longer while waiting for the later ones. All-or-nothing Lua: one round-trip, never holds a partial set; but on Cluster every key must share a slot (the hash tag puts them all on one nod
  • Sequential in sorted order: works on any topology, keys can live in different slots; but costs N round-trips and holds the first locks longer while waiting for the later ones.
  • All-or-nothing Lua: one round-trip, never holds a partial set; but on Cluster every key must share a slot (the hash tag puts them all on one node, which can become a hot key), and a longer script blocks Redis longer.
  • Parallel without order (like the sample code): fast without contention, but holds keys crosswise and livelocks under contention. Don't.
Read in post: Reviewing a Redis distributed lock
Edge caseMidcatch (Exception) { return false; } turns "Redis is down" into "lock is busy"Returning false in both cases leaves the caller unable to react correctly: a busy lock should become a 409 or a later retry; a dead Redis should become a 503, open a circuit breaker or fall back to a database lock. Catching Exception also swallows InterruptedException, losing the interrupt flag so the thread won't stop

Returning false in both cases leaves the caller unable to react correctly: a busy lock should become a 409 or a later retry; a dead Redis should become a 503, open a circuit breaker or fall back to a database lock. Catching Exception also swallows InterruptedException, losing the interrupt flag so the thread won't stop when the app shuts down. Return Optional.empty() for "busy", let infrastructure exceptions propagate, and declare throws InterruptedException (or call Thread.currentThread().interrupt() again).

Read in post: Reviewing a Redis distributed lock
Trade-offSeniorSingle-node Redis lock, Redlock, a Redisson watchdog or fencing tokensSingle node SET NX PX + token: enough for an efficiency lock; loses the lock on failover or on a pause longer than the TTL. Redlock: survives some nodes dying, but costs N independent nodes, depends on clock assumptions, and doesn't protect against a paused client. Redisson (RLock): per-thread tokens, a watchdog that r
  • Single node SET NX PX + token: enough for an efficiency lock; loses the lock on failover or on a pause longer than the TTL.
  • Redlock: survives some nodes dying, but costs N independent nodes, depends on clock assumptions, and doesn't protect against a paused client.
  • Redisson (RLock): per-thread tokens, a watchdog that renews every lockWatchdogTimeout/3 (30 seconds by default) when no lease time is given, reentrancy, and waiting via pub/sub instead of polling. The watchdog lowers the risk of expiry during long work, but if the JVM pauses, so does the watchdog.
  • Fencing tokens at the resource: the only thing that makes a lock correct when leases expire; requires a resource that can check the token (easy for a database, usually impossible for a third-party API).
Read in post: Reviewing a Redis distributed lock
TILJuniorSET NX PX replaced SETNX + EXPIREOld code often does SETNX key 1 followed by EXPIRE key 30: two non-atomic commands, so a client that dies between them leaves a lock that never expires. Since Redis 2.6.12, SET key value NX PX ms does both in one command, and Spring Data Redis's setIfAbsent(key, value, Duration) sends exactly that. Redis 6.2 added SET

Old code often does SETNX key 1 followed by EXPIRE key 30: two non-atomic commands, so a client that dies between them leaves a lock that never expires. Since Redis 2.6.12, SET key value NX PX ms does both in one command, and Spring Data Redis's setIfAbsent(key, value, Duration) sends exactly that. Redis 6.2 added SET ... GET and Redis 7 added EXPIRETIME, both handy when debugging locks.

Read in post: Reviewing a Redis distributed lock
Trade-offSeniorA Redis lock or the database's own mechanismsA conditional statement (UPDATE seat SET holder=? WHERE id=? AND holder IS NULL) or a unique constraint: no lock at all, fastest, and strictly correct. Try this first. Optimistic locking (a version column): for rare conflicts, holds nothing between requests. SELECT ... FOR UPDATE (with ORDER BY to avoid deadlocks, SKIP
  • A conditional statement (UPDATE seat SET holder=? WHERE id=? AND holder IS NULL) or a unique constraint: no lock at all, fastest, and strictly correct. Try this first.
  • Optimistic locking (a version column): for rare conflicts, holds nothing between requests.
  • SELECT ... FOR UPDATE (with ORDER BY to avoid deadlocks, SKIP LOCKED for queues): when you must read and then decide inside one transaction.
  • Advisory locks (pg_advisory_xact_lock(hash) on PostgreSQL, GET_LOCK() on MySQL): named locks without a row, released when the transaction ends (Postgres's _xact variant).
  • A Redis lock: when the work to protect is not inside a database transaction (calling an external API, processing a file, a job running on many pods), or the database is the bottleneck. Add fencing tokens if it must be correct.
  • Details of the database mechanisms: Transactions, isolation levels and locking.
Read in post: Reviewing a Redis distributed lock
Edge caseMidA shared cache name keyed by method name makes same-named methods return each other's data@Cacheable(cacheNames = "localCache", key = "root.methodName") on the findAll() of two repositories produces the same key findAll in the same cache: whichever runs second gets the first one's result, then a ClassCastException somewhere else. Give each kind of data its own cache name and keys that describe the content (

@Cacheable(cacheNames = "localCache", key = "#root.methodName") on the findAll() of two repositories produces the same key findAll in the same cache: whichever runs second gets the first one's result, then a ClassCastException somewhere else. Give each kind of data its own cache name and keys that describe the content ('all', #id). The default SimpleKeyGenerator only uses the parameters, so it can't tell the two methods apart either.

Read in post: Reviewing a Redis distributed lock
InterviewMidHow do you implement a basic, correct Redis distributed lock?

Acquire with SET lock:x <random token> NX PX <ttl>, release with a Lua script that compares the token before DEL.

Acquiring is atomic, only one client wins, and it expires if the client dies. Comparing the token on release means you never delete someone else's lock; extending also compares the token. Never use SETNX followed by a separate EXPIRE.

Read in post: Reviewing a Redis distributed lock
InterviewMidWhat do you watch out for when acquiring several locks at once?

Ordering and all-or-nothing.

Acquire in a fixed sorted order so two requests with overlapping sets can't hold each other's keys (a deadlock, or a livelock with retries); on failure, release only the locks you took. Or use one Lua script that checks and then sets all keys, with a hash tag so the keys share a slot on Cluster.

Read in post: Reviewing a Redis distributed lock
InterviewSeniorIs a Redis lock safe across a Redis failover? What does Redlock solve?

No. Redlock survives some nodes dying, but it can't protect against a client paused for longer than the TTL.

Replication is asynchronous, so the primary can die before the lock reaches the replica; the promoted replica has no lock and a second client takes it. Redlock acquires on a majority of N independent nodes, but relies on assumptions about clocks and delays. For locks that must be correct, you need fencing tokens checked by the resource, or the database's own locking.

Read in post: Reviewing a Redis distributed lock
InterviewSeniorWhat is a fencing token?

An increasing number issued with every lock acquisition; the resource rejects any write carrying a number lower than the highest it has seen.

Sources: an INCR in Redis, or a ZooKeeper/etcd version. Example: UPDATE ... SET fence = :t WHERE id = :id AND fence < :t. A stale client that wakes up after losing the lock gets rejected. It turns an "efficiency" lock into a "correctness" lock, provided the resource can check the token.

Read in post: Reviewing a Redis distributed lock
InterviewSeniorThe work in the critical section may run longer than the TTL. How do you handle it?

First make the critical section shorter; if you can't, renew with a watchdog and add a fencing token.

  • Move external calls out of the critical section, and put a timeout on every I/O inside.
  • Renew periodically with a token-checking script (a watchdog like Redisson's, every third of the TTL), and abort if renewal fails.
  • Add a fencing token, because the watchdog can't help when the whole JVM pauses.
  • On release, log when the script returns 0 (the lock had expired): a sign the critical section may have overlapped.
Read in post: Reviewing a Redis distributed lock
InterviewSeniorWhen do you use the database's locks instead of Redis?

When the protected resource is a database row; Redis locks are for work outside a database transaction, such as calling an external API or a job running on many pods.

In order of preference: a conditional statement or a unique constraint (no lock needed), optimistic locking with a version, SELECT ... FOR UPDATE with ORDER BY, and advisory locks like pg_advisory_xact_lock. Database locks live inside the transaction, are released on commit, rollback or a dropped connection, and never expire halfway.

Read in post: Reviewing a Redis distributed lock
InterviewSeniorYou're reviewing a lock function with catch (Exception e) { return false; }. What do you comment?

It returns the same result for "lock busy" and "Redis is down", and it swallows InterruptedException.

The caller can't answer with the right 409 or 503, can't open a circuit breaker, and can't fall back to another mechanism. Losing the interrupt flag means the thread won't stop on shutdown. Suggest Optional.empty() for busy, letting infrastructure exceptions propagate, throws InterruptedException, and separate metrics for each case.

Read in post: Reviewing a Redis distributed lock
Edge caseSeniorfork() on a large instance blocks the main thread, and copy-on-write can trigger the OOM killerfork() copies the page table on the main thread, around 10–20 ms per GB on a virtual machine: a 50 GB instance stalls for hundreds of ms on every BGSAVE or AOF rewrite. While the child writes, every page the parent modifies gets copied; with maxmemory close to the machine's RAM, the OOM killer may kill Redis. Monitor l

fork() copies the page table on the main thread, around 10–20 ms per GB on a virtual machine: a 50 GB instance stalls for hundreds of ms on every BGSAVE or AOF rewrite. While the child writes, every page the parent modifies gets copied; with maxmemory close to the machine's RAM, the OOM killer may kill Redis.

  • Monitor latest_fork_usec in INFO persistence.
  • Disable Transparent Huge Pages (they make copy-on-write copy whole 2 MB pages).
  • Leave 30–50% of RAM free and keep each instance moderately sized (a few tens of GB or less).
Read in post: Redis
Edge caseSeniorA slow disk makes AOF everysec block the main thread, not just lose 1 second of dataWith everysec, fsync runs on a background thread. But if the previous fsync still hasn't finished after 2 seconds (a congested disk, the same disk as an AOF rewrite or a backup), the main thread waits on the next write(), and the log says "Asynchronous AOF fsync is taking too long (disk is busy?)". At that point the la

With everysec, fsync runs on a background thread. But if the previous fsync still hasn't finished after 2 seconds (a congested disk, the same disk as an AOF rewrite or a backup), the main thread waits on the next write(), and the log says "Asynchronous AOF fsync is taking too long (disk is busy?)". At that point the latency of every command spikes.

Put the AOF on a dedicated disk, consider no-appendfsync-on-rewrite yes (accepting more loss while a rewrite is running), and alert on aof_delayed_fsync in INFO persistence.

Read in post: Redis
Trade-offSeniorChoose the persistence mode based on Redis's rolePure cache (reload from the database if lost): turn both off (save "", appendonly no), or keep infrequent RDB snapshots so a restart doesn't start with a "cold cache". Losing a few minutes is acceptable (recomputable leaderboards, statistics): RDB. Needs durability (sessions, queues, rate-limit counters, locks): AOF ev
  • Pure cache (reload from the database if lost): turn both off (save "", appendonly no), or keep infrequent RDB snapshots so a restart doesn't start with a "cold cache".
  • Losing a few minutes is acceptable (recomputable leaderboards, statistics): RDB.
  • Needs durability (sessions, queues, rate-limit counters, locks): AOF everysec + hybrid, plus periodic RDB snapshots for off-site backups. At most ~1 second lost when the whole machine dies.
  • Not a single write may be lost: Redis is the wrong tool. Even with appendfsync always, replication is still asynchronous, so a failover can lose data (section 2). Use a database with synchronous commits, or MemoryDB (which writes a multi-AZ log before replying).
Read in post: Redis
Edge caseSeniorThe default 1 MB replication backlog forces a full resync every time the network flapsAt 5 MB/s of writes, a 1 MB backlog only holds 0.2 seconds of commands. A replica that loses its connection for 1 second falls out of the backlog and needs a full sync: the master calls fork(), ships the entire dataset over the network, and the replica drops its old data and reloads. If the commands accumulated during

At 5 MB/s of writes, a 1 MB backlog only holds 0.2 seconds of commands. A replica that loses its connection for 1 second falls out of the backlog and needs a full sync: the master calls fork(), ships the entire dataset over the network, and the replica drops its old data and reloads.

If the commands accumulated during the full sync exceed client-output-buffer-limit replica (256 MB / 64 MB over 60 seconds by default), the master drops the connection and the full sync starts over, never finishing. Set repl-backlog-size = write rate per second × seconds of disconnection you want to tolerate (often hundreds of MB), and raise the replica buffer limit.

Read in post: Redis
Edge caseSeniorTwo sentinels are never enough for a safe failoverElecting a leader needs a majority of live sentinels, not just the quorum. With 2 sentinels, losing one machine (often the very machine running the master and one sentinel) leaves 1/2, which is not a majority: no failover, exactly when you need it most. Run at least 3 sentinels on 3 independent machines (or 3 availabil

Electing a leader needs a majority of live sentinels, not just the quorum. With 2 sentinels, losing one machine (often the very machine running the master and one sentinel) leaves 1/2, which is not a majority: no failover, exactly when you need it most. Run at least 3 sentinels on 3 independent machines (or 3 availability zones).

An old master cut off from the network but still alive keeps accepting writes from clients on its side, and those writes are lost when it rejoins as a replica; set min-replicas-to-write 1 so it stops on its own.

Read in post: Redis
Edge caseSeniorA hash tag that is too coarse piles all the data into one slotA hash tag is for grouping a few related keys, not for making multi-key commands convenient. Tagging by something with a huge number of keys ({tenant:big-customer}, {2026-11-18}) puts millions of keys and all their traffic into one slot on one node: that node runs out of memory and gets overloaded while the others sit

A hash tag is for grouping a few related keys, not for making multi-key commands convenient. Tagging by something with a huge number of keys ({tenant:big-customer}, {2026-11-18}) puts millions of keys and all their traffic into one slot on one node: that node runs out of memory and gets overloaded while the others sit idle, and a slot can't be split. Choose tags at the level of one entity (one user, one cart, one flight); if you need to group by something large, redesign so you don't need multi-key commands.

Read in post: Redis
Trade-offSeniorSingle node, master-replica, Sentinel or ClusterSingle node (optionally with RDB): dev, secondary caches where loss doesn't matter. Cheapest, no HA. Master + replica with manual failover: you want a hot standby and read scaling, and accept a few minutes of downtime while switching by hand. Sentinel: the data fits on one machine (a few tens of GB), writes fit one com
  • Single node (optionally with RDB): dev, secondary caches where loss doesn't matter. Cheapest, no HA.
  • Master + replica with manual failover: you want a hot standby and read scaling, and accept a few minutes of downtime while switching by hand.
  • Sentinel: the data fits on one machine (a few tens of GB), writes fit one command thread, and you need automatic failover. You keep every multi-key command, SELECT and arbitrary Lua. Suits most small and medium systems.
  • Cluster: the data or the write load outgrows one node, or you want small instances so fork() is fast. You must design keys with hash tags and accept the multi-key limitations.
  • Managed (ElastiCache, Memorystore, Azure Cache): removes most of the operations work, but you still need the concepts above to choose a configuration and make sense of incidents.
  • No mode turns Redis into a lossless store: replication is always asynchronous.
Read in post: Redis
InterviewMidHow do RDB and AOF differ?

RDB is a periodic snapshot (fast reload, loses changes since the last one); AOF logs every command (loses ~1 second with everysec, but the file is larger and reloads more slowly).

RDB is created by BGSAVE (forking a child process) and the file is compact. AOF fsyncs according to appendfsync (every second by default) and needs periodic rewrites. Hybrid mode (the default since 5.0 when AOF is on) writes the base in RDB format and then appends commands in AOF format.

Read in post: Redis
InterviewMidDoes BGSAVE block Redis?

Writing the file doesn't, but fork() itself does block the main thread.

fork() copies the page table, proportionally to the amount of RAM (tens to hundreds of ms on a large instance). Copy-on-write also makes memory grow with the amount of writes during the snapshot. SAVE, on the other hand, blocks completely.

Read in post: Redis
InterviewMidIs Redis replication synchronous or asynchronous? What are the consequences?

Asynchronous: the master replies to the client before the replica receives the command.

Consequences: reads from replicas can be stale, and when the master dies and a replica is promoted, writes acknowledged with "OK" that hadn't reached the replica are lost. WAIT and min-replicas-to-write reduce the risk but don't make it truly synchronous.

Read in post: Redis
InterviewMidWhat is a hash tag in Redis Cluster?

A non-empty {...} part of a key: only that part is hashed with CRC16 to pick the slot.

It puts related keys (user_profile:{34}, user_session:{34}) into the same slot, so multi-key commands, transactions and Lua can run on them. A tag that is too coarse piles many keys onto one node.

Read in post: Redis
InterviewSeniorHow does a Sentinel failover work? How many sentinels do you need?

SDOWN → a quorum makes it ODOWN → a leader is elected by majority → the leader promotes the best replica. You need at least 3 sentinels on 3 independent machines.

Each sentinel pings the master; after down-after-milliseconds without a reply it marks it SDOWN. The leader picks a replica (priority, largest offset, run ID), promotes it, reconfigures the other replicas and informs clients through service discovery. Three sentinels so that a majority still exists after losing one machine.

Read in post: Redis
InterviewSeniorWhy does Redis Cluster have 16,384 slots?

Because heartbeats carry a slot bitmap: 16,384 bits is 2 KB, while 65,536 bits is 8 KB, too heavy to send constantly.

Cluster targets at most ~1,000 masters, so 16,384 slots are fine-grained enough to spread evenly. Slots also allow moving data explicitly, piece by piece, during resharding.

Read in post: Redis
InterviewSeniorWhat is the difference between MOVED and ASK?

MOVED: the slot now belongs to another node permanently, so the client updates its slot table. ASK: the slot is being migrated, so the client redirects this one request only.

With ASK, this particular key is already on the target node; the client sends ASKING followed by the command to the target, without updating its slot table, because the slot still officially belongs to the source node until the migration finishes.

Read in post: Redis
InterviewSeniorWhen do you choose Sentinel over Cluster?

When the data fits on one node and the write load fits one command thread.

Sentinel gives you automatic failover while keeping every multi-key command, multiple databases and Lua without slot restrictions, with simpler clients. Choose Cluster when you need to scale writes or capacity beyond one node, or want small instances so forks are fast, and you accept designing keys with hash tags.

Read in post: Redis
InterviewSeniorCan Redis be used as a primary data store?

Yes, for data that fits in RAM and can tolerate a little loss; no, for data where acknowledged writes must never be lost.

You lose about 1 second with AOF everysec, more on failover because replication is asynchronous. It is a poor fit for money, inventory, or data needing complex queries, relations or multi-table transactions. Then Redis is a cache or an acceleration layer in front of the database, or you use a service with a durable log such as MemoryDB.

Read in post: Redis
Edge caseSeniorReDoS leaves no exception and no error logA ReDoS request is merely "slow": one thread at 100% CPU, no stack trace. A few dozen of them drain Tomcat's thread pool, health checks time out, the autoscaler adds pods, and the new pods get eaten too. How to spot it: a thread dump (jcmd <pid Thread.print) shows many RUNNABLE threads with deep stacks full of java.uti

A ReDoS request is merely "slow": one thread at 100% CPU, no stack trace. A few dozen of them drain Tomcat's thread pool, health checks time out, the autoscaler adds pods, and the new pods get eaten too.

How to spot it: a thread dump (jcmd <pid> Thread.print) shows many RUNNABLE threads with deep stacks full of java.util.regex.Pattern$Loop.match, Pattern$GroupTail.match, Pattern$CharProperty.match. A profiler or JFR (Java Flight Recorder) shows CPU concentrated in java.util.regex.

Read in post: ReDoS in Java
Edge caseSenior@Size does not stop @Pattern from running on long input@Size(max = 100) @Pattern(regexp = "...") String name does not mean @Pattern only runs once @Size has passed. Bean Validation evaluates every constraint on the field in no guaranteed order, so a 1 MB string still goes into the regex. Real ways to stop it: limit request size at the outer layers (server.tomcat.max-http-f

@Size(max = 100) @Pattern(regexp = "...") String name does not mean @Pattern only runs once @Size has passed. Bean Validation evaluates every constraint on the field in no guaranteed order, so a 1 MB string still goes into the regex.

Real ways to stop it: limit request size at the outer layers (server.tomcat.max-http-form-post-size, the reverse proxy's body limit, max-http-request-header-size), use a @GroupSequence so length is checked first, or check length() in code before calling matcher.

Read in post: ReDoS in Java
Edge caseSeniorFuture.cancel(true) does not stop a running regexcancel(true) only sets the worker thread's interrupt flag, and the regex engine never checks it. I measured it with ^(a+){2,30}$ on 30 a's plus !: get() timed out after 100 ms, cancel returned true, yet the worker finished after 15.4 seconds. The client already got its error while the CPU stays busy; under load, the ex

cancel(true) only sets the worker thread's interrupt flag, and the regex engine never checks it. I measured it with ^(a+){2,30}$ on 30 a's plus !: get() timed out after 100 ms, cancel returned true, yet the worker finished after 15.4 seconds.

The client already got its error while the CPU stays busy; under load, the executor fills up with threads nobody can stop. You have to make the engine itself stop, with a deadline-aware CharSequence.

Read in post: ReDoS in Java
Edge caseSenior(a|b)* on long input throws StackOverflowError, [ab]* doesn'tStackOverflowError is an Error, it sails past catch (Exception e), and it can kill a consumer thread. Fix: use a character class [ab] (one node, no recursion), or a possessive group (?:a|b)+. Same family: (.|\n) to match across lines; replace it with [\s\S] or the DOTALL flag.

StackOverflowError is an Error, it sails past catch (Exception e), and it can kill a consumer thread. Fix: use a character class [ab]* (one node, no recursion), or a possessive group (?:a|b)*+. Same family: (.|\n)* to match across lines; replace it with [\s\S]* or the DOTALL flag.

Read in post: ReDoS in Java
Trade-offSeniorRegex or hand-written code for validation and parsing on hot pathsRegex: short, declarable in an annotation, easy to change. In exchange it's hard to read when long and carries backtracking risk that reviewers usually can't see. Hand-written code (a charAt loop, indexOf, Character.isDigit): longer, but always linear, failures are obvious, and the JIT optimises it very well. Good for
  • Regex: short, declarable in an annotation, easy to change. In exchange it's hard to read when long and carries backtracking risk that reviewers usually can't see.
  • Hand-written code (a charAt loop, indexOf, Character.isDigit): longer, but always linear, failures are obvious, and the JIT optimises it very well. Good for simple formats executed extremely often: header parsing, key=value splitting, id checks.
  • A parser or purpose-built library (URI, InetAddress, LocalDate.parse, Jackson): more correct than either for standardised formats.
  • Choose regex when the pattern is short, reviewed and tested with hostile input, and the input is length-limited. Otherwise prefer a library, then hand-written code.
Read in post: ReDoS in Java
InterviewMidA form validates names with @Pattern. What do you check to make sure it isn't a ReDoS hole?

Three things: whether the pattern is ambiguous, whether input length is capped before the regex, and whether there's a test with hostile input.

  • Whether the pattern has nested quantifiers or bounded repetition of a group with an optional part ((\w+\s?){1,20}); if so, rewrite it so every input has one way to match (\w+(?:\s\w+){0,19}).
  • Whether input length is limited before it reaches the regex: an @Size next to it isn't enough, because constraint order isn't guaranteed, so you need a server-side body limit or a @GroupSequence.
  • A unit test with the longest worst-case input and a @Timeout.
Read in post: ReDoS in Java
InterviewMidWhy is \s+$ with find() slow even though it has no nested quantifiers?

Because find() tries every starting position, and from each one \s+ eats the rest of the run and then fails: about n²/2 steps in total.

20,000 spaces took 630 ms, and that's exactly the 2016 Stack Overflow outage. Fix it with (?<!\s)\s+$, so a match can only start at the beginning of a run, or skip regex entirely: stripTrailing().

Read in post: ReDoS in Java
InterviewSeniorYour Java service suddenly burns 100% CPU with no error logs. How do you tell whether it's ReDoS?

Take a few thread dumps a few seconds apart; many RUNNABLE threads with deep stacks full of java.util.regex.Pattern$...match frames make it almost certain.

  • Use jcmd <pid> Thread.print, and look for the same application frame at the bottom. JFR or async-profiler gives a clearer flame graph.
  • Find the triggering request in the access log (slow requests, long payloads), reproduce it in a unit test, fix the pattern.
  • Add an input length limit and a deadline-aware CharSequence timeout.
Read in post: ReDoS in Java
InterviewSeniorDoes Java have a regex timeout? How do you get one?

No. What works is wrapping the input in a CharSequence whose charAt throws past a deadline, since the engine calls charAt constantly.

Future.get(timeout) followed by cancel(true) doesn't stop it, because the engine never checks the interrupt flag; the thread keeps running until the regex finishes. Alongside that: limit input length, and for user-supplied patterns use a linear-time engine such as RE2/J.

Read in post: ReDoS in Java
InterviewSeniorWhy can (a|b)* cause a StackOverflowError, and why is that dangerous?

Java's engine recurses one level per iteration of a group containing an alternation, so stack depth grows with input length.

On a 2 MB thread stack, 5,000 characters already overflow. StackOverflowError is an Error, not caught by catch (Exception e), so it can kill a consumer or worker thread. Fix it with a character class [ab]*, a possessive group, or [\s\S]* instead of (.|\n)*.

Read in post: ReDoS in Java
InterviewSeniorWhat regex review checklist would you give your team?

Unambiguous patterns, bounded input, tests with hostile input, and a linear-time engine for anything from outside.

  • Patterns are static final; no String.matches/replaceAll on hot paths. Anchors in the right places.
  • No nested quantifiers or overlapping alternation; negated character classes instead of .* in the middle of a pattern.
  • Input length limited before the regex runs.
  • Unit tests with must-match cases, near-miss cases that must not match, and long hostile input under @Timeout.
  • RE2/J for patterns or input from outside.
  • User data going into a pattern is wrapped in Pattern.quote, and into a replacement string in Matcher.quoteReplacement.
Read in post: ReDoS in Java
Edge caseMidThe source contradicts itself about refresh tokensThe theory part says a refresh token is a "random string, 7–30 days, stored in the DB". The practice part sets a cookie refreshtoken=<jwt with Max-Age=259200 (3 days) and stores the raw token. Pick one clear contract: a random string, stored as a hash, TTL in configuration (app.jwt.refresh-ttl=7d), and the cookie using

The theory part says a refresh token is a "random string, 7–30 days, stored in the DB". The practice part sets a cookie refresh_token=<jwt> with Max-Age=259200 (3 days) and stores the raw token. Pick one clear contract: a random string, stored as a hash, TTL in configuration (app.jwt.refresh-ttl=7d), and the cookie using that same TTL.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Trade-offSeniorReuse detection versus kicking out real usersReuse detection sometimes hits the innocent: on a flaky network the client sends a refresh, the server rotates, the response is lost, the client retries with the old token → the whole family is revoked and the user must log in again. Mitigations: a short grace period (a few seconds) during which the just-rotated token

Reuse detection sometimes hits the innocent: on a flaky network the client sends a refresh, the server rotates, the response is lost, the client retries with the old token → the whole family is revoked and the user must log in again.

Mitigations: a short grace period (a few seconds) during which the just-rotated token returns the same successor, and an SPA that allows only one refresh in flight. The price: a fast thief inside that window gets through too. Financial systems usually choose strict; content apps choose forgiving.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Edge caseMidLazyInitializationException when reading roles after the transaction closedThe lab's first version returned Rotated(User user, String token) and let the controller call r.user().getRoles(). The refresh test returned 500: LazyInitializationException: Could not initialize proxy [User3] - no session. Why: current.getUser() is a lazy proxy; the transaction (and the Hibernate session) closes when

The lab's first version returned Rotated(User user, String token) and let the controller call r.user().getRoles(). The refresh test returned 500: LazyInitializationException: Could not initialize proxy [User#3] - no session.

Why: current.getUser() is a lazy proxy; the transaction (and the Hibernate session) closes when rotate() returns; with spring.jpa.open-in-view=false the controller has no session. Fix: read email and roles inside the transaction and return a plain data record. Don't fix it by re-enabling open-in-view or FetchType.EAGER. More on the persistence context: JPA persistence context and N+1.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Edge caseMidThe "Authority = standing, Permission = action" paragraph is misleadingThe source adds a "supplementary" paragraph calling an authority a "standing" (ADMIN, MANAGER) and a permission an "action". In Spring the opposite is closer: a role is the group (the standing), while authority is the general concept that covers roles (ROLEADMIN), action permissions (CREATEUSER) and even FACTORPASSWORD

The source adds a "supplementary" paragraph calling an authority a "standing" (ADMIN, MANAGER) and a permission an "action". In Spring the opposite is closer: a role is the group (the standing), while authority is the general concept that covers roles (ROLE_ADMIN), action permissions (CREATE_USER) and even FACTOR_PASSWORD. In an interview: "a role is an authority with the ROLE_ prefix".

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Trade-offSeniorA DB lookup per request or a permission cacheThe lab hits the DB per request: one indexed JOIN, correct the moment permissions change. Under high load that is one extra DB round-trip for every API call. The usual approach: cache role → permissions (Caffeine in-process, or Redis with many instances) and evict when a role or permission changes (events or a short TT

The lab hits the DB per request: one indexed JOIN, correct the moment permissions change. Under high load that is one extra DB round-trip for every API call.

The usual approach: cache role → permissions (Caffeine in-process, or Redis with many instances) and evict when a role or permission changes (events or a short TTL). The price: a delay between editing permissions and the change taking effect, and one more failure source. Don't solve it by putting the permission list into the JWT: tokens bloat and stale permissions live until expiry.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Edge caseSeniorA catch-all handler turns 403 into 500@PreAuthorize throws AccessDeniedException inside the controller call, so @RestControllerAdvice sees it. If the advice has an @ExceptionHandler(Exception.class) returning 500, unauthorized users get 500 "Unexpected error". The lab tried removing the dedicated handler: the test expected 403 and got 500. Fix: add a handl

@PreAuthorize throws AccessDeniedException inside the controller call, so @RestControllerAdvice sees it. If the advice has an @ExceptionHandler(Exception.class) returning 500, unauthorized users get 500 "Unexpected error". The lab tried removing the dedicated handler: the test expected 403 and got 500.

Fix: add a handler for AccessDeniedException that re-throws it so ExceptionTranslationFilter answers 403 through the AccessDeniedHandler (or return a 403 ProblemDetail yourself). A test for the forbidden case exposes this class of bug immediately.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewJuniorWhy do we need a refresh token if we already have an access token?

So the access token can be short-lived (minutes) without users logging in constantly, and so the server has a place to revoke the session.

An access token is verified without the DB, so it can't be revoked; the refresh token lives in the DB, so logout or blocking an account takes effect at the next refresh.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewJuniorWhat is the difference between hasRole('ADMIN') and hasAuthority('ADMIN')?

hasRole('ADMIN') compares with the authority ROLE_ADMIN; hasAuthority('ADMIN') matches the exact string ADMIN.

A role is just an authority with the ROLE_ prefix. Mixing the two styles is a common source of puzzling 403s.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewMidWhy store a hash of the refresh token, and why SHA-256 rather than BCrypt?

Hashing means a DB leak doesn't leak usable tokens; SHA-256 is enough because the token has 256 random bits and can't be guessed like a password.

BCrypt is slow to resist guessing weak passwords; random tokens don't need that, and a deterministic hash can be looked up through a unique index.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewMidA @Transactional service returns an entity, the controller calls getRoles() and gets LazyInitializationException. Why, and how do you fix it?

A lazy collection can only load while the Hibernate session is open, and the session closes with the transaction; with open-in-view off, the controller has no session.

Fix it by building the data you need (a DTO/record) inside the transaction, or with a fetch join / entity graph. Don't fix it with open-in-view or EAGER.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewMidWhy can @ExceptionHandler(Exception.class) give unauthorized users a 500?

Because @PreAuthorize throws AccessDeniedException during the controller call, the advice catches it before security does, and the catch-all returns 500.

Add a dedicated handler for AccessDeniedException (re-throw or return 403), and test the forbidden case.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewSeniorDesign rotating refresh tokens with reuse detection. Where is the implementation easy to get wrong?

Each refresh revokes the old token and issues a new one in the same family; a revoked token showing up again revokes the whole family. The traps are concurrency, transactions and user experience.

  • Two parallel refreshes: use a row lock or a conditional update, otherwise the family forks.
  • Throwing after revoking the family: needs noRollbackFor, otherwise the revocation rolls back.
  • Lost responses: consider a short grace period, and a single refresh in flight on the client.
  • Log reuse warnings for investigation.
Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewSeniorYou check (method, path) permissions in the DB on every request. What changes in production?

Cache role → permissions (in-process or Redis) with eviction when permissions change, measure latency, and still keep permissions out of the JWT.

Pre-compile path patterns instead of parsing them per request. Agree on an acceptable delay for permission changes. Keep data-based business rules (same company, record ownership) in the service, because URLs can't express them.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
InterviewSeniorWhat happens with a JPA many-to-many when you delete a Role that is assigned to users?

It depends on the owning side: if User owns user_role, deleting the Role fails with a foreign key violation; Hibernate only removes join rows when deleting from the owning side.

Remove the role from its users first (in the same transaction) or refuse to delete a role in use with a clear 409. Never put CascadeType.REMOVE on a many-to-many.

Read in post: Rotating refresh tokens and permission-based authorization in Spring Security
Edge caseMidAn optional group that didn't match returns null, not an empty stringAn interface without a secondary IP still matches, but m.group("ip01") returns null: string concatenation prints the word "null", and .trim() throws NullPointerException. Wrap it in Optional.ofNullable(m.group("ip01")), or check m.start("ip01") == -1. By contrast, (?<x\d) that matched zero characters returns "". Two di

An interface without a secondary IP still matches, but m.group("ip01") returns null: string concatenation prints the word "null", and .trim() throws NullPointerException. Wrap it in Optional.ofNullable(m.group("ip01")), or check m.start("ip01") == -1. By contrast, (?<x>\d*) that matched zero characters returns "". Two different meanings: "this line isn't there" versus "the line is there but the value is empty".

Read in post: Regex by example
Trade-offSeniorParse logs with regex, or log in a structured formatRegex over text logs: no application change, works immediately on old logs. But the pattern is tied to the message wording: someone changes "claimed voucher" to "redeemed voucher" and the report silently drops to zero. Structured logging (JSON, or key-value like event=voucherclaimed userId=U56 voucherId=V12): requires
  • Regex over text logs: no application change, works immediately on old logs. But the pattern is tied to the message wording: someone changes "claimed voucher" to "redeemed voucher" and the report silently drops to zero.
  • Structured logging (JSON, or key-value like event=voucher_claimed userId=U56 voucherId=V12): requires a code change and makes logs longer. In return, Loki, Elasticsearch or Datadog can filter on fields with no regex, and rewording a message doesn't break queries.
  • Choose: regex for one-off jobs or for logs from systems you can't change. For business numbers that must be right (how many vouchers were claimed), emit a structured event, or better, count from the database or the event stream, not from logs.
Read in post: Regex by example
Edge caseMidAn unanchored backreference treats U109 as a duplicate of U1092The "almost right" version (?m)^(.+)$(?=[\s\S]\1) returns [U123, U234, U1092, U109]: U234 is a "duplicate" because U2342 comes later, and U109 because it sits inside U1092. The backreference \1 matches a substring, not a whole line. Anchor both ends: ^\1$ (with MULTILINE). Bugs like this are why regex tests always need

The "almost right" version (?m)^(.+)$(?=[\s\S]*\1) returns [U123, U234, U1092, U109]: U234 is a "duplicate" because U2342 comes later, and U109 because it sits inside U1092. The backreference \1 matches a substring, not a whole line. Anchor both ends: ^\1$ (with MULTILINE). Bugs like this are why regex tests always need "almost the same but must not match" cases.

Read in post: Regex by example
Trade-offMidRegex or data structures for problems that compare linesRegex shines when each line (or chunk) is judged on its own: validation, field extraction, reformatting. When a line must be compared with other lines (duplicates, counts, grouping), regex needs backreferences and lookaheads that scan the whole input: hard to read, O(n²) or worse, and liable to hit stack limits on long
  • Regex shines when each line (or chunk) is judged on its own: validation, field extraction, reformatting.
  • When a line must be compared with other lines (duplicates, counts, grouping), regex needs backreferences and lookaheads that scan the whole input: hard to read, O(n²) or worse, and liable to hit stack limits on long input.
  • HashSet, a counting Map, awk or sort | uniq do the same job in O(n) or O(n log n), more clearly, and are easy to test.
  • Use regex for a one-off edit of a small file in the editor; use data structures for anything that runs repeatedly.
Read in post: Regex by example
InterviewJuniorHow do you remove duplicate lines in Java while keeping the original order?

Put the lines into a LinkedHashSet, or use lines.stream().distinct().toList().

The hash part dedupes in O(1) per element and the linked part keeps insertion order, so the first copy of each line survives. distinct() also keeps encounter order. On the command line: awk '!seen[$0]++' file.

Read in post: Regex by example
InterviewJuniorWhy use [0-9] with sed -E instead of \d?

Because sed and grep use POSIX regex, which has no Perl-style shorthands like \d, \S, and no lookaround.

POSIX ERE (-E) has +, ?, |, {n,m} and unescaped groups. Write [0-9], [^ ], or POSIX classes such as [[:digit:]] and [[:space:]]. GNU grep -P accepts PCRE syntax, but it isn't available in macOS's grep.

Read in post: Regex by example
InterviewMidWhat goes wrong when you use an unanchored \1 to find duplicate lines?

\1 re-matches the captured substring anywhere, so a line contained inside another line counts as a duplicate.

With (?m)^(.+)$(?=[\s\S]*\1), U109 counts as a duplicate because it appears inside U1092, and U234 because of U2342. Anchor the whole line: (?=[\s\S]*^\1$) with MULTILINE. The general lesson: regex tests always need "almost the same but must not match" cases.

Read in post: Regex by example
InterviewMidA multi-line block has an optional part. How do you write the pattern and read the result?

Put the optional part in (?:...)? with named groups inside, and handle group(name) returning null when it's absent.

Use \R for line breaks (it copes with \r\n) and \h for horizontal whitespace, so the pattern can't run into the next line. Wrap the result in an Optional. If the line order can change, split the input into blocks first (on the opening line) and parse each line with a small pattern, rather than one big pattern.

Read in post: Regex by example
InterviewSeniorWhen would you not use regex even though it could work?

When comparing lines with each other, when the format is nested, when a purpose-built library exists, and when you can change the producer of the data.

  • Comparing lines (duplicates, counts): data structures do it in O(n); regex is O(n²) and hard to read.
  • Nested formats like JSON, HTML, XML, SQL: regex can't parse nested languages, so use a parser.
  • A library exists: InetAddress for IPs, LocalDate.parse for dates, URI for URLs, BigDecimal or NumberFormat for numbers.
  • You can change the producer: structured logging instead of regex over log messages.
Read in post: Regex by example
InterviewSeniorThe team's log-extraction regex suddenly returns zero results after a deploy. How do you investigate and prevent it?

First suspect a change in the message format; prevent it by treating the log format as a contract with tests and alerts.

  • Investigate: the format can change through reworded text, an extra field, a new logback pattern, a timestamp in a different locale. Compare a fresh log line with the pattern on regex101 (in the right flavor) to find the mismatch.
  • Prevent: a unit test that produces a log line through the real logging code and runs the pattern on it; structured logging with an event field; an alert when the match count drops to zero unexpectedly.
  • Business metrics: read them from the database or the event stream rather than the logs.
Read in post: Regex by example
Edge caseJuniorThe dot does not match a newlineThe course slides (and plenty of other material) say . means "any character", but by default it excludes line terminators (\n, \r, ...): a.b does not match "a\nb". Turn on DOTALL (inline (?s)), or use [\s\S], which works in every flavor. This is why a regex that parses multi-line log entries (stack traces) works on the

The course slides (and plenty of other material) say . means "any character", but by default it excludes line terminators (\n, \r, ...): a.b does not match "a\nb". Turn on DOTALL (inline (?s)), or use [\s\S], which works in every flavor. This is why a regex that parses multi-line log entries (stack traces) works on the first line and then stops.

Read in post: Regex
TILMidIn Java, \w and \d are ASCII-only by default\w does not match é, and \d does not match the Arabic-Indic digit ٣; on Vietnamese data, \w+ splits "Nguyễn" into "Nguy" and "n". Turn on Pattern.UNICODECHARACTERCLASS ((?U)) to make them Unicode-aware (slightly slower), or use \p{L} (any Unicode letter) and \p{M} (combining marks, for text that isn't NFC-normalised).

\w does not match é, and \d does not match the Arabic-Indic digit ٣; on Vietnamese data, \w+ splits "Nguyễn" into "Nguy" and "n". Turn on Pattern.UNICODE_CHARACTER_CLASS ((?U)) to make them Unicode-aware (slightly slower), or use \p{L} (any Unicode letter) and \p{M} (combining marks, for text that isn't NFC-normalised).

Read in post: Regex
Edge caseJunior{n, m} with a space is not a quantifierThe slides write {n, m} with a space after the comma. Java throws PatternSyntaxException: Unclosed counted closure on a{1, 3}. JavaScript silently treats /a{1, 3}/ as literal text that only matches the string a{1, 3}: a silent bug. Write {1,3}.

The slides write {n, m} with a space after the comma. Java throws PatternSyntaxException: Unclosed counted closure on a{1, 3}. JavaScript silently treats /a{1, 3}/ as literal text that only matches the string a{1, 3}: a silent bug. Write {1,3}.

Read in post: Regex
Edge caseSeniorJava lookbehind needs a bounded maximum length, and sometimes fails silently(?<=(ab)+)c is rejected at compile time ("Look-behind group does not have an obvious maximum length"). Worse: on JDK 21, (?<=passport\s:\s)\d+ (two inside the lookbehind) compiles fine but never matches, not even "passport:123", while (?<=a\s)b (one ) works. Don't rely on that behaviour. Always bound the length: (?<=pa

(?<=(ab)+)c is rejected at compile time ("Look-behind group does not have an obvious maximum length"). Worse: on JDK 21, (?<=passport\s*:\s*)\d+ (two * inside the lookbehind) compiles fine but never matches, not even "passport:123", while (?<=a\s*)b (one *) works. Don't rely on that behaviour. Always bound the length: (?<=passport\s{0,5}:\s{0,5})\d+ correctly matches 123. Or use a capturing group instead of a lookbehind, which works in every flavor.

Read in post: Regex
Edge caseMidJava has no g flag, and m does not make the dot match newlinesThe g flag is a JavaScript and regex101 concept. In Java, "every match" means calling matcher.find() in a loop or using matcher.results(); replaceAll already replaces every occurrence. MULTILINE only changes what ^ and $ mean; DOTALL is what makes . match \n. Parsing a multi-line log block usually needs both: (?ms).

The g flag is a JavaScript and regex101 concept. In Java, "every match" means calling matcher.find() in a loop or using matcher.results(); replaceAll already replaces every occurrence. MULTILINE only changes what ^ and $ mean; DOTALL is what makes . match \n. Parsing a multi-line log block usually needs both: (?ms).

Read in post: Regex
Edge caseMidThe replacement string in replaceAll is not plain text"price".replaceAll("price", "$5") throws IndexOutOfBoundsException: No group 5 because $5 means group 5. This blows up in production when the replacement comes from data (prices, passwords containing $ or \). Wrap data in Matcher.quoteReplacement(value). When you don't need regex, use String.replace(CharSequence, CharS

"price".replaceAll("price", "$5") throws IndexOutOfBoundsException: No group 5 because $5 means group 5. This blows up in production when the replacement comes from data (prices, passwords containing $ or \). Wrap data in Matcher.quoteReplacement(value). When you don't need regex, use String.replace(CharSequence, CharSequence): it replaces every occurrence, literally (the name misleads people into thinking it only replaces the first).

Read in post: Regex
Edge caseJuniorsplit(".") returns an empty arrayThe argument of split is a regex: "a.b.c".split(".") returns an empty array, because . matches every character, every piece is empty, and split drops trailing empty strings. Write split("\\.") or split(Pattern.quote(".")). Same for |, $, +: "a|b".split("|") splits between every character. Pattern.quote(s) turns the who

The argument of split is a regex: "a.b.c".split(".") returns an empty array, because . matches every character, every piece is empty, and split drops trailing empty strings. Write split("\\.") or split(Pattern.quote(".")). Same for |, $, +: "a|b".split("|") splits between every character. Pattern.quote(s) turns the whole string into a literal, handy when the delimiter comes from configuration.

Read in post: Regex
Trade-offMidString.matches/replaceAll/split or a prebuilt PatternString.matches, replaceAll, replaceFirst and split compile the pattern on every call. split has a fast path that bypasses the regex engine: a single non-metacharacter delimiter (","), or two characters made of \ plus a non-alphanumeric character ("\\."). A rough measurement (one million calls, not JMH): validating an e
  • String.matches, replaceAll, replaceFirst and split compile the pattern on every call. split has a fast path that bypasses the regex engine: a single non-metacharacter delimiter (","), or two characters made of \ plus a non-alphanumeric character ("\\.").
  • A rough measurement (one million calls, not JMH): validating an email with String.matches took ~500 ns per call, with a static final Pattern ~240 ns. The difference is compilation cost plus garbage.
  • Choose: scripts, migrations and tests can use the String methods for brevity; the request path, loops and Kafka consumers should use a private static final Pattern.
Read in post: Regex
Edge caseMidTest a regex in the flavor that will run itA regex that works on regex101's JavaScript flavor can fail to compile in Java (unbounded lookbehind, {n, m} with a space that JS treats as literal) or match differently ($ before a final \n, \w and Unicode). The safe workflow: try it in the flavor of the runtime (Java 8, PCRE2 for Nginx, POSIX ERE for grep -E), then w

A regex that works on regex101's JavaScript flavor can fail to compile in Java (unbounded lookbehind, {n, m} with a space that JS treats as literal) or match differently ($ before a final \n, \w and Unicode). The safe workflow: try it in the flavor of the runtime (Java 8, PCRE2 for Nginx, POSIX ERE for grep -E), then write a Java unit test with cases that must match and cases that must not match.

Read in post: Regex
Edge caseMidA "fully correct" email regex doesn't exist and isn't neededThe exercise treats a%v@example.com as invalid, but under RFC 5322 % (like +, !, ...) is legal in the local part; blocking + also breaks real addresses like me+shop@gmail.com. A regex covering the whole RFC runs to thousands of characters and still can't answer the question that matters: does this mailbox exist and bel

The exercise treats a%v@example.com as invalid, but under RFC 5322 % (like +, !, #...) is legal in the local part; blocking + also breaks real addresses like me+shop@gmail.com. A regex covering the whole RFC runs to thousands of characters and still can't answer the question that matters: does this mailbox exist and belong to this person? In practice: a loose check (exactly one @, a dot in the domain, at most 254 characters) or Bean Validation's @Email, then send a confirmation email. The regex above still has holes (it accepts a..b@x.com); as a coarse filter that's acceptable.

Read in post: Regex
InterviewJuniorHow do matches(), find() and lookingAt() differ?

matches() needs the whole input to match, lookingAt() needs a match from the start, find() finds the next match anywhere.

matches() anchors both ends; lookingAt() doesn't have to reach the end; find() is called repeatedly for subsequent matches. Use matches() for validation; use find() or results() for search and extraction. Validating with find() and forgetting ^...$ is the classic bug: \d{6} then accepts "abc1234567".

Read in post: Regex
InterviewJuniorWhy does "a.b.c".split(".") return an empty array?

Because the argument of split is a regex, and . matches any character.

Every character is a delimiter, so every piece is empty, and split drops trailing empty strings, leaving an empty array. Fix: split("\\.") or split(Pattern.quote(".")). Same family of traps: |, $, +, *.

Read in post: Regex
InterviewJuniorWhen do you use a capturing group, a non-capturing group and a named group?

(...) when you need the matched text back, (?:...) when you only need grouping, (?<name>...) when the pattern has several groups.

(...) groups and remembers the text so you can read it (group(1)) or refer back to it (\1, $1). (?:...) only groups, for a quantifier or alternation over several tokens. (?<name>...) is read with group("name") and referenced as ${name}; adding a new group won't shift the numbers of the existing ones.

Read in post: Regex
InterviewJuniorWhat do ^ and $ mean, and what does MULTILINE change?

By default ^ is the start of the input and $ the end; with MULTILINE, they match at the start and end of every line.

In Java, $ also matches before one final \n; use \z for "the very end". MULTILINE does not make . match newlines; that's DOTALL's job.

Read in post: Regex
InterviewMidWhat are lookahead and lookbehind? Give an example that needs them.

Lookaround checks a condition at the current position without consuming characters, so the checked part isn't in the match.

Example: extracting passport numbers when passport and citizen ids share the same 8-digit format: (?<=passport (?:number|no): )\d{8}. Another: requiring at least one digit in a password with ^(?=.*\d).{8,}$. In Java a lookbehind must have a bounded maximum length; where possible, a capturing group is simpler and more portable.

Read in post: Regex
InterviewMidWhy can replaceAll throw when the replacement comes from user data?

Because in the replacement string $n is a group reference and \ is an escape; wrap the value with Matcher.quoteReplacement.

Values like "$5" or "C:\path" throw IndexOutOfBoundsException or IllegalArgumentException, or silently produce the wrong text. If you don't need regex, use String.replace. The other direction: when user text goes into the pattern, wrap it with Pattern.quote so special characters don't become regex syntax.

Read in post: Regex
InterviewMidIs Pattern thread-safe? How should you declare it?

Yes: Pattern is immutable, so declare private static final Pattern X = Pattern.compile(...) and share it; Matcher is not thread-safe.

Create a Matcher per use with X.matcher(input), which is cheap. String.matches, replaceAll and split (apart from the single-character fast path) recompile the pattern on every call, so keep them off hot paths.

Read in post: Regex
InterviewMidHow do you validate email addresses with regex?

I don't write an "RFC-correct" regex; I use a loose check and then send a confirmation email.

An RFC-correct regex is enormous, the RFCs themselves disagree in places, and it can't prove the mailbox exists. I use a loose check (one @, a dot in the domain, a length limit, or Bean Validation's @Email), normalise (trim, lowercase the domain), then send a confirmation email. I don't block legal characters like +, because real users rely on me+tag@gmail.com.

Read in post: Regex
InterviewSeniorA colleague says "Java's regex engine is bad, just use JavaScript on regex101". How do you respond?

Java's engine isn't worse; the differences are in the API and escaping, so testing in the JavaScript flavor and pasting into Java is exactly how you get bugs.

java.util.regex is feature-rich (possessive quantifiers, atomic groups, Unicode classes, \R, class intersection); it differs from JavaScript in the API (no g flag, matches() anchors for you), escaping inside string literals, and the lookbehind restriction. Test in regex101's Java 8 flavor and pin the behaviour with unit tests. The real weakness is backtracking: some patterns run in exponential or high-polynomial time, and Java has no built-in timeout. JavaScript, Python and PCRE share that weakness, so switching flavors doesn't help; you need careful patterns, input length limits, or a linear-time engine such as RE2/J.

Read in post: Regex
Edge caseMidAlternation in Java picks the first branch that matches, not the longestJava (and JavaScript, PCRE, Python) all behave this way. Fallout: (\d+|\d+\.\d+) on "3.14" captures just "3"; (m|mm|cm) turns "mm" into "m". Put the longer or more specific branch first, or anchor with \b, $ or a lookahead so the short branch fails when the token isn't finished.

Java (and JavaScript, PCRE, Python) all behave this way. Fallout: (\d+|\d+\.\d+) on "3.14" captures just "3"; (m|mm|cm) turns "mm" into "m". Put the longer or more specific branch first, or anchor with \b, $ or a lookahead so the short branch fails when the token isn't finished.

Read in post: Inside Java's regex engine
Trade-offSeniorGreedy, lazy or possessiveGreedy: the default, cheap when what follows rarely fails. Lazy: right for stopping at the first delimiter (".?"), but no cure for backtracking: without a closing delimiter it still tries every length. Possessive, atomic groups: cut backtracking entirely, but change the meaning when what follows needs characters back (
  • Greedy: the default, cheap when what follows rarely fails.
  • Lazy: right for stopping at the first delimiter (".*?"), but no cure for backtracking: without a closing delimiter it still tries every length.
  • Possessive, atomic groups: cut backtracking entirely, but change the meaning when what follows needs characters back (".*+" never matches). Use them only when the two parts can't share a character, e.g. [^"]*+", \d++\b.
  • My order of preference: negated character class first, possessive once the boundary is certain, lazy for whatever is left.
Read in post: Inside Java's regex engine
Trade-offSeniorBacktracking engine (java.util.regex) or linear-time engine (RE2/J)java.util.regex: built in, feature-complete (backreferences, lookaround, possessive), fast on simple patterns. In exchange: exponential worst case, no timeout. RE2/J (com.google.re2j, an API close to Pattern/Matcher): guaranteed linear time, safe when the pattern or the input comes from outside. In exchange: no backref
  • java.util.regex: built in, feature-complete (backreferences, lookaround, possessive), fast on simple patterns. In exchange: exponential worst case, no timeout.
  • RE2/J (com.google.re2j, an API close to Pattern/Matcher): guaranteed linear time, safe when the pattern or the input comes from outside. In exchange: no backreferences or lookaround, an extra dependency, possibly slower than the JDK on ordinary patterns.
  • Choose: team-reviewed patterns on length-limited input, use the JDK. User-supplied regexes (advanced search, alert rules, admin filters) or large untrusted input, use RE2/J.
Read in post: Inside Java's regex engine
TILSeniorOn modern JDKs, many classic ReDoS examples are no longer slow(a+)+b and ^(\w)$ (the slide's "avoid exponential" example) run instantly on JDK 21 thanks to memoization of /+ loops. Don't conclude from that that your pattern is safe: measure that exact pattern with worst-case input, or analyse it with a tool.

(a+)+b and ^(\w*)*$ (the slide's "avoid exponential" example) run instantly on JDK 21 thanks to memoization of */+ loops. Don't conclude from that that your pattern is safe: measure that exact pattern with worst-case input, or analyse it with a tool.

Read in post: Inside Java's regex engine
Edge caseSeniorAdding a {1,20} limit "for safety" can turn a pattern into a ReDoS^(\w+\s?)$ runs instantly, while ^(\w+\s?){1,20}$, which looks stricter, takes 13 seconds on 30 a's plus a !: bounded repetition isn't memoized. Fix it by removing the ambiguity: ^\w+(?:\s\w+){0,19}$ requires exactly one whitespace between words, so every string has exactly one split: 0 ms at every n. It changes the me

^(\w+\s?)*$ runs instantly, while ^(\w+\s?){1,20}$, which looks stricter, takes 13 seconds on 30 a's plus a !: bounded repetition isn't memoized. Fix it by removing the ambiguity: ^\w+(?:\s\w+){0,19}$ requires exactly one whitespace between words, so every string has exactly one split: 0 ms at every n. It changes the meaning slightly (no trailing whitespace anymore), so retest.

Read in post: Inside Java's regex engine
InterviewMidHow do greedy, lazy and possessive quantifiers differ?

Greedy takes as much as possible then gives back, lazy takes as little as possible then takes more, possessive takes as much as possible and never gives back.

Greedy and lazy can reach the same set of matches but try them in a different order, so they pick different matches (<.+> versus <.+?>). Possessive can change the result (".*+" never matches) but cuts backtracking completely.

Read in post: Inside Java's regex engine
InterviewMidWhy does car|carpet on "carpet" return "car"?

Because Java's backtracking engine tries branches in order and accepts the first one that leads to a match; it doesn't look for the longest.

A POSIX engine follows leftmost-longest and would return "carpet". Fix: put the longer branch first (carpet|car) or anchor with \b(?:car|carpet)\b.

Read in post: Inside Java's regex engine
InterviewMidWhat is catastrophic backtracking, and how do you spot a dangerous pattern?

It's when the number of paths the engine must try grows exponentially (or as a high-degree polynomial) with input length, usually when the match ultimately fails.

Warning signs: the same stretch of input can match the same part of the pattern in several ways: nested quantifiers ((a+)+, (\w+\s?)*), overlapping alternation ((a|aa)+, (\d+|\w+)*), or adjacent .* (.*.*=.*). Fix it by removing the ambiguity: negated character classes, mandatory separators, possessive quantifiers or atomic groups.

Read in post: Inside Java's regex engine
InterviewMidWhat is an atomic group (?>...) for?

To stop useless backtracking: once the group has matched, the engine discards every choice point inside it and never goes back in to try alternatives.

X*+ is exactly (?>X*). The catch: the pattern may stop matching at all if what follows needs characters back from the group, so use it only when the boundary is clear.

Read in post: Inside Java's regex engine
InterviewSeniorHow does RE2 differ from java.util.regex? When would you pick RE2/J?

RE2 builds an automaton and walks the input once, so it's always linear and can't be ReDoS'd; in exchange it has no backreferences or lookaround.

I'd pick RE2/J when the pattern or the input comes from outside: users writing their own search or alert regexes, WAF rules, untrusted imported data. For reviewed internal patterns on length-limited input, the JDK engine is enough.

Read in post: Inside Java's regex engine
InterviewSeniorTextbook ReDoS examples like (a+)+b run instantly on your JDK 21. Is Java immune to ReDoS now?

No. Modern JDKs only memoize */+ group loops, so the classic examples don't reproduce, but many other shapes still blow up.

Bounded repetition ((X+\s?){1,20}), backreferences and three-level nested quantifiers are still exponential; .*.*=.* or \s+$ with find() are still quadratic or cubic. I measured 13 seconds for ^(\w+\s?){1,20}$ on 30 characters. You have to test your actual pattern with hostile input, or use SonarQube or CodeQL to flag it.

Read in post: Inside Java's regex engine
Edge caseMidAn endpoint that creates a job must not be a GETThe slide creates the job with GET /products/jobs/export?name=pen. GET has to be safe: crawlers, browser prefetching, Slack link previews and automatic proxy retries may all repeat a GET, and each repeat starts another heavy export. Creating a job creates a resource: use POST returning 202 Accepted + Location. Stop dou

The slide creates the job with GET /products/jobs/export?name=pen. GET has to be safe: crawlers, browser prefetching, Slack link previews and automatic proxy retries may all repeat a GET, and each repeat starts another heavy export. Creating a job creates a resource: use POST returning 202 Accepted + Location. Stop double clicks with an Idempotency-Key, or dedupe on (user, export type, filter hash) while the previous job is still running.

Read in post: Advanced REST API design
Trade-offSeniorPolling vs webhooks vs SSE/WebSocket for async jobsIn practice you combine them: a webhook to notify, and a status API that always exists for when a webhook is lost. Polling should come with Retry-After and backoff so clients don't hit you every 100 ms.
Polling Webhook (callback) SSE / WebSocket
Complexity Low, just a GET High on both sides: URL registration, signing, retries, idempotent receiver Medium: long-lived connections, sticky sessions or pub/sub across instances
Resources Wasted empty requests One call when done One open connection per client
Who can use it Any client, even behind a firewall Servers with a public URL (partners, B2B) Browsers, apps that are open
Fits Import/export, low load Payments, partner integrations, high load UIs that need live progress

In practice you combine them: a webhook to notify, and a status API that always exists for when a webhook is lost. Polling should come with Retry-After and backoff so clients don't hit you every 100 ms.

Read in post: Advanced REST API design
Edge caseSeniorAn unsigned webhook can be forged by anyoneA callback URL is a public endpoint: anyone who knows it can post {"payment": "SUCCESS"}. The sender signs HMAC-SHA256(secret, timestamp + "." + body) into a header, e.g. Signature: t=1763443200,v1=<hex. The receiver recomputes it over the raw body (not a parsed-then-reserialised copy), compares with MessageDigest.isEq

A callback URL is a public endpoint: anyone who knows it can post {"payment": "SUCCESS"}.

  • The sender signs HMAC-SHA256(secret, timestamp + "." + body) into a header, e.g. Signature: t=1763443200,v1=<hex>.
  • The receiver recomputes it over the raw body (not a parsed-then-reserialised copy), compares with MessageDigest.isEqual (constant time), and rejects timestamps more than 5 minutes off to block replays (resending an old request).
  • The sender retries with backoff whenever it doesn't get a 2xx, so the receiver must be idempotent on event_id, return 2xx quickly and do the work asynchronously.
Read in post: Advanced REST API design
Trade-offSeniorWho generates the idempotency key: client or serverClient-generated (a UUID v4/v7 per operation, kept across retries): the most faithful, because only the client knows two requests are "the same intent". Cost: a client that generates a fresh key on each retry defeats the purpose. Server-derived from content (a hash of user + amount + recipient within a 1-minute window)
  • Client-generated (a UUID v4/v7 per operation, kept across retries): the most faithful, because only the client knows two requests are "the same intent". Cost: a client that generates a fresh key on each retry defeats the purpose.
  • Server-derived from content (a hash of user + amount + recipient within a 1-minute window): needs no client cooperation, but wrongly blocks two legitimate identical payments (sending mum 100k twice in a minute).
  • Server-issued up front (the client gets a checkout_id, then submits with it): the most robust for checkout, at the cost of an extra round trip.

Public payment APIs usually require an Idempotency-Key header on POST and return 400 if it's missing.

Read in post: Advanced REST API design
Edge caseMidBusiness codes and HTTP status must agreeThe original template shows "Status Code: 401" for error code 400001, and a row with code 401000 described as "credit account is locked", which doesn't match its type name. A client that acts on the status (retrying, logging out on 401) will do the wrong thing. The rule: the first 3 digits of code always equal the real

The original template shows "Status Code: 401" for error code 400001, and a row with code 401000 described as "credit account is locked", which doesn't match its type name. A client that acts on the status (retrying, logging out on 401) will do the wrong thing. The rule: the first 3 digits of code always equal the real HTTP status; "account locked" is 403 or 422, not 401 (401 means not authenticated). Enforce it with an automated test asserting the status matches the meta.code prefix.

Read in post: Advanced REST API design
Trade-offSeniorA custom meta/data envelope vs RFC 9457 Problem DetailsCustom envelope: one shape everywhere, easy shared metadata (requestid, serviceid, pagination), fine-grained business codes. Cons: non-standard; clients unwrap data everywhere; it tempts teams to return 200 for everything, breaking retries, caching and status-based monitoring. Problem Details (application/problem+json,
  • Custom envelope: one shape everywhere, easy shared metadata (request_id, service_id, pagination), fine-grained business codes. Cons: non-standard; clients unwrap data everywhere; it tempts teams to return 200 for everything, breaking retries, caching and status-based monitoring.
  • Problem Details (application/problem+json, built into Spring 6 as ProblemDetail): standard, and successful responses stay plain resources. Business codes go into an extension field ("code": "400001").
  • If a system already has an envelope, keep it for consistency and just keep the HTTP status right. For new systems, Problem Details for errors is the less controversial choice. See Spring Boot error handling.
Read in post: Advanced REST API design
Edge caseMidCopy-pasted docs end up contradicting themselvesThe course's sample template carries two copy-paste leftovers: page/size parameters on a POST that creates a payment, and a cURL sample taken from an unrelated export API. An integrator can't tell which part to trust. The fix: generate the mechanical parts (URL, method, schema) from OpenAPI and hand-write only the busi

The course's sample template carries two copy-paste leftovers: page/size parameters on a POST that creates a payment, and a cURL sample taken from an unrelated export API. An integrator can't tell which part to trust. The fix: generate the mechanical parts (URL, method, schema) from OpenAPI and hand-write only the business rules; run the cURL samples in CI (or generate them from tests, as Spring REST Docs does); review the docs in the same PR as the code.

Read in post: Advanced REST API design
TILMidSpring REST Docs generates documentation from tests, so it can't drift from the codespringdoc-openapi builds the spec from annotations, so the docs match what you declared. Spring REST Docs works the other way round: snippets come from MockMvc/WebTestClient tests that actually ran; a test fails if the docs describe a field that doesn't exist or miss one that does. You can combine them: restdocs-api-sp

springdoc-openapi builds the spec from annotations, so the docs match what you declared. Spring REST Docs works the other way round: snippets come from MockMvc/WebTestClient tests that actually ran; a test fails if the docs describe a field that doesn't exist or miss one that does. You can combine them: restdocs-api-spec produces OpenAPI from REST Docs tests.

Read in post: Advanced REST API design
InterviewJuniorWhy not use GET to create an export job?

Because GET must be safe: many things are allowed to repeat a GET, and each repeat would create another heavy job.

Crawlers, prefetching, link previews and automatic retries may all repeat a GET. Creating a job creates a resource, so use POST and return 202 Accepted with a Location header pointing at the job resource.

Read in post: Advanced REST API design
InterviewMidWhen do you return 202 Accepted instead of 201 Created?

201 when the resource was fully created within the request; 202 when the server has only accepted the request and will process it later.

201 comes with a Location pointing at the resource. 202 should carry a Location for the job resource so the client can track it, optionally with Retry-After. 202 makes no promise that the work will succeed.

Read in post: Advanced REST API design
InterviewMidWhat do 6-digit business error codes buy you, and what rules do they need?

The code tells you the error class at a glance (the first 3 digits are the HTTP status), but only if the prefix always matches the real status.

The last 3 digits are a business sequence number; type is a stable constant for clients to switch on. Rules: the prefix matches the real HTTP status, each code has exactly one meaning listed in the docs, and codes are never reused for something else. Check the prefix match with an automated test.

Read in post: Advanced REST API design
InterviewSeniorHow would you design an API that exports a file of several hundred MB?

As an async job: POST returns 202 + Location, a worker streams the data, the result is served through a presigned URL; never synchronously.

  • Synchronously you'd hit LB/gateway timeouts (often 60 seconds), run out of memory, and hold threads and connections for minutes.
  • The worker streams from the database (fetch size, server-side cursor, no List) and does a multipart upload to object storage.
  • The client polls with Retry-After or receives a webhook; it downloads through a time-limited presigned URL.
  • Dead workers: leases and bounded retries. Also cap concurrent jobs per tenant, check ownership on jobs, and clean up files with a lifecycle rule.
Read in post: Advanced REST API design
InterviewSeniorHow does a Stripe-style Idempotency-Key work?

The client sends one key per operation; the server stores the key with the first response and returns it verbatim on every retry.

  • The server stores (client, key) under a UNIQUE constraint, with a body hash, a status and the response.
  • First call: insert the key, do the work, store status + body.
  • Later calls with the same key: different body → 422, still in progress → 409 (or wait), completed → exactly the stored response.
  • Validation errors aren't stored so the client can fix them; infrastructure failures roll the key back. Keys expire after about 24 hours.
Read in post: Advanced REST API design
InterviewSeniorPolling, webhooks, SSE/WebSocket: how do you choose for job-completion notices?

Polling for low load and any client, webhooks for B2B and payments, SSE/WebSocket for UIs that need live progress; always keep the status API as the fallback.

  • Polling: simple, works for every client, wastes empty requests.
  • Webhooks: efficient and near real-time, but need a receiver with a public URL, HMAC signatures, retries with backoff and an idempotent receiver.
  • SSE/WebSocket: long-lived connections and fan-out of events across instances.
Read in post: Advanced REST API design
InterviewSeniorHow do you secure a webhook receiver?

Verify an HMAC signature over the raw body, block replays with a timestamp, dedupe on event_id, and for payments call the provider back to confirm.

  • Compare signatures in constant time; accept HTTPS only.
  • Deduplicate on event_id because the sender will retry.
  • Return 2xx fast and process asynchronously so you don't time out and trigger a resend.
  • For critical data, don't fully trust the webhook payload: call the provider's API to confirm the status.
Read in post: Advanced REST API design
InterviewSeniorWhat are the downsides of a meta/data response envelope?

It's non-standard, clients have to unwrap data everywhere, and it tends to lead to HTTP 200 even for errors.

200 for errors breaks retries, caching and status-based alerting. If you use one, the HTTP status must always be correct and the business code must match it. Problem Details (RFC 9457) is the standard choice for errors, with the business code in an extension field.

Read in post: Advanced REST API design
Trade-offMidNginx as a reverse proxy vs a full API gatewayNginx (or Caddy, HAProxy): light, fast, readable static config. Enough for TLS, path/host routing, compression, static caching and per-IP rate limits. Missing: JWT validation, per-API-key quotas, dynamic config over an API (open source needs a reload), dashboards. An API gateway (Kong, APISIX, Spring Cloud Gateway): pl
  • Nginx (or Caddy, HAProxy): light, fast, readable static config. Enough for TLS, path/host routing, compression, static caching and per-IP rate limits. Missing: JWT validation, per-API-key quotas, dynamic config over an API (open source needs a reload), dashboards.
  • An API gateway (Kong, APISIX, Spring Cloud Gateway): plugins for auth, quotas, header-based canaries, route changes without reloads. The cost: one more system to run (often with its own database or etcd), and one more place where business logic can creep in where it doesn't belong. How a canary splits traffic and which numbers tell you to stop it is in Deployment strategies.
  • Pick Nginx when the need is "one entry point, route by path, TLS". Pick a gateway when many teams and many external clients need auth, quotas and frequent route changes. Plenty of systems use both: cloud load balancer → Nginx ingress → services.
Read in post: Reverse proxying with Nginx
Edge caseMidlocation /api without a trailing slash also matches /apiv2 and /api-docsPrefix locations compare characters, not path segments: location /api also matches /apiv2, /api-internal and /apixyz. To catch only paths under /api/, write location /api/ (that's why /apiv2 falls through to the frontend in the lab). If you also need the bare /api, add location = /api { return 301 /api/; } or proxy it

Prefix locations compare characters, not path segments: location /api also matches /apiv2, /api-internal and /apixyz.

To catch only paths under /api/, write location /api/ (that's why /apiv2 falls through to the frontend in the lab). If you also need the bare /api, add location = /api { return 301 /api/; } or proxy it separately.

Read in post: Reverse proxying with Nginx
Edge caseMidA regex location can steal requests from a longer prefix locationRegexes are checked after the longest prefix is found, and a matching regex wins. With location /api/ { proxypass http://backend; } and, further down, location ~ \.(png|jpg|css)$ { root /var/www; }, the request /api/users/7/avatar.png is served from disk and never reaches the backend. Fix it with location ^~ /api/ so r

Regexes are checked after the longest prefix is found, and a matching regex wins. With location /api/ { proxy_pass http://backend; } and, further down, location ~* \.(png|jpg|css)$ { root /var/www; }, the request /api/users/7/avatar.png is served from disk and never reaches the backend.

Fix it with location ^~ /api/ so regexes can't override that prefix, or nest the regex inside the location that needs it.

Read in post: Reverse proxying with Nginx
Edge caseMidThe location and the proxy_pass URI must both have, or both lack, the trailing slashlocation /api { proxypass http://be:8080/; } turns /api/orders into //orders and /apiv2 into /v2. To strip the prefix, give both a slash: location /api/ { proxypass http://be:8080/; }. To keep the path, drop the URI entirely: proxypass http://be:8080;. In a regex location Nginx can't tell what to replace, so use proxyp

location /api { proxy_pass http://be:8080/; } turns /api/orders into //orders and /apiv2 into /v2.

  • To strip the prefix, give both a slash: location /api/ { proxy_pass http://be:8080/; }.
  • To keep the path, drop the URI entirely: proxy_pass http://be:8080;.
  • In a regex location Nginx can't tell what to replace, so use proxy_pass without a URI or build it with variables, such as http://fe:8000/static/$1.
Read in post: Reverse proxying with Nginx
Edge caseMidRedirects generated by Nginx use the port it listens on, not the one the client seesBehind a port mapping (8088:80) or a load balancer, Nginx's automatic redirects (adding the trailing slash, return 301 /path) build an absolute URL from the port and scheme Nginx sees, so the client is sent to http://host/... with the wrong port or scheme. Set absoluteredirect off; and Nginx sends a relative URL instea

Behind a port mapping (8088:80) or a load balancer, Nginx's automatic redirects (adding the trailing slash, return 301 /path) build an absolute URL from the port and scheme Nginx sees, so the client is sent to http://host/... with the wrong port or scheme.

Set absolute_redirect off; and Nginx sends a relative URL instead (I tested it: the result is Location: /blog/). For redirects generated by the backend, use proxy_redirect or make the backend read X-Forwarded-Host/X-Forwarded-Proto (section 6).

Read in post: Reverse proxying with Nginx
TILMidproxy_redirect default rewrites the backend's Location header for youproxyredirect default; is on unless you change it. With location /one/ { proxypass http://up:8080/two/; }, when the backend returns Location: http://up:8080/two/x, Nginx rewrites it to /one/x before sending it to the client. It only works when the URL in Location starts exactly with the proxypass value. If the backend

proxy_redirect default; is on unless you change it. With location /one/ { proxy_pass http://up:8080/two/; }, when the backend returns Location: http://up:8080/two/x, Nginx rewrites it to /one/x before sending it to the client.

It only works when the URL in Location starts exactly with the proxy_pass value. If the backend uses a different host name (taken from the Host header, say), you need your own proxy_redirect rule. default can't be used when proxy_pass contains variables.

Read in post: Reverse proxying with Nginx
Edge caseMidA proxy_set_header in a child location drops every header set at server levelproxysetheader is inherited from the parent level only when the current level has no proxysetheader of its own. If server sets Host, X-Forwarded-For and X-Forwarded-Proto, and location /ws/ adds only Upgrade, that location loses all the server-level headers: the backend is back to Host: be:8080 and no client IP. Avoid

proxy_set_header is inherited from the parent level only when the current level has no proxy_set_header of its own. If server sets Host, X-Forwarded-For and X-Forwarded-Proto, and location /ws/ adds only Upgrade, that location loses all the server-level headers: the backend is back to Host: be:8080 and no client IP.

Avoid it by putting the common headers in a file you include in every location that adds its own, or by repeating them in full.

Read in post: Reverse proxying with Nginx
Edge caseSeniorTaking the first X-Forwarded-For entry as the client IP lets clients pick their own IPA client can send any X-Forwarded-For it likes and proxies only append to the end, so the first entry is whatever the client put there. The trustworthy client IP is the first entry from the right that isn't one of your proxies. Nginx: setrealipfrom with realiprecursive on. Spring Boot: server.forward-headers-strategy=n

A client can send any X-Forwarded-For it likes and proxies only append to the end, so the first entry is whatever the client put there. The trustworthy client IP is the first entry from the right that isn't one of your proxies.

  • Nginx: set_real_ip_from with real_ip_recursive on.
  • Spring Boot: server.forward-headers-strategy=native (Tomcat's RemoteIpValve, which by default trusts only private ranges), with server.tomcat.remoteip.internal-proxies set to your load balancer's range.
  • At the outermost layer (the proxy facing the Internet), overwrite the header outright: proxy_set_header X-Forwarded-For $remote_addr;.
Read in post: Reverse proxying with Nginx
Edge caseSeniorNginx keeps a backend's old IP after the container or pod is recreatedThe name in upstream { server be:8080; } is resolved at start or reload. When the be container is recreated with a new IP, Nginx keeps sending to the old one and returns 502 until the next reload. Three fixes: Use a stable name (a Kubernetes Service with a fixed ClusterIP). Declare resolver 127.0.0.11 valid=10s; (Docke

The name in upstream { server be:8080; } is resolved at start or reload. When the be container is recreated with a new IP, Nginx keeps sending to the old one and returns 502 until the next reload. Three fixes:

  • Use a stable name (a Kubernetes Service with a fixed ClusterIP).
  • Declare resolver 127.0.0.11 valid=10s; (Docker's DNS) and put the host in a variable (set $be http://be:8080; proxy_pass $be;) so Nginx re-resolves per TTL.
  • Use the resolve parameter on server inside upstream (open source since 1.27.3; needs a zone in the upstream and a resolver; I ran upstream dyn { zone dyn 64k; server be:8080 resolve; } on 1.29.8).
Read in post: Reverse proxying with Nginx
Edge caseSeniorEnabling proxy_next_upstream ... non_idempotent can create an order twiceWhen a backend has received POST /orders, written to the database, and then times out while sending the response, Nginx can't know the request was processed. Allow retries of non-idempotent requests and it resends to another backend, and the order is created a second time. Only enable it when every write endpoint is id

When a backend has received POST /orders, written to the database, and then times out while sending the response, Nginx can't know the request was processed. Allow retries of non-idempotent requests and it resends to another backend, and the order is created a second time.

Only enable it when every write endpoint is idempotent through an Idempotency-Key or a unique constraint (see Idempotency part 1). Also cap proxy_next_upstream_tries and proxy_next_upstream_timeout (the default 0 means unlimited) so retries don't multiply the load when the whole cluster is already struggling.

Read in post: Reverse proxying with Nginx
Trade-offMidStrip the prefix at the proxy, or let the backend know its own prefixStrip at the proxy (location /blog/ { proxypass http://blog:9000/; }): the service runs at / just like in local development, and the public prefix can change without touching the service. Downside: absolute links and redirects the service generates (/posts/1, /login) lack the prefix, and clients wander off to the front
  • Strip at the proxy (location /blog/ { proxy_pass http://blog:9000/; }): the service runs at / just like in local development, and the public prefix can change without touching the service. Downside: absolute links and redirects the service generates (/posts/1, /login) lack the prefix, and clients wander off to the frontend. You patch that with proxy_redirect, sub_filter (fragile), or by sending X-Forwarded-Prefix and making the service read it (Spring's ForwardedHeaderFilter supports it).
  • Keep the prefix (location /api/ { proxy_pass http://backend; }, with Spring's server.servlet.context-path=/api or controllers mapped to /api/...): the service generates correct links and the proxy config stays simple. Downside: the prefix is baked into the service.
  • For APIs I keep the prefix (the path is part of the API contract). For web apps with HTML and redirects I also keep it, or give the app its own subdomain instead of a path.
Read in post: Reverse proxying with Nginx
InterviewJuniorHow is a reverse proxy different from a forward proxy?

A forward proxy sits on the client side and goes out on the client's behalf; a reverse proxy sits on the server side and takes requests in on behalf of the services.

With a forward proxy (a corporate proxy), the destination only sees the proxy. With a reverse proxy, clients only see one address. Reverse proxies terminate TLS, route by path or host, balance load, compress, cache, rate-limit and hide the internal layout.

Read in post: Reverse proxying with Nginx
InterviewJuniorWhy does a backend behind a proxy need X-Forwarded-For and X-Forwarded-Proto?

Because the connection to the backend comes from the proxy: the source IP is the proxy's, and the scheme is HTTP if TLS ended at the proxy.

Without these headers, logs and rate limits see only the proxy's IP, and links and redirects the app generates use the wrong http://. X-Forwarded-For carries the chain of IPs, X-Forwarded-Proto the scheme the client used.

Read in post: Reverse proxying with Nginx
InterviewMidWhat's the difference between location /api/ { proxy_pass http://be:8080; } and proxy_pass http://be:8080/;?

Without a URI the path is unchanged (/api/orders); with the URI / the part matching the location is replaced, so the backend gets /orders.

They have to go together: if the location ends in a slash, so must the URI, or you get //orders, or /apiv2 turning into /v2.

Read in post: Reverse proxying with Nginx
InterviewMidIn what order does Nginx choose a location?

It remembers the longest matching prefix, stops on an exact = match or if that prefix has ^~, then the first regex matching in file order wins; if none matches, it uses the remembered prefix.

The consequence: a regex catching .png can steal requests from location /api/.

Read in post: Reverse proxying with Nginx
InterviewMidWhat does upstream keepalive need, and why bother?

keepalive N in the upstream, proxy_http_version 1.1 and proxy_set_header Connection "", so connections are reused instead of opened per request.

Connection "" stops Nginx from sending Connection: close. You skip the TCP (and TLS, if any) handshake on every request, which cuts latency and avoids tens of thousands of TIME_WAIT sockets exhausting ports under load.

Read in post: Reverse proxying with Nginx
InterviewMidYou put SSE behind Nginx and clients receive events in big bursts. Why?

Because proxy_buffering is on by default, so Nginx collects the response in buffers before sending it.

Turn it off for that location (proxy_buffering off;) or have the backend send X-Accel-Buffering: no. Also raise proxy_read_timeout above the heartbeat interval so the connection isn't cut after 60 seconds.

Read in post: Reverse proxying with Nginx
InterviewSeniorHow do you get the real client IP through several layers of proxies?

Read X-Forwarded-For from right to left, skip the IPs that belong to your proxies; the first untrusted one is the client.

  • Never take the first entry, because the client controls it. The outermost layer should overwrite the header with $remote_addr.
  • Nginx: set_real_ip_from with real_ip_recursive on. Spring Boot: forward-headers-strategy=native and internal-proxies set to the load balancer's range.
  • Behind an L4 load balancer there are no HTTP headers, so use the PROXY protocol.
Read in post: Reverse proxying with Nginx
InterviewSeniorShould the proxy retry requests when a backend fails?

Connection errors before the request was sent are safe to retry; timeouts after sending are only safe for idempotent requests.

  • Nginx doesn't retry POST/PATCH by default because the backend may already have processed them.
  • Even for GET, cap the number of tries and the total retry time: when the whole cluster is overloaded, retries multiply the load and spread the outage.
  • Retries should live in one layer with backoff, not in the client, the gateway and the service all at once.
Read in post: Reverse proxying with Nginx
InterviewSeniorAfter redeploying a backend in Docker, Nginx returns 502 until it's reloaded. Explain and fix.

Open-source Nginx resolves upstream host names once at start or reload and keeps that IP; the new container has a different IP, so connections to the old one fail.

Fix: use a name with a stable IP (a Kubernetes Service), or a resolver plus a variable in proxy_pass so it re-resolves per TTL, or the resolve parameter in upstream (since 1.27.3). If you keep the static approach, add a reload to the deploy process.

Read in post: Reverse proxying with Nginx
InterviewSeniorWhen would you use an API gateway instead of Nginx?

When you need API-aware logic that's awkward in static Nginx config; if all you need is one entry point with TLS, path routing and per-IP rate limits, Nginx is simpler.

API-aware logic means JWT or API-key auth for partners, per-client quotas, header-based canaries, frequent route changes without reloads, many teams editing routes. Nginx has fewer moving parts. Either way, keep business logic out of the gateway.

Read in post: Reverse proxying with Nginx
Trade-offSeniorShard the RDBMS yourself, use middleware, or move to a self-sharding systemSharding in the application: full control, no extra infrastructure; but every query must carry the shard key, and resharding is a big project. Middleware (Vitess, Citus, ShardingSphere): routing and resharding come with tools; it's one more layer to run and understand deeply. Self-sharding systems (Cassandra, MongoDB,
  • Sharding in the application: full control, no extra infrastructure; but every query must carry the shard key, and resharding is a big project.
  • Middleware (Vitess, Citus, ShardingSphere): routing and resharding come with tools; it's one more layer to run and understand deeply.
  • Self-sharding systems (Cassandra, MongoDB, TiDB, DynamoDB): sharding is built in; in exchange you accept that system's data model and limits.
Read in post: Sharding in system design
Edge caseSeniorHashing still leaves hot keysHashing spreads keys evenly, not load. A celebrity with 100 million followers, a shop with 30% of the orders on a sale day: every request for that key still lands on one shard. To handle it: split the hot key into sub-keys (celeb:420..15), cache in front, or give the hot key its own shard through a directory.

Hashing spreads keys evenly, not load. A celebrity with 100 million followers, a shop with 30% of the orders on a sale day: every request for that key still lands on one shard. To handle it: split the hot key into sub-keys (celeb:42#0..#15), cache in front, or give the hot key its own shard through a directory.

Read in post: Sharding in system design
Edge caseMidThe database no longer guarantees global uniquenessA unique email on a user table sharded by userid: each shard checks only its own part, so two shards can accept the same email. You need a lookup table email → userid sharded by email (written first, with a unique constraint), or make email the shard key of that lookup table.

A unique email on a user table sharded by user_id: each shard checks only its own part, so two shards can accept the same email. You need a lookup table email → user_id sharded by email (written first, with a unique constraint), or make email the shard key of that lookup table.

Read in post: Sharding in system design
Trade-offSeniorDouble-writes from the application or copying with CDCDouble-write: the application writes to both old and new places during the move. Easy to understand, but the two writes aren't atomic, you need a reconciliation job, and it's easy to miss a write path. CDC (reading the database's change log): no application changes, no missed write paths; in exchange you need CDC infra
  • Double-write: the application writes to both old and new places during the move. Easy to understand, but the two writes aren't atomic, you need a reconciliation job, and it's easy to miss a write path.
  • CDC (reading the database's change log): no application changes, no missed write paths; in exchange you need CDC infrastructure and a moment of blocked writes at cutover.
  • If the system ships tooling (Vitess Reshard, Citus rebalance_table_shards), use the tooling.
Read in post: Sharding in system design
InterviewMidHow do partitioning and sharding differ?

Partitioning splits one table into pieces on the same server; sharding splits data across many servers.

Partitioning lets you read less and delete old data cheaply, but it doesn't raise write capacity beyond one machine. Sharding raises write capacity and storage, but you lose transactions, joins and global uniqueness.

Read in post: Sharding in system design
InterviewMidRange or hash sharding, which do you pick?

Hash by default, because it spreads data and load evenly; pick range when range queries dominate and load is spread evenly across the ranges.

Range by time almost always creates a hot spot on the newest range. Hash loses range queries across keys, so combine them: hash by entity, sort by time within the shard.

Read in post: Sharding in system design
InterviewMidWhat properties does a good shard key have?

It's the root entity of the main queries, it's small, it has many distinct values, and it doesn't change over time.

Example: user_id for orders. A user's order history sits on one shard, a bigint is small, there are millions of values, and a user never changes their id.

Read in post: Sharding in system design
InterviewSeniorHow would you shard the transaction table of a payment system?

Put off sharding as long as possible, because a transaction belongs to two accounts; when you must shard, switch to double-entry and shard each entry by its own account_id.

Each transaction produces two ledger_entry rows (debit, credit), each on its own account's shard, so every account's history is a single-shard query. The two writes are on two shards, so use a saga/outbox plus reconciliation, with an idempotency key per entry.

Read in post: Sharding in system design
InterviewSeniorYou have 8 shards with hash % 8 and need to go to 12. How?

Going from 8 to 12 with hash % N moves about 2/3 of the rows; switch to logical shards instead (say 1,024) and only move whole logical shards.

Steps: add a column/function that computes the logical shard, build a logical → physical map that matches the current 8 shards, then gradually move some logical shards to the 4 new machines with CDC, verify checksums, and cut over group by group with a few seconds of blocked writes.

Read in post: Sharding in system design
InterviewSeniorHow does Discord store messages so channel history reads are fast?

Partition by channel_id and sort within the partition by message_id, a Snowflake ID, so a channel's history is one sequential read on one node.

Very large channels make partitions too big, so they add a time bucket to the partition key (channel_id, bucket), where the bucket is a fixed window (for example 10 days). They moved from Cassandra to ScyllaDB because of GC and compaction latency.

Read in post: Sharding in system design
InterviewSeniorHow do you find orders by shop_id when the order table is sharded by user_id?

No scatter-gather on the API; keep a copy of the data keyed by shop_id (a side table sharded by shop_id, or an Elasticsearch index) updated asynchronously.

The source of truth is still the table sharded by user. The copy is updated through outbox/CDC → Kafka, accepts a few seconds of delay, and has a reconciliation job. Very large shops may need a secondary shard by (shop_id, month).

Read in post: Sharding in system design
Edge caseMid@ConditionalOnMissingBean in a regular @Configuration class is a gamble@ConditionalOnMissingBean is evaluated when bean definitions are registered, in the order classes are processed. For auto-configs, Boot guarantees they run after your configuration. For a regular @Configuration found by component scanning, that order isn't guaranteed: the condition may be checked before the "overriding

@ConditionalOnMissingBean is evaluated when bean definitions are registered, in the order classes are processed. For auto-configs, Boot guarantees they run after your configuration. For a regular @Configuration found by component scanning, that order isn't guaranteed: the condition may be checked before the "overriding" bean is registered, so both beans exist or the default wins.

Rule: use OnBean/OnMissingBean conditions only in @AutoConfiguration classes registered through the .imports file.

Read in post: Spring Boot from the inside
Edge caseMidBoth application.properties and application.yml in the same folderThe lab hit exactly this: an earlier run left both an application.yml (refresh TTL 3 days) and an application.properties (7 days). The app got 7 days, because in the same location .properties takes precedence over .yml. No error, just a "strange" value. Pick one format for the whole project and delete the other. When i

The lab hit exactly this: an earlier run left both an application.yml (refresh TTL 3 days) and an application.properties (7 days). The app got 7 days, because in the same location .properties takes precedence over .yml. No error, just a "strange" value.

Pick one format for the whole project and delete the other. When in doubt, check /actuator/env (mask secrets) to see which source a property came from.

Read in post: Spring Boot from the inside
Trade-offMidValidate config in the record constructor or with @ValidatedRecord constructor (the lab's way): no extra library, handles complex rules (the HS256 key must be at least 256 bits after Base64 decoding). @Validated + @NotBlank, @Min: concise declarations, consistent messages, needs spring-boot-starter-validation. Both give the result that matters most: fail fast at startup. An err
  • Record constructor (the lab's way): no extra library, handles complex rules (the HS256 key must be at least 256 bits after Base64 decoding).
  • @Validated + @NotBlank, @Min: concise declarations, consistent messages, needs spring-boot-starter-validation.

Both give the result that matters most: fail fast at startup. An error that waits for the first request is an error your users see.

Read in post: Spring Boot from the inside
Edge caseMidProduction secrets in application-prod.propertiesProfiles separate configuration, but application-prod.properties still sits in Git and inside the jar. Whoever can read the repo or the jar has the DB password. Read secrets from environment variables or a secret manager (Vault, AWS Secrets Manager, Kubernetes Secrets); the file only holds a placeholder: spring.datasou

Profiles separate configuration, but application-prod.properties still sits in Git and inside the jar. Whoever can read the repo or the jar has the DB password.

Read secrets from environment variables or a secret manager (Vault, AWS Secrets Manager, Kubernetes Secrets); the file only holds a placeholder: spring.datasource.password=${DB_PASSWORD}. The lab does this with JWT_SECRET; the default in the file is for dev only.

Read in post: Spring Boot from the inside
Edge caseMidFlyway "can't use Java code" and "only Liquibase can roll back"The course notes say Flyway only takes SQL/XML. In fact Flyway supports Java-based migrations (classes extending BaseJavaMigration), handy when you need logic such as hashing the initial admin password. On rollback: Liquibase has declarative rollback; Flyway has undo, but only in the paid edition. In practice many team

The course notes say Flyway only takes SQL/XML. In fact Flyway supports Java-based migrations (classes extending BaseJavaMigration), handy when you need logic such as hashing the initial admin password. On rollback: Liquibase has declarative rollback; Flyway has undo, but only in the paid edition. In practice many teams don't roll back at all and write a new migration that fixes forward.

One more thing the notes skip: data.sql plus ddl-auto without defer-datasource-initialization fails with "table not found", because the script runs before Hibernate creates the tables.

Read in post: Spring Boot from the inside
InterviewJuniorWhat does @SpringBootApplication consist of?

Three annotations: @SpringBootConfiguration, @ComponentScan (current package and sub-packages) and @EnableAutoConfiguration.

Because scanning starts at the main class's package, that class should sit in the root package. Beans outside that package tree won't be found.

Read in post: Spring Boot from the inside
InterviewJuniorHow do you change the port or turn off an auto-configuration?

Changing a property (server.port=9090) is the lightest way; to turn one off completely use exclude on @SpringBootApplication or spring.autoconfigure.exclude.

The middle ground is declaring a bean of the same type; the auto-config backs off thanks to @ConditionalOnMissingBean.

Read in post: Spring Boot from the inside
InterviewMidHow does auto-configuration work?

Boot reads @AutoConfiguration classes from the AutoConfiguration.imports files on the classpath, processes them after your configuration, and activates only those whose @Conditional... conditions match.

Typical conditions: a class on the classpath, a bean present or missing, a property value. Debug with --debug for the condition evaluation report, or /actuator/conditions.

Read in post: Spring Boot from the inside
InterviewMidA property is set in application.properties but the app sees a different value. What do you check?

The higher-priority sources: command-line args, environment variables, the active profile's file, files outside the jar, and a .properties/.yml pair in the same place.

Check the active profiles in the startup log and the property's source in /actuator/env. Remember relaxed binding: APP_JWT_SECRET overrides app.jwt.secret.

Read in post: Spring Boot from the inside
InterviewMidHow do @Value and @ConfigurationProperties differ, and which do you pick?

@Value reads single values; @ConfigurationProperties binds a whole group into a structured type with validation and IDE hints.

For several properties under one prefix, use @ConfigurationProperties (a record) and validate so the app dies at startup when config is missing or wrong.

Read in post: Spring Boot from the inside
InterviewMidWhen does a CommandLineRunner run, and how is it different from @PostConstruct?

A runner runs after the context has refreshed and the web server has started, before ApplicationReadyEvent; @PostConstruct runs right after one bean is created.

In @PostConstruct, other beans may not be ready and the transactional proxy may not wrap the bean itself yet, so work like seeding data belongs in a runner.

Read in post: Spring Boot from the inside
InterviewSeniorYou're writing an internal library shared by many services. How do you package it as an auto-configuration?

An auto-configure module with an @AutoConfiguration class registered via the .imports file, guarded by conditions and @ConditionalOnMissingBean on interfaces, plus a starter that only pulls dependencies.

  • Properties under their own prefix, bound with @ConfigurationProperties, with the configuration processor.
  • @ConditionalOnClass for parts that depend on optional libraries.
  • Tests with ApplicationContextRunner: default on, backs off for a custom bean, off by property, missing library.
Read in post: Spring Boot from the inside
InterviewSeniorHow does graceful shutdown work, and what else do you need for zero dropped requests during a deploy?

On SIGTERM the server stops accepting new requests, waits for in-flight ones within the phase timeout, then destroys beans; it's on by default since Boot 3.4.

For rolling deploys you also need: readiness switching to refusing traffic before shutdown, the load balancer removing the instance in time, a shutdown timeout longer than your longest request, and stopping with SIGTERM rather than SIGKILL.

Read in post: Spring Boot from the inside
TILMidThe mapping table is built once at startupThe course material describes step 2 as "the server scans all controllers to find a matching one". In reality Spring scans controllers once at startup and builds the URL → method table inside RequestMappingHandlerMapping; each request is just a lookup. The lab's table holds 18 handler methods. That's why two methods wi

The course material describes step 2 as "the server scans all controllers to find a matching one". In reality Spring scans controllers once at startup and builds the URL → method table inside RequestMappingHandlerMapping; each request is just a lookup. The lab's table holds 18 handler methods. That's why two methods with the same URL and HTTP method stop the application from starting (Ambiguous mapping) rather than failing at runtime.

Read in post: Spring MVC
Trade-offMidServer-side rendering or an SPA calling a REST APISSR (Spring MVC + Thymeleaf): one codebase, one deployment, SEO out of the box, fast first paint, simple security (session cookie + CSRF token in forms). The cost: rich interactions need extra JavaScript, every action reloads the page, the backend is hard to reuse for mobile. SPA + REST: smooth UI, separate frontend an
  • SSR (Spring MVC + Thymeleaf): one codebase, one deployment, SEO out of the box, fast first paint, simple security (session cookie + CSRF token in forms). The cost: rich interactions need extra JavaScript, every action reloads the page, the backend is hard to reuse for mobile.
  • SPA + REST: smooth UI, separate frontend and backend teams, the API serves mobile too. The cost: two codebases, CORS, token storage, SEO needs frontend-side SSR.
  • Internal admin tools, small shops, small teams: SSR. Products with a mobile app or a highly interactive UI: SPA + REST. Hybrids are fine: SSR pages plus a few JSON endpoints for AJAX (like an "add to cart" button).
Read in post: Spring MVC
TILMidA flash attribute lives for exactly one redirectThe model only lives for one request, so it is lost on redirect. RedirectAttributes.addFlashAttribute parks the value in the session; the next GET moves it into the model and deletes it. Plain addAttribute (no "Flash") puts the value in the URL (?message=...): visible in the address bar and written to logs. Flash attri

The model only lives for one request, so it is lost on redirect. RedirectAttributes.addFlashAttribute parks the value in the session; the next GET moves it into the model and deletes it. Plain addAttribute (no "Flash") puts the value in the URL (?message=...): visible in the address bar and written to logs. Flash attributes need a session, so they don't work for stateless APIs.

Read in post: Spring MVC
Edge caseMidDeleting or changing data through a GET linkThe labs in the course material delete a user through a separate GET page. GET must be safe: browsers prefetch links, crawlers follow them, and Spring's CSRF token isn't checked on GET. An <img src="/admin/users/7/delete" on another site is enough to delete data if deletion is a GET. The lab uses @PostMapping("/{id}/de

The labs in the course material delete a user through a separate GET page. GET must be safe: browsers prefetch links, crawlers follow them, and Spring's CSRF token isn't checked on GET. An <img src="/admin/users/7/delete"> on another site is enough to delete data if deletion is a GET.

The lab uses @PostMapping("/{id}/delete") inside a <form method="post">; Thymeleaf inserts the CSRF token automatically. The lab's test confirms it: GET returns 405, POST without the token returns 403, only POST with the token deletes.

Read in post: Spring MVC
Edge caseMidJSP inside a standalone jarThe Boot docs list JSP as a limitation: with jar packaging, JSPs don't work (the embedded container can't find a webapp folder inside the jar). From the IDE they do, because the IDE reads src/main/webapp directly, so the failure only appears on deployment. If you use JSP, set <packagingwar</packaging; that war still ru

The Boot docs list JSP as a limitation: with jar packaging, JSPs don't work (the embedded container can't find a webapp folder inside the jar). From the IDE they do, because the IDE reads src/main/webapp directly, so the failure only appears on deployment. If you use JSP, set <packaging>war</packaging>; that war still runs with java -jar, as in the experiment in section 8. New projects: use Thymeleaf.

Read in post: Spring MVC
Edge caseMidAdding @EnableWebMvc to a Spring Boot applicationThe course material creates a configuration class with @EnableWebMvc plus an InternalResourceViewResolver bean. In Spring Boot, @EnableWebMvc means "I'll configure MVC myself from scratch": WebMvcAutoConfiguration backs off. You lose serving files from classpath:/static, the spring.mvc. properties, and Boot's default c

The course material creates a configuration class with @EnableWebMvc plus an InternalResourceViewResolver bean. In Spring Boot, @EnableWebMvc means "I'll configure MVC myself from scratch": WebMvcAutoConfiguration backs off. You lose serving files from classpath:/static, the spring.mvc.* properties, and Boot's default converters and formatters.

Experiment on the lab: adding @EnableWebMvc to WebConfig turned GET /css/app.css from 200 into 404; Thymeleaf pages and Pageable kept working (they have their own auto-configuration), which makes the breakage easy to miss. To add configuration, just implements WebMvcConfigurer in a @Configuration class, without @EnableWebMvc.

Read in post: Spring MVC
Edge caseMidView names starting with "/" when Spring Security 6 is onRule: a view name is a path relative to the prefix and doesn't start with /. Thymeleaf doesn't forward, so it never meets the firewall, but it has its own trap. Experiment on the lab with return "/auth/login": The path templates//auth/login.html resolves in a folder but not inside a jar. Both variants of the bug only s

Rule: a view name is a path relative to the prefix and doesn't start with /. Thymeleaf doesn't forward, so it never meets the firewall, but it has its own trap. Experiment on the lab with return "/auth/login":

How it runs "/auth/login" "auth/login"
From the IDE (classpath is the target/classes folder) 200 200
java -jar fat jar 500 TemplateInputException: Error resolving template [/auth/login] 200

The path templates//auth/login.html resolves in a folder but not inside a jar. Both variants of the bug only show up after deployment. Write tests that assert view().name(...) and add a CI smoke test that runs the real jar.

Read in post: Spring MVC
InterviewJuniorHow do @Controller and @RestController differ?

@RestController is @Controller plus @ResponseBody: the return value is written straight into the body (usually JSON) instead of being treated as a view name.

@Controller is for server-rendered pages: the method returns "products/list" and a ViewResolver finds the template. The same DispatcherServlet handles both; they differ in the return value handler.

Read in post: Spring MVC
InterviewJuniorHow do redirect: and forward: differ?

forward: moves the request inside the server, the browser doesn't know and the URL stays; redirect: returns 302 and the browser sends a new GET to another URL.

A forward keeps the same request (attributes included); a redirect loses the model, so you use flash attributes. After a POST that changes data, redirect so F5 doesn't resubmit the form.

Read in post: Spring MVC
InterviewJuniorWhat is Post/Redirect/Get and what problem does it solve?

After a successful POST the server redirects to a GET page instead of rendering directly, so reloading the page doesn't resubmit the form.

If validation fails, don't redirect: render the form again with the errors. A "saved" message crosses the redirect as a flash attribute. PRG doesn't replace server-side duplicate protection.

Read in post: Spring MVC
InterviewMidDescribe the path of a request in Spring MVC.

Filters (Spring Security included) → DispatcherServlet → HandlerMapping finds the handler → HandlerAdapter invokes the method, argument resolvers build its parameters → return value handler → ViewResolver and View render, or an HttpMessageConverter writes JSON.

Exceptions along the way go through HandlerExceptionResolver, where @ControllerAdvice catches them. The mapping table is built at startup, so duplicate mappings stop the app from starting.

Read in post: Spring MVC
InterviewMidWhy shouldn't you add @EnableWebMvc to a Spring Boot application?

It tells Boot you're configuring MVC yourself, so WebMvcAutoConfiguration backs off: you lose static file serving, the spring.mvc.* properties and the default converters.

To add interceptors, resource handlers or formatters, implement WebMvcConfigurer in a plain @Configuration. In the experiment, the annotation turned /css/app.css into a 404 while pages kept working.

Read in post: Spring MVC
InterviewMidWhat are the limitations of JSP with Spring Boot?

JSPs don't work in an executable jar, so you need war packaging; you need Jasper and JSTL; rendering is a forward, so it passes through the filters again; ${} expressions don't escape HTML.

Thymeleaf is supported out of the box, runs from a jar, escapes by default, and its templates open in a browser. New projects should pick Thymeleaf or a separate frontend.

Read in post: Spring MVC
InterviewSeniorAfter upgrading to Spring Boot 3, the JSP login page fails with "malicious String //" or loops on redirects. How do you explain and fix it?

Spring Security 6 also authorizes FORWARD dispatches; JSPs render through a forward, and a view name with a leading / produces a // path that StrictHttpFirewall rejects.

Fix both: permit dispatcherTypeMatchers(FORWARD, ERROR) and drop the leading / from view names. Don't loosen the firewall (setAllowUrlEncodedDoubleSlash or a custom firewall), because // is a known trick for bypassing authorization rules. Add tests on view names to catch it before it reaches a real environment.

Read in post: Spring MVC
InterviewSeniorOne application has SSR pages and a REST API for mobile. How do you organise it?

Split by path (/api/**) with two SecurityFilterChains: form login + session + CSRF for pages, stateless bearer tokens for the API; page controllers and API controllers are separate classes sharing the same services.

Split error handling too: a @ControllerAdvice for pages that renders error views, another for /api that returns ProblemDetail. Give the API filter chain a higher @Order. Never return entities as JSON or to views; use DTOs on each side.

Read in post: Spring MVC
Edge caseJuniorDisabling Spring Security by excluding its auto-configuration"Temporarily turning security off" with @SpringBootApplication(exclude = SecurityAutoConfiguration.class) leaves every URL wide open, and when you switch it back on a pile of errors (403s from CSRF, blocked forwards) lands at once. Better: keep security on from day one, permitAll() what must be public, and write a test

"Temporarily turning security off" with @SpringBootApplication(exclude = SecurityAutoConfiguration.class) leaves every URL wide open, and when you switch it back on a pile of errors (403s from CSRF, blocked forwards) lands at once. Better: keep security on from day one, permitAll() what must be public, and write a test for each rule as you add endpoints.

Read in post: Form login with Spring Security
Edge caseMidsetHideUserNotFoundExceptions(false) reveals which emails are registeredThe course material declares its own DaoAuthenticationProvider with setHideUserNotFoundExceptions(false) to see "User not found" while debugging. The default is true: an unknown user raises the same BadCredentialsException as a wrong password. Turn it off and the login page (or whatever error reaches the client) can te

The course material declares its own DaoAuthenticationProvider with setHideUserNotFoundExceptions(false) to see "User not found" while debugging. The default is true: an unknown user raises the same BadCredentialsException as a wrong password. Turn it off and the login page (or whatever error reaches the client) can tell the two apart, so an attacker learns which emails have accounts (user enumeration) before guessing passwords.

The default provider also defends against timing: when the user isn't found it still runs BCrypt on a dummy password so response times match. The lab's wrongPasswordGoesToLoginError test checks that a wrong password and an unknown email both end at /login?error.

Read in post: Form login with Spring Security
TILMidYou don't need to declare an AuthenticationManager or DaoAuthenticationProviderThe course material builds an AuthenticationManager bean via http.getSharedObject(AuthenticationManagerBuilder.class) and adds a DaoAuthenticationProvider bean. With Spring Boot 3, one UserDetailsService bean and one PasswordEncoder bean are enough: Spring Security wires the provider. The lab's log says exactly that: G

The course material builds an AuthenticationManager bean via http.getSharedObject(AuthenticationManagerBuilder.class) and adds a DaoAuthenticationProvider bean. With Spring Boot 3, one UserDetailsService bean and one PasswordEncoder bean are enough: Spring Security wires the provider. The lab's log says exactly that: Global AuthenticationManager configured with UserDetailsService bean with name dbUserDetailsService. Declare them by hand only when you need several providers (LDAP plus database, say).

Read in post: Form login with Spring Security
Edge caseJuniorHard-coding ROLE_USER for everyone in loadUserByUsernameThe course's first version returns new User(email, password, singletonList(new SimpleGrantedAuthority("ROLEUSER"))) for every account, so the admin is just a USER. Authorities must come from data (a role column, a role table), and a test like "admin can open /admin, a user gets 403" keeps this kind of bug out.

The course's first version returns new User(email, password, singletonList(new SimpleGrantedAuthority("ROLE_USER"))) for every account, so the admin is just a USER. Authorities must come from data (a role column, a role table), and a test like "admin can open /admin, a user gets 403" keeps this kind of bug out.

Read in post: Form login with Spring Security
Edge caseMidThe "//" error and the redirect loop when rendering JSP after enabling Security 6The two errors the course hits when enabling Spring Security 6 with JSP share one root: Spring Security 6 also authorizes internal forward dispatches. Rendering a JSP is a forward to /WEB-INF/view/...jsp. Infinite loop: the JSP forward URL isn't in permitAll, so it triggers a login; the login page is a JSP too, so it t

The two errors the course hits when enabling Spring Security 6 with JSP share one root: Spring Security 6 also authorizes internal forward dispatches. Rendering a JSP is a forward to /WEB-INF/view/...jsp.

  • Infinite loop: the JSP forward URL isn't in permitAll, so it triggers a login; the login page is a JSP too, so it triggers another. Fix: .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll() as the first rule. ERROR is there so the /error page renders instead of a 401.
  • "malicious String //": the controller returns "/client/auth/login", the prefix is /WEB-INF/view/, giving /WEB-INF/view//client/auth/login.jsp. StrictHttpFirewall sees // in the forward path and rejects it. The course's advice "remove the extra slash" is the right fix; the cause is the firewall, not JSP.

Thymeleaf doesn't forward (it renders straight into the response), so the Thymeleaf lab doesn't hit either error. The JSP experiment that was actually run (302 without permitting FORWARD, 400 for "/auth/login", 200 for "auth/login") is in part 2.

Read in post: Form login with Spring Security
Edge caseMidAn anonymous AJAX call gets the login page's HTML instead of a 401With formLogin, a fetch from a logged-out user is also redirected with a 302 to /login; fetch follows the redirect and receives a 200 with HTML, so the JavaScript thinks it worked. I tried it in the lab: even with the X-Requested-With: XMLHttpRequest header the answer is a 302. The fix is a separate entry point for AJA

With formLogin, a fetch from a logged-out user is also redirected with a 302 to /login; fetch follows the redirect and receives a 200 with HTML, so the JavaScript thinks it worked. I tried it in the lab: even with the X-Requested-With: XMLHttpRequest header the answer is a 302.

The fix is a separate entry point for AJAX. The second trap I hit while trying it: declaring only one defaultAuthenticationEntryPointFor(...) makes it the default entry point for every request, so normal browser requests got a 401 too and two of the lab's redirect tests went red. Declare both, AJAX first:

.exceptionHandling(e -> e
    .accessDeniedPage("/access-denied")
    .defaultAuthenticationEntryPointFor(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED),
        new RequestHeaderRequestMatcher("X-Requested-With", "XMLHttpRequest"))
    .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"),
        AnyRequestMatcher.INSTANCE))
Read in post: Form login with Spring Security
Edge caseMidTaking the target URL from a request parameter opens a redirectA common variant: /login?redirect=... and a success handler doing sendRedirect(request.getParameter("redirect")). An attacker sends the victim https://shop.vn/login?redirect=https://shop-vn.evil/; after a real login the victim lands on the fake site. Use the saved request (stored by the server), or accept only relative

A common variant: /login?redirect=... and a success handler doing sendRedirect(request.getParameter("redirect")). An attacker sends the victim https://shop.vn/login?redirect=https://shop-vn.evil/; after a real login the victim lands on the fake site. Use the saved request (stored by the server), or accept only relative paths starting with a single /.

Read in post: Form login with Spring Security
Edge caseJuniorWebSecurityConfigurerAdapter is goneMany older tutorials extend WebSecurityConfigurerAdapter and override configure(HttpSecurity). It was deprecated in Spring Security 5.7 and removed in 6.0 (Spring Boot 3). The current style is a SecurityFilterChain bean with the lambda DSL; antMatchers/mvcMatchers became requestMatchers, and authorizeRequests became au

Many older tutorials extend WebSecurityConfigurerAdapter and override configure(HttpSecurity). It was deprecated in Spring Security 5.7 and removed in 6.0 (Spring Boot 3). The current style is a SecurityFilterChain bean with the lambda DSL; antMatchers/mvcMatchers became requestMatchers, and authorizeRequests became authorizeHttpRequests.

Read in post: Form login with Spring Security
InterviewJuniorWhere does Spring Security stop a request, relative to the controller?

At the servlet filter level, before the request reaches the DispatcherServlet, so a rejected request never touches a controller.

Tomcat calls DelegatingFilterProxy, which hands off to the FilterChainProxy bean. FilterChainProxy picks the first SecurityFilterChain matching the URL and runs its filters: CSRF, login, remember-me, authorization and so on.

Read in post: Form login with Spring Security
InterviewJuniorWhat's the difference between hasRole("ADMIN") and hasAuthority("ADMIN")?

hasRole("ADMIN") checks the authority ROLE_ADMIN (it adds the prefix); hasAuthority("ADMIN") checks the exact string ADMIN.

If UserDetails returns ROLE_ADMIN and the rule says hasAuthority("ADMIN"), the admin gets a 403. Convention: roles carry the ROLE_ prefix, fine-grained permissions (order:refund) use hasAuthority.

Read in post: Form login with Spring Security
InterviewJuniorWhy must logout be a POST?

Because logout changes state; if GET worked, an <img src="/logout"> on any other site could log users out.

With CSRF on, Spring Security only accepts POST /logout with a CSRF token by default. GET /logout goes straight to the DispatcherServlet and is usually a 404.

Read in post: Form login with Spring Security
InterviewMidWalk through the steps from clicking "Log in" to the next request being recognised.

Filter reads the form → ProviderManager → DaoAuthenticationProvider loads the user and checks the hash → session id changes → SecurityContext saved in the session → redirect; on the next request SecurityContextHolderFilter loads the context back from the session.

UsernamePasswordAuthenticationFilter builds an unauthenticated token. DaoAuthenticationProvider calls UserDetailsService and PasswordEncoder.matches and checks lock/expiry. On success, SessionAuthenticationStrategy changes the id and enforces session limits, SecurityContextRepository stores the SPRING_SECURITY_CONTEXT attribute, and the success handler redirects.

Read in post: Form login with Spring Security
InterviewMidWhat does a logged-out user get versus a user without permission, and who decides?

ExceptionTranslationFilter decides: not logged in goes through the AuthenticationEntryPoint (login redirect or 401), logged in but not allowed goes through the AccessDeniedHandler (403).

For web forms the entry point redirects to /login; for AJAX or APIs it should return 401. To have both, declare defaultAuthenticationEntryPointFor for each matcher, including an "any other request" one, otherwise the first entry point declared becomes the default for everything.

Read in post: Form login with Spring Security
InterviewMidYou enable Spring Security 6 and JSP pages go into a redirect loop. Why?

Because Spring Security 6 also authorizes forward dispatches; rendering a JSP is a forward to /WEB-INF/...jsp, which isn't permitted, so it triggers a login, and the login page is a JSP as well.

Fix: dispatcherTypeMatchers(FORWARD, ERROR).permitAll() at the top of the rules. The "malicious String //" error has the same root: a view name with a leading / plus the prefix produces //, which StrictHttpFirewall rejects.

Read in post: Form login with Spring Security
InterviewMidWhy shouldn't the principal be a JPA entity?

The principal lives in the SecurityContext, i.e. in the session, so it gets serialized; an entity brings lazy proxies, relationships and stale data, and it's heavy and fragile.

Use a small record (id, email, hash, role) implementing UserDetails. Controllers get the id via @AuthenticationPrincipal, and data that changes (name, avatar) is read from the database when needed.

Read in post: Form login with Spring Security
InterviewSeniorAssess the setting setHideUserNotFoundExceptions(false).

Don't use it: it separates "no such user" from "wrong password", which helps an attacker find out which emails have accounts.

By default Spring folds both into BadCredentialsException and even hashes a dummy password when the user is missing so the timing matches. For debugging, read server-side logs at DEBUG. Registration and password-reset pages must answer neutrally too, or they leak the same information.

Read in post: Form login with Spring Security
InterviewSeniorOne application serves a web form UI and a mobile API. How do you organise Spring Security?

Two SecurityFilterChains: a stateless /api/** chain with bearer tokens, CSRF off and JSON 401s; and a form-login chain with sessions and CSRF on for the rest.

Declare the API chain first with securityMatcher("/api/**"), because FilterChainProxy stops at the first match. Each chain has its own entry point and error handling. Test both, especially that the API doesn't quietly accept the session cookie (if it does, CSRF comes back).

Read in post: Form login with Spring Security
Edge caseMidFilterSecurityInterceptor is a thing of the pastThe course material describes the authorization step as FilterSecurityInterceptor. Since Spring Security 6, authorizeHttpRequests uses AuthorizationFilter with an AuthorizationManager; FilterSecurityInterceptor only remains for the old (deprecated) authorizeRequests. When you read debug logs or write custom rules, look

The course material describes the authorization step as FilterSecurityInterceptor. Since Spring Security 6, authorizeHttpRequests uses AuthorizationFilter with an AuthorizationManager; FilterSecurityInterceptor only remains for the old (deprecated) authorizeRequests. When you read debug logs or write custom rules, look for the new names.

Read in post: Spring Security for REST APIs
Trade-offSeniorDisabling CSRF: when it is safeCSRF abuses the browser sending cookies automatically. An access token in the Authorization header is never sent automatically, so turning CSRF off for this chain is reasonable. The /auth/refresh endpoint, however, takes the refresh token from a cookie. There the defences are SameSite=Strict, a narrow Path and CORS lim

CSRF abuses the browser sending cookies automatically. An access token in the Authorization header is never sent automatically, so turning CSRF off for this chain is reasonable.

The /auth/refresh endpoint, however, takes the refresh token from a cookie. There the defences are SameSite=Strict, a narrow Path and CORS limited to the SPA's origin (part 2). If you ever move the access token into a cookie, turn CSRF back on or check Origin.

Read in post: Spring Security for REST APIs
Edge caseJuniorA JWT is signed, not encryptedThe source says JWTs are "encrypted with HS256/RS256" and calls decoding "decryption". Wrong: a JWS is signed; header and payload are just Base64url that anyone can read. The signature prevents tampering, not reading. So never put passwords, card numbers or personal data into claims.

The source says JWTs are "encrypted with HS256/RS256" and calls decoding "decryption". Wrong: a JWS is signed; header and payload are just Base64url that anyone can read. The signature prevents tampering, not reading. So never put passwords, card numbers or personal data into claims.

Read in post: Spring Security for REST APIs
TILSeniorSpring Security 7 adds FACTOR_* authoritiesSince Security 7 (Boot 4), each way of authenticating adds a "factor" authority: password login gets FACTORPASSWORD, a request carrying a bearer token gets FACTORBEARER. They are the building blocks for MFA: a rule can require two factors. The practical consequence: if you dump getAuthorities() straight into the roles

Since Security 7 (Boot 4), each way of authenticating adds a "factor" authority: password login gets FACTOR_PASSWORD, a request carrying a bearer token gets FACTOR_BEARER. They are the building blocks for MFA: a rule can require two factors.

The practical consequence: if you dump getAuthorities() straight into the roles claim, the token contains FACTOR_PASSWORD and every permission based on that list is off. The lab filters for ROLE_ only.

Read in post: Spring Security for REST APIs
Edge caseJuniorauthentication.getEmail() does not existThe course's sample prompt tells the AI to use authentication.getEmail() as the subject. Authentication has no such method; the identity is getName() (here, the email, because UserDetails uses email as username). Code generated from that prompt won't compile, or worse, the AI "fixes" it by casting the principal arbitra

The course's sample prompt tells the AI to use authentication.getEmail() as the subject. Authentication has no such method; the identity is getName() (here, the email, because UserDetails uses email as username). Code generated from that prompt won't compile, or worse, the AI "fixes" it by casting the principal arbitrarily.

Read in post: Spring Security for REST APIs
Edge caseMidStuffing roles into the scope claimThe source's example uses "scope": "ADMIN USER" to ride on the default configuration. It works, but mixes two concepts. An OAuth2 scope is what a user delegates to a client (this app may read your calendar). A role is what the user may do in the system. Once you move to a real IdP, tokens carry both, and SCOPEADMIN get

The source's example uses "scope": "ADMIN USER" to ride on the default configuration. It works, but mixes two concepts. An OAuth2 scope is what a user delegates to a client (this app may read your calendar). A role is what the user may do in the system. Once you move to a real IdP, tokens carry both, and SCOPE_ADMIN gets confused with real scopes. Use a dedicated claim (roles) from day one.

Read in post: Spring Security for REST APIs
Edge caseMidKeeping the access token in localStorageThe source's login flow ends with "client saves the token to localStorage", right after advising against it. A single XSS bug lets a script read localStorage and ship the token away. The balanced approach: a 15-minute access token in a JS variable (lost on reload, so call /refresh), the refresh token in an HttpOnly coo

The source's login flow ends with "client saves the token to localStorage", right after advising against it. A single XSS bug lets a script read localStorage and ship the token away. The balanced approach: a 15-minute access token in a JS variable (lost on reload, so call /refresh), the refresh token in an HttpOnly cookie JS can't read. XSS can still call the API as the user while the page is open, but can't carry the token elsewhere.

Read in post: Spring Security for REST APIs
InterviewJuniorIs a JWT encrypted? Should the payload contain email or phone number?

No, a normal JWT (JWS) is only signed; the payload is Base64url anyone can read. Keep only minimal identity in it.

The signature prevents tampering, not reading. Email as sub is acceptable in an internal system, but never passwords, card numbers or sensitive personal data. To hide content, use JWE or an opaque token looked up on the server.

Read in post: Spring Security for REST APIs
InterviewJuniorWhat is the difference between 401 and 403 in Spring Security?

401: you could not be authenticated (no token, bad token, expired). 403: we know who you are, but you lack permission.

ExceptionTranslationFilter decides: an AuthenticationException goes to the AuthenticationEntryPoint (401); an AccessDeniedException for an authenticated user goes to the AccessDeniedHandler (403).

Read in post: Spring Security for REST APIs
InterviewMidWhy can an API using JWTs in a header disable CSRF?

Because CSRF relies on the browser attaching cookies automatically; the Authorization header is never sent automatically.

A malicious page can't read the token in the SPA's memory, so it can't forge the request. The condition is that no credential travels as a cookie on that chain. The refresh endpoint, which does use a cookie, is protected by SameSite=Strict, a narrow path and strict CORS.

Read in post: Spring Security for REST APIs
InterviewMidWhy doesn't @RestControllerAdvice catch an expired-token error?

Because the error happens in a security filter, before the DispatcherServlet; controller advice only sees exceptions thrown while MVC handles the request.

For a consistent format, install an AuthenticationEntryPoint and an AccessDeniedHandler that write ProblemDetail. Conversely, an AccessDeniedException from @PreAuthorize is thrown inside the controller call, so the advice does see it, and a catch-all handler can turn it into a 500.

Read in post: Spring Security for REST APIs
InterviewMidWhich claim does the default resource server configuration turn into authorities?

The scope (or scp) claim, split on spaces and prefixed with SCOPE_.

To use hasRole('ADMIN') with a roles claim, configure a JwtGrantedAuthoritiesConverter that reads roles with the ROLE_ prefix and plug it into a JwtAuthenticationConverter. Don't put roles into scope: scopes are what a user delegates to a client.

Read in post: Spring Security for REST APIs
InterviewSeniorWhen is a self-issued HS256 JWT enough, and when should you use an IdP?

One API with your own frontend: a self-issued HS256 token is enough. Many services, SSO, MFA or third parties: use an IdP with asymmetric keys.

With HS256, every verifier can also sign, so leaking the secret in one service compromises all of them. An IdP keeps the private key, services only need public keys via JWKS, and keys rotate by kid without redeploys. The price is one more system to run and a dependency at login time.

Read in post: Spring Security for REST APIs
InterviewSeniorA colleague puts all of getAuthorities() into the token's claims on Spring Security 7. What's wrong?

The token will contain FACTOR_PASSWORD (and possibly other non-role authorities), so claim-based permissions go wrong and the token carries noise.

Security 7 adds factor authorities for MFA. Select only what the token contract needs (here, roles without the ROLE_ prefix) and add a test asserting the claim content.

Read in post: Spring Security for REST APIs
InterviewSeniorList what a JwtDecoder must check in a production system.

The signature with a pinned algorithm, exp/nbf with a small clock skew, iss, aud, and the key length.

Never take the algorithm from the token header (alg: none or RS256-to-HS256 attacks). With JWKS, only accept keys from a trusted issuer. Add an automated test for each broken case.

Read in post: Spring Security for REST APIs
Edge caseJuniorThe default session is not "stored on the client in cookies"The course material says the default session is "stored on the client through cookies" and "stored in memory". Only the second half is right: the data sits in Tomcat's RAM and the cookie is just the id. That's why a server restart logs everyone out, and with two instances behind a load balancer a request landing on the

The course material says the default session is "stored on the client through cookies" and "stored in memory". Only the second half is right: the data sits in Tomcat's RAM and the cookie is just the id. That's why a server restart logs everyone out, and with two instances behind a load balancer a request landing on the other instance can't find the session. Spring Session fixes exactly those two problems.

Read in post: Sessions and remember-me in Spring
Edge caseMidinvalidSessionUrl("/logout?expired") points to a page that doesn't existThe course material configures invalidSessionUrl("/logout?expired"). That's a redirect, i.e. a GET, and LogoutFilter only handles POST. I tried GET /logout in the lab: 404. Point it to /login?expired and let the login page say "your session expired". One more thing: invalidSessionUrl also catches logged-out visitors ca

The course material configures invalidSessionUrl("/logout?expired"). That's a redirect, i.e. a GET, and LogoutFilter only handles POST. I tried GET /logout in the lab: 404. Point it to /login?expired and let the login page say "your session expired".

One more thing: invalidSessionUrl also catches logged-out visitors carrying an old cookie, so people just browsing products get pushed to the login page. Usually expiredUrl is enough, and the entry point handles the rest.

Read in post: Sessions and remember-me in Spring
Edge caseMid"Closing the browser deletes the cookie, so it's as safe as a banking app"The course material concludes this from the session cookie having no Max-Age. In practice Chrome and Firefox have "continue where you left off", which restores session cookies too, and phones almost never "close" the browser. What really limits a session is the server-side timeout (idle + absolute) and the logout butto

The course material concludes this from the session cookie having no Max-Age. In practice Chrome and Firefox have "continue where you left off", which restores session cookies too, and phones almost never "close" the browser. What really limits a session is the server-side timeout (idle + absolute) and the logout button. Banking apps also use short timeouts (5 to 10 minutes) and re-authentication for transactions.

Read in post: Sessions and remember-me in Spring
Edge caseSeniorAn in-memory SessionRegistry is wrong with two instances, and it needs events to learn a session diedThe default registry (SessionRegistryImpl) is an in-memory map. With two instances behind a load balancer each sees half the sessions, so "one session" becomes "one session per instance". Use SpringSessionBackedSessionRegistry, which asks the shared store through FindByIndexNameSessionRepository (find sessions by princ

The default registry (SessionRegistryImpl) is an in-memory map. With two instances behind a load balancer each sees half the sessions, so "one session" becomes "one session per instance". Use SpringSessionBackedSessionRegistry, which asks the shared store through FindByIndexNameSessionRepository (find sessions by principal name).

Without Spring Session, an in-memory registry needs an HttpSessionEventPublisher bean; without it the registry never learns that a session timed out or logged out, and with maxSessionsPreventsLogin(true) the user is locked out for good.

Read in post: Sessions and remember-me in Spring
Edge caseJuniorspring.session.store-type was removed in Spring Boot 3The course material sets spring.session.store-type=jdbc. That property was removed in Spring Boot 3.0: Boot picks the store from the dependencies on the classpath. With both Redis and JDBC present it uses a fixed order (Redis first); to change that, configure it yourself. Leaving the line in doesn't break anything, it

The course material sets spring.session.store-type=jdbc. That property was removed in Spring Boot 3.0: Boot picks the store from the dependencies on the classpath. With both Redis and JDBC present it uses a fixed order (Redis first); to change that, configure it yourself. Leaving the line in doesn't break anything, it only suggests it has an effect.

Read in post: Sessions and remember-me in Spring
TILSeniorWith SpringSessionRememberMeServices the SESSION cookie's Max-Age is practically infiniteI wrote a lab test expecting the SESSION cookie to have a Max-Age of 14 days, and it failed: the actual value was 2147483647 (Integer.MAXVALUE, about 68 years). Spring Session's DefaultCookieSerializer sets that when the request carries the remember-me flag. The real expiry is held by the server: the SPRINGSESSION row

I wrote a lab test expecting the SESSION cookie to have a Max-Age of 14 days, and it failed: the actual value was 2147483647 (Integer.MAX_VALUE, about 68 years). Spring Session's DefaultCookieSerializer sets that when the request carries the remember-me flag. The real expiry is held by the server: the SPRING_SESSION row has MAX_INACTIVE_INTERVAL = 1209600 (14 days), after which the cleanup job deletes it and the cookie points at nothing.

Lesson: don't test or reason about session lifetime from cookie attributes; the source of truth is the session store.

Read in post: Sessions and remember-me in Spring
Edge caseMidsetAlwaysRemember(true) makes the "Remember me" checkbox meaninglessThe course material copies the example rememberMeServices.setAlwaysRemember(true). With it, every login is remembered (30 days by default), including someone on a shared computer who didn't tick the box. Keep the default false and set a sensible setValiditySeconds; only then does the name="remember-me" checkbox matter.

The course material copies the example rememberMeServices.setAlwaysRemember(true). With it, every login is remembered (30 days by default), including someone on a shared computer who didn't tick the box. Keep the default false and set a sensible setValiditySeconds; only then does the name="remember-me" checkbox matter.

Read in post: Sessions and remember-me in Spring
InterviewJuniorWhat does a session cookie contain?

Only a random session id; the session data (who's logged in, authorities, CSRF token) lives on the server.

The browser sends the cookie on every request and the server uses the id to find the session in RAM, Redis or a database. That's why the cookie must be HttpOnly, Secure and SameSite, so the id can't be read or sent from another site.

Read in post: Sessions and remember-me in Spring
InterviewJuniorWhy does a server restart log users out, and how do you fix it?

Because by default the session lives in Tomcat's RAM; move it to an external store (Spring Session with JDBC or Redis) and restarts no longer lose it.

The external store also lets you run several instances behind a load balancer without sticky sessions.

Read in post: Sessions and remember-me in Spring
InterviewMidHow does maximumSessions(1) behave when the user logs in on a second device?

By default the old session is marked expired and kicked out on its next request; with maxSessionsPreventsLogin(true) the new login is rejected instead.

It relies on a SessionRegistry. One instance can use the in-memory registry (with HttpSessionEventPublisher); several instances need SpringSessionBackedSessionRegistry. Choosing true locks out anyone who forgot to log out elsewhere until the timeout.

Read in post: Sessions and remember-me in Spring
InterviewMidYou store an object in the session; it works locally but fails in an environment with Spring Session JDBC. Why?

An external store must serialize attributes to bytes; an object that isn't Serializable (or holds a field that isn't) makes the session write fail.

The real fix is to keep only small data such as ids or serializable DTOs in the session and read the rest from the database. Making the entity Serializable only treats the symptom: you still get lazy proxies, stale data, and InvalidClassException when the class changes between deploys.

Read in post: Sessions and remember-me in Spring
InterviewMidWhat's the difference between idle and absolute timeouts, and which does Spring support?

Idle expires after a period of inactivity (built in via spring.session.timeout); absolute expires a fixed time after creation even when active (not built in, you write it).

With only an idle timeout, a stolen session that is used continuously lives forever. An absolute timeout is a filter comparing the session's creation time with a limit and invalidating it.

Read in post: Sessions and remember-me in Spring
InterviewSeniorCompare Spring's three remember-me styles. Which do you pick?

Hashed cookie: simple but can't revoke one device. Persistent token: revocable per device and detects stolen cookies. Spring Session: extends the session itself, revocable, but loses the "remembered" versus "just typed the password" distinction.

If the app already uses Spring Session, the third is the neatest, plus your own "last re-authenticated" marker for sensitive actions. Without a shared session store and with higher security needs, use persistent tokens. The hashed cookie only suits small apps.

Read in post: Sessions and remember-me in Spring
InterviewSeniorA user changes their password. What must a session-based system do?

Invalidate the user's other sessions (except the current one) and all remember-me tokens, so whoever hijacked a session loses access immediately.

With Spring Session use FindByIndexNameSessionRepository.findByPrincipalName then deleteById; with persistent tokens delete the rows in persistent_logins; hashed cookies die on their own because the signature depends on the password hash. Log the event and notify the user by email.

Read in post: Sessions and remember-me in Spring
InterviewSeniorJDBC or Redis for Spring Session?

JDBC for moderate load and fewer moving parts; Redis for high request rates or a busy main database, because each request may write LAST_ACCESS_TIME.

JDBC: easy to query and backed up with the database, but adds write load and needs a cleanup job. Redis: under 1 ms and TTL-based expiry, but one more component to keep alive (if Redis dies, everyone is logged out). Either way, measure writes per request before deciding.

Read in post: Sessions and remember-me in Spring
Trade-offMidOptimize directly first, indirectly secondDirect (rewrite the query, add an index): small scope, easy to measure, easy to roll back, usually a single migration. The cost: every index slows down writes and takes space. Indirect (archive, partition, cache, replicas): works when the sheer volume of data is the problem. The cost: it changes the architecture, adds
  • Direct (rewrite the query, add an index): small scope, easy to measure, easy to roll back, usually a single migration. The cost: every index slows down writes and takes space.
  • Indirect (archive, partition, cache, replicas): works when the sheer volume of data is the problem. The cost: it changes the architecture, adds moving parts to operate and usually brings a data-consistency problem with it.
  • Rule: try the direct route first and measure with EXPLAIN ANALYZE. Only climb to the indirect route when the plan is already good and it's still slow because there's too much data or too much load.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseMidMySQL 8.0 removed the query cache entirelyMany older MySQL architecture diagrams show a "query cache" step before the parser: if the exact same SQL text had run before, the stored result came back. It was deprecated in 5.7.20 and removed in MySQL 8.0. Why: every write to a table invalidated that table's cached results, and its global mutex became a bottleneck

Many older MySQL architecture diagrams show a "query cache" step before the parser: if the exact same SQL text had run before, the stored result came back.

  • It was deprecated in 5.7.20 and removed in MySQL 8.0.
  • Why: every write to a table invalidated that table's cached results, and its global mutex became a bottleneck on multi-core machines.
  • Don't say in an interview that "MySQL caches query results for you". What MySQL still caches is data pages in the buffer pool.
  • Result caching belongs in the application (Redis, Caffeine) with an explicit invalidation strategy.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseJuniorRow filters placed in HAVING make the database group rows it will throw awaySELECT bookref, count() FROM tickets GROUP BY bookref HAVING bookref LIKE 'A%' returns the right answer. But logically all 3.1 million tickets get grouped before most groups are discarded. PostgreSQL usually pushes a condition that contains no aggregate down by itself, but not every database does that for every query.

SELECT book_ref, count(*) FROM tickets GROUP BY book_ref HAVING book_ref LIKE 'A%' returns the right answer. But logically all 3.1 million tickets get grouped before most groups are discarded.

PostgreSQL usually pushes a condition that contains no aggregate down by itself, but not every database does that for every query. Conditions on plain columns belong in WHERE; HAVING is for conditions on aggregates, such as count(*) > 3.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseMidStale statistics make the planner pick bad plansAfter importing millions of rows or deleting in bulk, autovacuum may not have run ANALYZE yet. The planner believes the table has 1,000 rows when it actually has 5 million, and picks a nested loop (for each row on one side, one lookup on the other) that runs millions of iterations. The symptom: estimated rows= off from

After importing millions of rows or deleting in bulk, autovacuum may not have run ANALYZE yet. The planner believes the table has 1,000 rows when it actually has 5 million, and picks a nested loop (for each row on one side, one lookup on the other) that runs millions of iterations.

The symptom: estimated rows= off from the actual count by tens or hundreds of times. The fix:

  • Run ANALYZE table_name at the end of every large load job.
  • Raise the statistics target (ALTER TABLE ... ALTER COLUMN ... SET STATISTICS 1000) for skewed columns.
  • Use CREATE STATISTICS when two columns are correlated (say city and zip_code), because by default the planner treats columns as independent and multiplies their selectivities.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Trade-offSeniorLowering random_page_cost on SSDsThe default randompagecost = 4 assumes a random read costs four times a sequential one, which fits spinning disks. On SSD/NVMe, and when the hot data sits in RAM, many systems use 1.1–1.5. Upside: the planner is willing to use an index scan for medium-sized ranges instead of a seq scan. Downside: set too low while data
  • The default random_page_cost = 4 assumes a random read costs four times a sequential one, which fits spinning disks. On SSD/NVMe, and when the hot data sits in RAM, many systems use 1.1–1.5.
  • Upside: the planner is willing to use an index scan for medium-sized ranges instead of a seq scan.
  • Downside: set too low while data isn't cached, and the planner picks the index for large ranges; in part 2, forcing an index scan over 94% of the table was about 7.5 times slower than the seq scan.
  • Change it at database or role level and re-measure the main queries before and after. Don't change planner settings to "fix" a single query.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseMidEXPLAIN ANALYZE really executes the statement, UPDATE and DELETE includedEXPLAIN ANALYZE DELETE FROM bookings WHERE bookdate < '2017-01-01' deletes real data. To see the actual plan of a write without changing anything, wrap it in a transaction: Even with the rollback, the statement holds its locks while it runs, generates WAL and dead tuples (dead rows waiting for cleanup), and fires trigg

EXPLAIN ANALYZE DELETE FROM bookings WHERE book_date < '2017-01-01' deletes real data. To see the actual plan of a write without changing anything, wrap it in a transaction:

BEGIN;
EXPLAIN (ANALYZE, BUFFERS) DELETE FROM bookings WHERE book_date < '2017-01-01';
ROLLBACK;

Even with the rollback, the statement holds its locks while it runs, generates WAL and dead tuples (dead rows waiting for cleanup), and fires triggers. In production, do it on a copy of the data or off-peak.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
TILSeniorA prepared statement can switch to a generic plan after five executionsThe PostgreSQL JDBC driver turns a PreparedStatement into a server-side prepared statement after prepareThreshold executions (default 5). On the server, after five custom plans (planned for the specific parameter values), PostgreSQL may switch to a generic plan shared by all values if its average cost doesn't look wors
  • The PostgreSQL JDBC driver turns a PreparedStatement into a server-side prepared statement after prepareThreshold executions (default 5).
  • On the server, after five custom plans (planned for the specific parameter values), PostgreSQL may switch to a generic plan shared by all values if its average cost doesn't look worse.
  • With skewed data (one status covering 95% of the table), the generic plan can be a disaster for the common value.
  • The symptom: a query that was fast at first suddenly gets slow although nobody changed anything.
  • Check with PREPARE + EXPLAIN EXECUTE. Fix with plan_cache_mode = force_custom_plan for the affected role or session.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseSeniorAn Index Only Scan still reads the heap when the visibility map is out of dateSeeing Index Only Scan doesn't mean the table wasn't touched; look at Heap Fetches. Experiment on bookings0: the very same plan read 1,820 pages right after 5,404 rows were updated, and only 58 pages after VACUUM (almost 10 times faster). VACUUM is what marks pages all-visible. For a write-heavy table that relies on a

Seeing Index Only Scan doesn't mean the table wasn't touched; look at Heap Fetches.

  • Experiment on bookings0: the very same plan read 1,820 pages right after 5,404 rows were updated, and only 58 pages after VACUUM (almost 10 times faster).
  • VACUUM is what marks pages all-visible.
  • For a write-heavy table that relies on a covering index, tune autovacuum for that table: a smaller autovacuum_vacuum_scale_factor; PostgreSQL 13+ adds autovacuum_vacuum_insert_scale_factor for insert-mostly tables.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseMidactual time and rows in a plan are per loop, not totalsA node showing Index Scan ... (actual time=0.031..0.032 rows=1 loops=37) doesn't cost 0.032 ms; it costs about 0.032 × 37 ≈ 1.2 ms and returns about 37 rows in total, not 1. Inside a nested loop with loops=100000, a harmless-looking "0.01 ms" is really one second. For parallel nodes, loops counts the leader and the wor

A node showing Index Scan ... (actual time=0.031..0.032 rows=1 loops=37) doesn't cost 0.032 ms; it costs about 0.032 × 37 ≈ 1.2 ms and returns about 37 rows in total, not 1.

  • Inside a nested loop with loops=100000, a harmless-looking "0.01 ms" is really one second.
  • For parallel nodes, loops counts the leader and the workers.
  • When hunting for the most expensive node, always multiply actual time by loops (explain.dalibo.com does the multiplication for you).
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseMidDon't trust ORM-generated SQL until you've seen its planThree Spring Data JPA examples: findByEmailIgnoreCase generates lower(email) = lower(?), which can't use a plain index on email. Fix it with an expression index on lower(email) or the citext type. @ManyToOne(fetch = EAGER) drags in extra joins. Page<T runs an extra count() for every page. Slice<T drops the count query.

Three Spring Data JPA examples:

  • findByEmailIgnoreCase generates lower(email) = lower(?), which can't use a plain index on email. Fix it with an expression index on lower(email) or the citext type.
  • @ManyToOne(fetch = EAGER) drags in extra joins.
  • Page<T> runs an extra count(*) for every page. Slice<T> drops the count query.

How to work: turn on SQL logging in dev (the org.hibernate.SQL logger), grab the real SQL with real parameters, run EXPLAIN (ANALYZE, BUFFERS) on production-sized data, and add a test that counts queries for the important flows.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
Trade-offSeniorFix statistics, force a plan, or fix the data when the planner misestimatesANALYZE: cheap and safe, the first reflex when estimated rows is far from actual after a bulk load. It can't fix misestimates caused by correlated columns or extreme skew. CREATE STATISTICS / a higher statistics target: fixes estimates for correlated or skewed columns; ANALYZE gets a bit slower. Forcing a plan (enablen
  • ANALYZE: cheap and safe, the first reflex when estimated rows is far from actual after a bulk load. It can't fix misestimates caused by correlated columns or extreme skew.
  • CREATE STATISTICS / a higher statistics target: fixes estimates for correlated or skewed columns; ANALYZE gets a bit slower.
  • Forcing a plan (enable_nestloop = off, pg_hint_plan, MySQL hints): a temporary painkiller that turns into tech debt once the data changes.
  • Fixing the data or the query (drop placeholders, give "hot" values their own path): the most work, but the only way to make sure the problem doesn't come back.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewJuniorWhat's the difference between EXPLAIN and EXPLAIN ANALYZE?

EXPLAIN only prints the expected plan and estimated costs without running the statement; EXPLAIN ANALYZE really runs it.

EXPLAIN ANALYZE adds real time, row counts and loop counts, so writes must be wrapped in BEGIN ... ROLLBACK. Add BUFFERS to see pages read from cache versus disk.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewJuniorWhy can't you use a SELECT alias in WHERE?

Because in the logical order WHERE is evaluated before SELECT, so the alias doesn't exist yet.

The logical order is FROM/JOIN → ON → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. ORDER BY comes after SELECT, so it can use the alias. The physical plan may differ from this order as long as the result is the same.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewJuniorIs a Seq Scan always a bad sign?

No. When you need most of the table, or the table is small, reading sequentially beats walking an index and jumping randomly into the table.

It's worrying when a Seq Scan on a large table returns very few rows compared with Rows Removed by Filter.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewMidHow do Index Scan, Index Only Scan and Bitmap Heap Scan differ?

They differ in how they touch the table: row by row, not at all, or grouped by page.

  • An Index Scan walks the index and fetches each row from the heap in index order; good for few rows or when order is needed.
  • An Index Only Scan answers from the index and reads the heap only for pages not marked all-visible.
  • A bitmap scan collects the pages to read into a bitmap and reads them in physical order; good for a medium number of rows and able to combine indexes, but it loses ordering.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewMidWhat do cost=0.43..8.45 and actual time=0.5..0.6 rows=1 loops=37 mean?

Cost is an estimate in abstract units; actual time and rows are real measurements for one loop.

Cost: 0.43 before the first row, 8.45 for the whole node including its children. Actual time is in ms per loop; the node ran 37 times, so it took about 22 ms in total and returned about 37 rows.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewMidWhy is a big gap between estimated and actual rows the most important signal in a plan?

Because every planner decision (scan type, join algorithm and order, parallelism) is based on row estimates.

An error at a low node spreads through the whole tree: expecting one row, the planner picks a nested loop, and 50,000 actual rows turn into 50,000 lookups. Fix it with ANALYZE, a higher statistics target, or CREATE STATISTICS.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewSeniorA query is fast in psql but slow from the Java application. What could be going on?

Usually a different plan (a generic plan, a parameter type cast), or the time isn't spent in the database at all.

  • The prepared statement switched to a generic plan that's bad for common values (check with EXPLAIN EXECUTE, try plan_cache_mode).
  • The parameter type differs from the column type, forcing a cast that disables the index.
  • The app pulls the whole result set into memory because of the fetch size.
  • The time is actually spent waiting for locks, waiting for a pooled connection, on the network or in ORM mapping.

Use auto_explain and tracing to tell them apart.

Read in post: How SQL runs and how to read a PostgreSQL execution plan
InterviewSeniorWould you turn off enable_seqscan or lower random_page_cost to make the planner use your index?

enable_seqscan = off: never in production. Lowering random_page_cost: yes on SSDs, and re-measure.

  • enable_seqscan = off is only for experiments, to see what the alternative plan costs.
  • Lowering random_page_cost to 1.1–1.5 is reasonable on SSDs with data in RAM; set it at database level and re-measure the main queries.
  • When the planner gets a single query wrong, the cause is usually a bad estimate or an index that doesn't match the query; fix that first.
Read in post: How SQL runs and how to read a PostgreSQL execution plan
Edge caseSeniorA cache that restarts empty can kill the database a second timeRestart Redis and reopen traffic straight away: the cache is empty, the hit rate is 0%, the whole load hits a database that has only just recovered, and it goes down again. Before reopening: reload from RDB/AOF, warm up the hot keys (taken from metrics or access logs), and ramp traffic up gradually (canary, increasing

Restart Redis and reopen traffic straight away: the cache is empty, the hit rate is 0%, the whole load hits a database that has only just recovered, and it goes down again. Before reopening: reload from RDB/AOF, warm up the hot keys (taken from metrics or access logs), and ramp traffic up gradually (canary, increasing percentages) while a bulkhead caps cache-miss queries to the database.

Read in post: Cache failures
Edge caseSeniorTtlFunction gets value = null under @Cacheable(sync = true) on RedisIn Spring Data Redis 3.4, RedisCache.put passes the real value to the TtlFunction, but the get(key, valueLoader) path that @Cacheable(sync = true) uses passes null. A TTL function that depends on the value ("short TTL for null") gives every entry loaded through sync = true the null-branch TTL. Pure jitter is unaffected

In Spring Data Redis 3.4, RedisCache.put passes the real value to the TtlFunction, but the get(key, valueLoader) path that @Cacheable(sync = true) uses passes null. A TTL function that depends on the value ("short TTL for null") gives every entry loaded through sync = true the null-branch TTL. Pure jitter is unaffected. Write a test against the exact version you run before relying on this behaviour.

Read in post: Cache failures
Trade-offSeniorBackground refresh, mutex, single-flight or probabilistic early expiryNo TTL + background refresh: never a miss; costs a job, and you must know which keys are hot. Good for a small, stable set (home page, config). Mutex in Redis: works across the whole cluster; but other requests wait or get stale data, and every miss pays an extra round-trip for the lock. Single-flight in the JVM (Caffe
  • No TTL + background refresh: never a miss; costs a job, and you must know which keys are hot. Good for a small, stable set (home page, config).
  • Mutex in Redis: works across the whole cluster; but other requests wait or get stale data, and every miss pays an extra round-trip for the lock.
  • Single-flight in the JVM (Caffeine get(key, loader)): no infrastructure, practically free; but per instance, so 50 pods still means 50 loads.
  • XFetch: no lock, no waiting; a few requests reload early, and you store delta and the expiry time next to the value.
  • Usually combined: single-flight always on, plus background refresh or a mutex for the few truly hot keys.
Read in post: Cache failures
Edge caseSenior@Cacheable(sync = true) doesn't prevent a stampede across instancessync = true only means "call cache.get(key, loader)"; whether that prevents a stampede depends on the cache underneath. Caffeine: per-key single-flight, but only inside one JVM. RedisCacheManager (Spring Data Redis 3.x): the default (non-locking) writer synchronizes nothing; the locking writer (RedisCacheWriter.locking

sync = true only means "call cache.get(key, loader)"; whether that prevents a stampede depends on the cache underneath. Caffeine: per-key single-flight, but only inside one JVM. RedisCacheManager (Spring Data Redis 3.x): the default (non-locking) writer synchronizes nothing; the locking writer (RedisCacheWriter.lockingRedisCacheWriter) locks per cache name (<cacheName>~lock), serializing every write to that cache rather than locking per key. For hot keys across many pods, build a per-key mutex or a background refresh yourself.

Read in post: Cache failures
Trade-offSeniorCaching empty values or a Bloom filterCaching empty values: simple, and self-correcting when the record is created later (it shows up after the short TTL). But every junk id takes a key: 10 million different ids means 10 million junk keys, and the first request for each still reaches the database. Bloom filter: blocks an entire space of random ids with fix
  • Caching empty values: simple, and self-correcting when the record is created later (it shows up after the short TTL). But every junk id takes a key: 10 million different ids means 10 million junk keys, and the first request for each still reaches the database.
  • Bloom filter: blocks an entire space of random ids with fixed memory. But it must be fully loaded from the database, updated on every insert, it can't delete elements (you need a counting Bloom filter or periodic rebuilds), and about 1% of junk requests still get through.
  • Usually all three: validation stops obvious junk, the Bloom filter stops random ids, and short-lived empty entries absorb what slips through.
Read in post: Cache failures
Edge caseSeniordisableCachingNullValues() opens the door to penetrationThe course's sample Redis cache config uses RedisCacheConfiguration...disableCachingNullValues(). A @Cacheable method returning null then makes RedisCache.put throw IllegalArgumentException ("does not allow 'null' values"), so people add unless = "result == null", and every non-existent id hits the database every time.

The course's sample Redis cache config uses RedisCacheConfiguration...disableCachingNullValues(). A @Cacheable method returning null then makes RedisCache.put throw IllegalArgumentException ("does not allow 'null' values"), so people add unless = "#result == null", and every non-existent id hits the database every time. If an endpoint takes arbitrary ids, allow null caching (Spring stores a NullValue sentinel) with a short TTL, or block with a Bloom filter or validation.

Read in post: Cache failures
TILSeniorRedis 6 has client-side caching with invalidation messagesSince Redis 6, a client can enable CLIENT TRACKING (over RESP3): Redis remembers which keys a client has read and sends an invalidation message when one of them changes. The client keeps a copy in memory and drops it only when told to, so a hot-key local cache no longer has to choose between a long TTL (stale) and a sh

Since Redis 6, a client can enable CLIENT TRACKING (over RESP3): Redis remembers which keys a client has read and sends an invalidation message when one of them changes. The client keeps a copy in memory and drops it only when told to, so a hot-key local cache no longer has to choose between a long TTL (stale) and a short one (many misses). Lettuce supports it through ClientSideCaching. The cost: Redis spends memory on the tracking table, and on disconnect the client must drop its whole local copy.

Read in post: Cache failures
Edge caseSeniorDEL on a big key blocks Redis; use UNLINKDEL on a hash or list with millions of elements frees memory synchronously on the main thread, blocking Redis for hundreds of milliseconds to seconds. UNLINK (Redis 4+) removes the key from the keyspace immediately and frees the memory on a background thread. Also enable lazyfree-lazy-eviction, lazyfree-lazy-expire and

DEL on a hash or list with millions of elements frees memory synchronously on the main thread, blocking Redis for hundreds of milliseconds to seconds. UNLINK (Redis 4+) removes the key from the keyspace immediately and frees the memory on a background thread. Also enable lazyfree-lazy-eviction, lazyfree-lazy-expire and lazyfree-lazy-user-del so evictions, expiries and DEL free memory in the background too (Redis 6.2+ adds lazyfree-lazy-user-flush for FLUSHALL).

Read in post: Cache failures
Edge caseSeniorvolatile-* with keys that have no TTL ends in OOM errorsvolatile- only evicts keys with a TTL. If most keys have none (sessions missing EX, "never-expiring" hot keys), Redis finds nothing to evict and behaves like noeviction: every write returns OOM command not allowed, cache-aside can't populate, and the hit rate collapses. Use allkeys-lru/allkeys-lfu for a pure cache; mov

volatile-* only evicts keys with a TTL. If most keys have none (sessions missing EX, "never-expiring" hot keys), Redis finds nothing to evict and behaves like noeviction: every write returns OOM command not allowed, cache-aside can't populate, and the hit rate collapses. Use allkeys-lru/allkeys-lfu for a pure cache; move Redis used as a data store (sessions, locks, queues) to a separate instance with noeviction.

Read in post: Cache failures
InterviewMidHow do cache avalanche, breakdown and penetration differ?

Avalanche is many keys (or the whole cache) gone at once, breakdown is one hot key expiring, penetration is a key that exists nowhere.

Avalanche: the cache goes down or a huge number of keys expire together, and load spills onto the database broadly. Breakdown: one hot key expires, and thousands of requests miss and reload it at once. Penetration: keys that exist neither in the cache nor in the database, so they always go through to the database. Fix them with HA + jitter + database protection; background refresh/mutex/single-flight; and null caching + validation + Bloom filters, respectively.

Read in post: Cache failures
InterviewMidWhat is a Bloom filter and where does it fit in caching?

A probabilistic structure that answers "definitely absent" or "possibly present"; it sits in front of the cache to stop penetration.

A bit array plus k hash functions. Adding an element sets k bits; checking it says "definitely absent" if any bit is unset and "possibly present" if all are set. No false negatives, false positives at a chosen rate, and no deletion. Ids that definitely don't exist get an immediate 404. A million ids at a 1% false-positive rate take only about 1.2 MB.

Read in post: Cache failures
InterviewSeniorA hot key expires and overloads the database. Which fix do you pick?

Single-flight in the JVM always on, plus background refresh or a per-key Redis mutex for the few truly hot keys.

Single-flight (Caffeine get(key, loader)) only collapses loads within one pod. For the few truly hot keys: no TTL plus background refresh, or stale-while-revalidate (refreshAfterWrite) so requests never wait. To limit loads across the whole cluster: a per-key mutex in Redis (SET NX PX with a token), with other requests serving the old value or waiting briefly. XFetch if you want no locks at all. Add a bulkhead to cap concurrent reloads hitting the database.

Read in post: Cache failures
InterviewSeniorWhat are the downsides of caching nulls to stop penetration?

Every junk id costs a key, and a record created later can be reported missing until the TTL runs out.

An attacker using random ids can fill memory, and the first request for each id still reaches the database. The TTL must be short, or a record created later is reported missing until it expires. In Spring, disableCachingNullValues() plus unless = "#result == null" turns this protection off entirely. Combine it with validation and a Bloom filter.

Read in post: Cache failures
InterviewSeniorA hot key on Redis Cluster: why doesn't adding nodes help, and what do you do?

A key belongs to one slot and a slot lives on one node, so its traffic still hits one node; fix it with a local cache or key replication.

Fixes: a short-TTL local cache on each instance (or Redis 6 client-side caching with invalidation), replicating the key into N suffixed copies spread across slots (and deleting all N on invalidation), or reading from replicas if lagging data is acceptable. Detect it with --hotkeys under an LFU policy or with client-side metrics.

Read in post: Cache failures
InterviewSeniorWhat problems do big keys cause and how do you deal with them?

A multi-MB value blocks Redis's single command thread and eats bandwidth; split it, compress it, move it to another store, and delete it with UNLINK.

Commands get slow and block everything else, partial updates force whole-value rewrites, and reloads are slow. Deal with it by compressing, splitting into several keys or hash fields, using a longer TTL, enforcing size limits in review and alerts, and moving large files to object storage. Find them with --bigkeys/--memkeys; delete them with UNLINK instead of DEL.

Read in post: Cache failures
InterviewSeniorHow do LRU, LFU and W-TinyLFU differ, and which policy would you pick in Redis?

LRU goes by recency, LFU by frequency, W-TinyLFU combines both; a pure-cache Redis uses allkeys-lru or allkeys-lfu.

LRU evicts the key read longest ago, but one scan can flush hot keys. LFU evicts the least frequently read key and needs counter decay so once-hot keys don't stay forever. W-TinyLFU (Caffeine): a small LRU window for new keys and a frequency sketch that decides whether a newcomer gets into the main area. Redis uses sampled, approximated LRU/LFU; the default noeviction only makes sense when Redis is a data store.

Read in post: Cache failures
InterviewSeniorYour Redis cache cluster dies at peak traffic. How should the system behave?

Errors must come back fast and a bulkhead must shield the database; when Redis returns, warm it up first and ramp traffic back.

Short client timeouts, an open circuit breaker, no hanging threads. The cache-miss path to the database goes through a bulkhead or rate limit, and anything above it fails fast or returns degraded data (empty lists, defaults) for non-essential features. An L1 local cache carries the hottest data. When Redis recovers: reload from persistence or warm up hot keys first, then ramp traffic back. Long term: Sentinel or Cluster with replicas, and a load test of the "Redis is down" scenario to know how much the database can actually take.

Read in post: Cache failures
Trade-offSeniorHow much documentation is enoughToo little (just code and a README): decisions get forgotten, old debates return every quarter, newcomers break constraints they never knew about. Too much (80 pages describing every class): nobody reads it, nobody updates it, and wrong docs are worse than none because readers trust them. The balance: record what is du
  • Too little (just code and a README): decisions get forgotten, old debates return every quarter, newcomers break constraints they never knew about.
  • Too much (80 pages describing every class): nobody reads it, nobody updates it, and wrong docs are worse than none because readers trust them.
  • The balance: record what is durable and can't be derived from code (goals, constraints, context, boundaries, ADRs, quality requirements, risks). Leave whatever changes with every commit (classes, fields) to the code and generated tooling. Apply (Cx − Cy) > Cmd per section.
Read in post: Architecture docs part 1
TILMidarc42 doesn't require you to fill in all 12 sectionsarc42 is a checklist so you don't forget things, not a form to complete. Its authors encourage dropping sections that add no value, starting lean and filling in over time. The biggest win: every document in the company has the same structure, so readers know decisions always live in section 9 and risks in section 11.

arc42 is a checklist so you don't forget things, not a form to complete. Its authors encourage dropping sections that add no value, starting lean and filling in over time. The biggest win: every document in the company has the same structure, so readers know decisions always live in section 9 and risks in section 11.

Read in post: Architecture docs part 1
Edge caseMidNumbering diagrams C0–C4 muddles the C4 model's levelsThe course template calls the context diagram "C0/C1", then C2 (container), C3 (component), C4 (code). That numbering is misleading: the "C4" in the model's name means four Cs (Context, Containers, Components, Code), not "level 4", and the levels are numbered 1–4. There is no "level 0"; the closest thing is the System

The course template calls the context diagram "C0/C1", then C2 (container), C3 (component), C4 (code). That numbering is misleading: the "C4" in the model's name means four Cs (Context, Containers, Components, Code), not "level 4", and the levels are numbered 1–4.

There is no "level 0"; the closest thing is the System Landscape diagram, a supplementary diagram showing many of the company's systems. In docs, refer to levels by name (Context, Container, Component) so nobody has to guess.

Read in post: Architecture docs part 1
Edge caseMidA deployment view that hides where staging differs from productionThe two most common sources of "works in staging, dies in prod": External dependencies: staging calls a mock or sandbox with generous timeouts, prod calls the real endpoint with an 800 ms timeout. Data: staging has a few thousand rows, prod has tens of millions, so query plans look completely different. Spell out each

The two most common sources of "works in staging, dies in prod":

  • External dependencies: staging calls a mock or sandbox with generous timeouts, prod calls the real endpoint with an 800 ms timeout.
  • Data: staging has a few thousand rows, prod has tens of millions, so query plans look completely different.

Spell out each such difference, along with instance counts and HA setup, so reviewers know what a staging test tells them about prod.

Read in post: Architecture docs part 1
Trade-offMidText-based diagrams (diagram-as-code) vs drag-and-drop toolsText (Mermaid, PlantUML, Structurizr DSL): diffable in PRs, changed in the same commit as the code, no "master file" on someone's laptop. Structurizr generates several C4 views from one model, so the diagrams never contradict each other. Cons: automatic layout is sometimes ugly, and polished presentation diagrams are h
  • Text (Mermaid, PlantUML, Structurizr DSL): diffable in PRs, changed in the same commit as the code, no "master file" on someone's laptop. Structurizr generates several C4 views from one model, so the diagrams never contradict each other. Cons: automatic layout is sometimes ugly, and polished presentation diagrams are hard.
  • Drag-and-drop (draw.io, Excalidraw, Figma): pretty and fast for workshops and slides. Cons: binary or XML files are hard to review, each diagram is a separate drawing so they drift apart, and usually nobody updates them.
  • Use text for diagrams that live in the docs; use drag-and-drop for discussions, then move the outcome into text. (draw.io's .drawio.svg files in the repo are a middle ground.)
Read in post: Architecture docs part 1
InterviewJuniorWhat is arc42 and what is it for?

An open-source template for architecture documentation with 12 sections, so that every document shares the same structure.

The 12 sections: goals, constraints, context, solution strategy, building blocks, runtime, deployment, crosscutting concepts, decisions, quality requirements, risks, glossary. You don't have to fill in every one; the main value is that readers know where to look.

Read in post: Architecture docs part 1
InterviewJuniorWhat are the levels of the C4 model?

System Context, Container, Component and Code; each level zooms into part of the one above.

Context: the system as one box with its users and external systems. Container: deployable units such as apps, services, databases, queues. Component: modules inside one container. Code: classes, tables; rarely worth drawing by hand.

Read in post: Architecture docs part 1
InterviewMidHow does a runtime view differ from a building block view?

The building block view is the static structure (what exists, how it depends on what); the runtime view shows how the pieces cooperate in each scenario.

The runtime view is usually a sequence diagram, including error and timeout paths. Many problems (chains of synchronous calls, missing idempotency, fail-open vs fail-closed) only become visible there.

Read in post: Architecture docs part 1
InterviewMidWhat makes a good architecture diagram?

A reader understands it without the author explaining it.

It stays at one zoom level; every box has a name, technology and responsibility; every arrow is labelled with what it does and over which protocol; there's a legend for shapes and colours; and your own system is clearly distinguished from external ones.

Read in post: Architecture docs part 1
InterviewSeniorHow do you keep architecture documentation from going stale?

Docs-as-code: docs and text-based diagrams in the repo, reviewed in the same PR as the code, with only the durable parts written by hand.

  • CI builds the docs and checks links.
  • Hand-write goals, constraints, decisions and quality requirements; generate the mechanical parts (API spec, ERD) from code.
  • Put ADRs and doc updates on the review checklist.
  • Enforce architecture rules with tests (ArchUnit) so the component diagram is executed, not just hoped for.
  • Give docs an owner and a review date.
Read in post: Architecture docs part 1
InterviewSeniorWhen should you not write architecture documentation?

When writing and maintaining it costs more than it saves.

For example: an internal script with few users, a throwaway prototype, or anything that changes with every commit and is already clear from the code. Even for small systems, though, a few-line ADR for a hard-to-reverse decision (the database, service boundaries, the money data model) is almost always worth it.

Read in post: Architecture docs part 1
Trade-offSeniormTLS or HMAC request signing for backend-to-backend APIsmTLS: no change to business code, the private key never leaves the client, revocation goes through the CA. But it only protects each TLS hop: behind a load balancer that terminates TLS, the app has to trust a header the proxy adds. Running a CA and rotating certificates takes effort. Request signing: the signature trav
  • mTLS: no change to business code, the private key never leaves the client, revocation goes through the CA. But it only protects each TLS hop: behind a load balancer that terminates TLS, the app has to trust a header the proxy adds. Running a CA and rotating certificates takes effort.
  • Request signing: the signature travels with the content end to end, survives proxies and can be stored as evidence. In exchange both sides must agree on how to canonicalize the signed string, and you build replay protection yourself.
  • Financial partners often require both. Inside a cluster, a service mesh that issues mTLS automatically is the cheapest option.
Read in post: Web attacks and the OWASP Top 10
Edge caseSeniorRecording the nonce before checking the signature lets an attacker burn other clients' noncesRecord the nonce before verifying the signature, and an attacker can send junk requests carrying the nonce a real client is about to use, so the real request gets rejected. The right order: check the timestamp (cheap), verify the signature with a constant-time comparison, and only then record the nonce atomically (putI

Record the nonce before verifying the signature, and an attacker can send junk requests carrying the nonce a real client is about to use, so the real request gets rejected. The right order: check the timestamp (cheap), verify the signature with a constant-time comparison, and only then record the nonce atomically (putIfAbsent, SET NX).

Read in post: Web attacks and the OWASP Top 10
Edge caseMidColumn names and sort direction can't be bound as parameters? only replaces a value, not an identifier (column, table) or a keyword (ASC/DESC). So sort often gets pasted straight into ORDER BY: where injection survives longest in code that "already uses PreparedStatement everywhere". The fix: an allowlist (name → username, created → createdat), unknown values get a 400, and onl

? only replaces a value, not an identifier (column, table) or a keyword (ASC/DESC). So sort often gets pasted straight into ORDER BY: where injection survives longest in code that "already uses PreparedStatement everywhere". The fix: an allowlist (name → username, created → created_at), unknown values get a 400, and only two sort directions are accepted.

Read in post: Web attacks and the OWASP Top 10
TILMidSecond-order SQL injection: clean when stored, toxic when usedThe username admin'-- is stored safely with a PreparedStatement. Months later, a reporting job reads it from the database and concatenates it into another query because "data from our own DB is trustworthy". The rule: every value that goes into SQL is bound, whether it came from a request, the database, a file or a que

The username admin'-- is stored safely with a PreparedStatement. Months later, a reporting job reads it from the database and concatenates it into another query because "data from our own DB is trustworthy". The rule: every value that goes into SQL is bound, whether it came from a request, the database, a file or a queue.

Read in post: Web attacks and the OWASP Top 10
Edge caseMidA bound LIKE parameter still carries the user's wildcardsWHERE username LIKE ? with "%" + term + "%" isn't injectable, but term = "" matches every username and % matches everything: wrong results plus a user-controlled full table scan. Escape \, % and , then declare ESCAPE '\'; in the demo, searching for after escaping returns only annguyen. A %term% pattern can't use a B-tr

WHERE username LIKE ? with "%" + term + "%" isn't injectable, but term = "_" matches every username and % matches everything: wrong results plus a user-controlled full table scan. Escape \, % and _, then declare ESCAPE '\'; in the demo, searching for _ after escaping returns only an_nguyen. A %term% pattern can't use a B-tree index, so large tables need pg_trgm or full-text search.

Read in post: Web attacks and the OWASP Top 10
Edge caseMidAn HttpOnly cookie doesn't stop XSS, it only stops reading the cookieHttpOnly hides the session cookie from document.cookie. But the script can still call fetch('/api/transfer', {method: 'POST', credentials: 'include'}) and the browser attaches the cookie for it. Keep it on (it beats a token in localStorage), but the XSS defense has to be output encoding and CSP.

HttpOnly hides the session cookie from document.cookie. But the script can still call fetch('/api/transfer', {method: 'POST', credentials: 'include'}) and the browser attaches the cookie for it. Keep it on (it beats a token in localStorage), but the XSS defense has to be output encoding and CSP.

Read in post: Web attacks and the OWASP Top 10
Trade-offSeniorDomain allowlist CSP or nonce-based strict CSPDomain allowlist: easy to write, but bypassable if an allowed domain hosts JSONP endpoints or libraries with script gadgets. Nonce + strict-dynamic: blocks every inline script without the nonce. The cost is a nonce per response; static pages cached on a CDN use hashes ('sha256-...').
  • Domain allowlist: easy to write, but bypassable if an allowed domain hosts JSONP endpoints or libraries with script gadgets.
  • Nonce + strict-dynamic: blocks every inline script without the nonce. The cost is a nonce per response; static pages cached on a CDN use hashes ('sha256-...').
Read in post: Web attacks and the OWASP Top 10
Trade-offSeniorRely on SameSite alone or keep CSRF tokensSameSite=Lax only: no extra code, stops most form-POST CSRF. But "site" means eTLD+1: evil.example.com and app.example.com are the same site, so a compromised subdomain still gets the cookie sent; GET with side effects stays exposed; older WebViews may not implement it correctly. CSRF tokens: stop same-site attacks too
  • SameSite=Lax only: no extra code, stops most form-POST CSRF. But "site" means eTLD+1: evil.example.com and app.example.com are the same site, so a compromised subdomain still gets the cookie sent; GET with side effects stays exposed; older WebViews may not implement it correctly.
  • CSRF tokens: stop same-site attacks too and don't depend on the browser. The cost is that the SPA has to fetch the token and attach it as a header.
  • With session cookies: keep both, the token as the main defense and SameSite as an extra layer.
Read in post: Web attacks and the OWASP Top 10
Edge caseMidDisabling CSRF while still logging in with a session cookieThe csrf.disable() in many tutorials is only correct for a pure bearer-token API. With formLogin or a JWT kept in a cookie, the browser attaches the cookie automatically and CSRF is back. The test question: "does the browser send anything for authentication on its own?". If yes, keep CSRF on.

The csrf.disable() in many tutorials is only correct for a pure bearer-token API. With formLogin or a JWT kept in a cookie, the browser attaches the cookie automatically and CSRF is back. The test question: "does the browser send anything for authentication on its own?". If yes, keep CSRF on.

Read in post: Web attacks and the OWASP Top 10
Edge caseSeniorThe login endpoint is the cheapest DoS target because password hashing is slow on purposeBcrypt or Argon2 is tuned so each hash costs around 100 ms of CPU (against offline cracking), so 100 junk logins per second eat 10 cores. Defend with rate limits per IP and per username before hashing, a CAPTCHA after a few failures, a separate thread pool for authentication. Still hash a dummy value when the user does

Bcrypt or Argon2 is tuned so each hash costs around 100 ms of CPU (against offline cracking), so 100 junk logins per second eat 10 cores. Defend with rate limits per IP and per username before hashing, a CAPTCHA after a few failures, a separate thread pool for authentication. Still hash a dummy value when the user doesn't exist, so response time doesn't reveal which users are real.

Read in post: Web attacks and the OWASP Top 10
Trade-offMidRate limiting per IP or per user/API keyPer IP: works for unauthenticated requests and can be done right in Nginx. But many people behind one NAT (offices, mobile CGNAT) get blocked unfairly, while a botnet spreads itself across tens of thousands of IPs. Per user/API key: fair, and maps to service plans. Only possible after authentication, and needs a shared
  • Per IP: works for unauthenticated requests and can be done right in Nginx. But many people behind one NAT (offices, mobile CGNAT) get blocked unfairly, while a botnet spreads itself across tens of thousands of IPs.
  • Per user/API key: fair, and maps to service plans. Only possible after authentication, and needs a shared counter (Redis).
  • In practice use both: IP at the edge for public endpoints, user/key inside the app.
Read in post: Web attacks and the OWASP Top 10
TILMidThe OWASP Top 10 is an awareness document; ASVS is the verification standard"We've handled the Top 10" doesn't mean the application is secure. The checkable list of requirements is ASVS (Application Security Verification Standard): three levels and several hundred requirements such as "all queries are parameterized" or "session cookies are Secure and HttpOnly".

"We've handled the Top 10" doesn't mean the application is secure. The checkable list of requirements is ASVS (Application Security Verification Standard): three levels and several hundred requirements such as "all queries are parameterized" or "session cookies are Secure and HttpOnly".

Read in post: Web attacks and the OWASP Top 10
Edge caseMidrequestMatchers are evaluated in order and the first match winsPut .requestMatchers("/api/").permitAll() before .requestMatchers("/api/admin/").hasRole("ADMIN") and the admin rule is never reached: /api/admin/users is open to everyone. Write rules from specific to general and end with anyRequest().denyAll() or .authenticated(), so a new endpoint someone forgot to declare starts cl

Put .requestMatchers("/api/**").permitAll() before .requestMatchers("/api/admin/**").hasRole("ADMIN") and the admin rule is never reached: /api/admin/users is open to everyone. Write rules from specific to general and end with anyRequest().denyAll() or .authenticated(), so a new endpoint someone forgot to declare starts closed.

Read in post: Web attacks and the OWASP Top 10
Edge caseMidFixing a security symptom by switching off the protection: disabling CSRF because of a 403An AJAX request getting a 403 means CSRF protection is working correctly; the "fix" removed it instead of attaching the token. The pattern repeats: disabling certificate checks because of a PKIX error, CORS because of a preflight error. Any line that turns off a protection needs a concrete technical reason, and should

An AJAX request getting a 403 means CSRF protection is working correctly; the "fix" removed it instead of attaching the token. The pattern repeats: disabling certificate checks because of a PKIX error, CORS * because of a preflight error. Any line that turns off a protection needs a concrete technical reason, and should be caught by a static analysis rule.

Read in post: Web attacks and the OWASP Top 10
InterviewJuniorWhat is SQL injection and what's the main defense?

User input concatenated into SQL gets interpreted by the database as code; the main defense is parameterization.

For example ' OR 1=1 -- bypasses a login. With PreparedStatement or named parameters in JPA, the statement is parsed first and values are only data. Extras: an allowlist for sort columns and a least-privilege DB account.

Read in post: Web attacks and the OWASP Top 10
InterviewJuniorHow is XSS different from CSRF?

XSS runs the attacker's script inside a trusted page; CSRF tricks the browser into sending a request with side effects using cookies it attaches automatically.

XSS can read and do anything the user can; CSRF can't read the response. XSS is stopped by output encoding and CSP, CSRF by tokens and SameSite. With XSS present, CSRF tokens are useless because the script can read them.

Read in post: Web attacks and the OWASP Top 10
InterviewJuniorWhy shouldn't GET change data?

Because GET is the easiest request to forge and the least protected.

An <img src="/delete?id=5"> on any page is enough for CSRF, SameSite=Lax still sends cookies on top-level GET navigation, Spring Security doesn't require a CSRF token for GET, and GET parameters end up in logs.

Read in post: Web attacks and the OWASP Top 10
InterviewMidWe use PreparedStatement everywhere. Where can SQL injection still happen?

Wherever binding isn't possible, and in data read from the DB and concatenated again.

ORDER BY, column or table names built from input; concatenated JPQL or native queries; dynamic SQL inside stored procedures; and second-order injection, where data read from the DB is concatenated into another query. The fix: allowlist identifiers and bind every value regardless of its source.

Read in post: Web attacks and the OWASP Top 10
InterviewMidWhen is it OK to disable CSRF in Spring Security?

Only when the browser sends no credentials by itself.

That means only an Authorization: Bearer header the client attaches, no session cookie, no token in a cookie. With formLogin or a JWT in a cookie, keep CSRF; for an SPA use CookieCsrfTokenRepository and send the token in a header.

Read in post: Web attacks and the OWASP Top 10
InterviewMidWhat is CSP and how do you configure it effectively?

A header telling the browser where scripts may come from, the second line of defense against XSS; use a nonce-based strict CSP.

Domain allowlists are easy to bypass, so use script-src 'nonce-...' 'strict-dynamic', object-src 'none', base-uri 'none', and frame-ancestors against clickjacking. Roll it out in Report-Only mode first.

Read in post: Web attacks and the OWASP Top 10
InterviewSeniorHow do you protect a webhook or partner API against replay?

Sign a timestamp and a nonce, reject stale timestamps and nonces already seen in the window; a signature alone doesn't prevent replay.

Remember nonces for the window with an atomic operation (Redis SET NX EX), and verify the signature before recording the nonce. At the business level, add idempotency keyed on the transaction id.

Read in post: Web attacks and the OWASP Top 10
InterviewSeniorHow would you design DDoS protection for a public API?

L3/L4 goes to a scrubbing provider or a large CDN; L7 is handled with several layers of limits.

For L7: cache public content; rate-limit per IP at the edge and per user/API key in the app; cap body size and page size; make expensive endpoints asynchronous with quotas; use timeouts and bulkheads; autoscale with a ceiling; and have a 429-rate dashboard plus an emergency runbook.

Read in post: Web attacks and the OWASP Top 10
InterviewSeniorYou're reviewing a PR that disables CSRF, sets CORS to * and adds th:utext. What do you say?

Reject it: each line removes a protection, and together they make a self-spreading XSS worm.

CSRF can only be disabled for a pure bearer-token API. CORS * opens the API to every origin; it needs an explicit origin list. th:utext on user data is stored XSS. I'd also propose security tests in CI and static analysis rules that block these patterns.

Read in post: Web attacks and the OWASP Top 10
InterviewSeniorWhat's in the OWASP Top 10 2021 and how do you apply it to a Spring project?

Ten risk categories led by Broken Access Control; you apply it through concrete controls, and use ASVS when you need checkable requirements.

The list: Broken Access Control, Cryptographic Failures, Injection, Insecure Design, Security Misconfiguration, Vulnerable Components, Authentication Failures, Integrity Failures, Logging and Monitoring Failures, SSRF. Applying it: deny by default with ownership checks, bound parameters, dependency scanning in CI, no exposed actuator, security event logging, and host allowlists for user-supplied URLs.

Read in post: Web attacks and the OWASP Top 10
Trade-offMidAn abstract step or a hook with a defaultAbstract: every subclass has to decide, so nobody can "forget". Adding a new abstract step breaks compilation of every existing subclass: both a benefit (nothing missed) and a cost (edit N classes). A subclass that needs nothing still has to write an empty method, as VillaBookingService would. A hook with a default: su
  • Abstract: every subclass has to decide, so nobody can "forget". Adding a new abstract step breaks compilation of every existing subclass: both a benefit (nothing missed) and a cost (edit N classes). A subclass that needs nothing still has to write an empty method, as VillaBookingService would.
  • A hook with a default: subclasses implement it only when needed, and adding a hook breaks nobody. The price: a subclass that needed custom behaviour but forgot to override silently runs the default.

Use abstract for decisions every type must answer for itself (how fees are computed, how a booking is confirmed); use hooks for optional extensions (an extra notification, publishing an event).

Read in post: Template Method or composition
Edge caseMidOverriding a step without calling super silently drops a checkSubclasses often "extend" a step by adding logic and calling super.step(). Forget the super line and the code still compiles, the subclass's tests still pass if they only cover the added part, and the parent's check (say, the guest limit) quietly disappears. Prevention: move the mandatory part into a private step the t

Subclasses often "extend" a step by adding logic and calling super.step(). Forget the super line and the code still compiles, the subclass's tests still pass if they only cover the added part, and the parent's check (say, the guest limit) quietly disappears.

Prevention: move the mandatory part into a private step the template always calls, and give subclasses an additional hook (checkExtraRules) to override instead.

Read in post: Template Method or composition
Edge caseMidCalling an overridable method from a constructorA parent constructor runs before the subclass's fields are assigned. If it calls a method the subclass overrides, that method sees the subclass's fields as null (or 0): Even a final field reads as null. Never call template steps from a constructor; if you need initialisation, use an init() method called afterwards, or

A parent constructor runs before the subclass's fields are assigned. If it calls a method the subclass overrides, that method sees the subclass's fields as null (or 0):

static abstract class Base {
    Base() { describe(); }
    abstract void describe();
}
static final class Child extends Base {
    private final String name = new String("child");
    void describe() { System.out.println("describe() sees name = " + name); }
}
// new Child() prints: describe() sees name = null

Even a final field reads as null. Never call template steps from a constructor; if you need initialisation, use an init() method called afterwards, or @PostConstruct in Spring.

Read in post: Template Method or composition
Edge caseSenior@Transactional on a template step does nothing when the template calls itSpring applies transactions through a proxy (an object wrapped around the bean). The template calls its steps as this.step(), straight on the object, bypassing the proxy. So @Transactional(propagation = REQUIRESNEW) on postProcess to "write the audit log in its own transaction" is silently ignored: the step runs inside

Spring applies transactions through a proxy (an object wrapped around the bean). The template calls its steps as this.step(), straight on the object, bypassing the proxy. So @Transactional(propagation = REQUIRES_NEW) on postProcess to "write the audit log in its own transaction" is silently ignored: the step runs inside execute's transaction, or with no transaction if execute has none.

If a step needs its own transaction: move it to another bean and inject it, or use a TransactionTemplate inside that step.

Read in post: Template Method or composition
Trade-offSeniorTemplate Method or composition (rules and listeners)Template Method: one place shows the whole flow, few types; good when the skeleton is stable and a few variants differ in a few steps. The price: subclasses depend on the parent's details (fragile base class: a change in the parent breaks subclasses); each variant has only one parent, so "apartment + corporate guest +
  • Template Method: one place shows the whole flow, few types; good when the skeleton is stable and a few variants differ in a few steps. The price: subclasses depend on the parent's details (fragile base class: a change in the parent breaks subclasses); each variant has only one parent, so "apartment + corporate guest + long stay" leads to a subclass explosion; constructor injection is repeated in every subclass.
  • Composition: each rule is small, tested alone, combined freely per type or per configuration; a new rule is a new bean. The price: the order of the flow no longer lives in one place (you read the wiring), and too many tiny rules get hard to trace while debugging.

A pragmatic rule: start with Template Method when there are two or three types; move to composition once variants start combining or subclasses override more than half the steps.

Read in post: Template Method or composition
InterviewJuniorWhat is Template Method and how does it differ from Strategy?

Template Method uses inheritance to fix the order of steps; Strategy uses composition to swap a whole behaviour, even at runtime.

Template Method fixes the order of steps in one method of a parent class, and subclasses override some steps; the variant is chosen at compile time (which subclass you instantiate). With Strategy, the object receives an implementation through a constructor or setter, it can change at runtime, and strategies can be combined.

Read in post: Template Method or composition
InterviewMidWhat is a hook method, and how is it different from an abstract step?

A hook has a default (often empty) that a subclass may override; an abstract step is one every subclass must implement.

The template calls the hook at a fixed point, for example afterBooked to publish an event. Use hooks for optional extensions and abstract steps for decisions every variant has to make.

Read in post: Template Method or composition
InterviewMidWhy shouldn't the template method be overridable?

Because Template Method's value is guaranteeing the order and the mandatory steps; an overridable template lets a subclass skip them.

The mandatory steps are things like validation, locking and logging. Declare the template final, invariant steps private, and open only the steps that are allowed to vary.

Read in post: Template Method or composition
InterviewMidWhy shouldn't a constructor call an overridable method?

Because the parent constructor runs before the subclass's fields are assigned, so the overriding method sees its fields as null or 0.

That includes final fields that aren't compile-time constants. The compiler doesn't catch it, and it only bites in subclasses that use their fields. If initialisation needs a template step, use an init() method called after construction, or @PostConstruct in Spring.

Read in post: Template Method or composition
InterviewSeniorWhen do you choose composition over Template Method?

When variants start combining, when subclasses override more than half the steps, when behaviour has to change by configuration at runtime, or when constructor injection is repeated in every subclass.

An example of combining: apartment and corporate guest and long stay. Composition turns each rule into a small bean, tested alone, wired per type. The price is that the overall flow no longer sits in one place, so I usually keep an orchestrating service that reads like a template method but calls injected rules.

Read in post: Template Method or composition
InterviewSeniorA template step has @Transactional(propagation = REQUIRES_NEW) but no new transaction appears. Why?

Self-invocation: the template calls the step as this.step(), bypassing Spring's proxy, so the annotation is ignored.

Fix it by moving the step into another bean that gets injected, or by using a TransactionTemplate inside the step. Also check: private and final methods can't be intercepted by a CGLIB proxy either.

Read in post: Template Method or composition
InterviewSeniorA service has both @SneakyThrows and @Transactional. What's the risk?

A checked exception sneaked out through @SneakyThrows doesn't trigger a rollback, so the transaction commits even though the method failed halfway.

By default Spring and JTA only roll back on unchecked exceptions. Example damage: nights marked booked but the booking not fully saved. Fix: drop @SneakyThrows and wrap into an unchecked business exception, or declare rollbackFor = Exception.class.

Read in post: Template Method or composition
Edge caseSeniorA slice test runs the default security chain, not yoursIn the lab, SecurityConfig is not loaded into the slice (it needs PermissionAuthorizationManager, a @Component the slice skips). The slice uses Spring Security's default chain: every request must be authenticated and CSRF is on. So the tests need @WithMockUser (or .with(jwt())) and .with(csrf()), even though the real A

In the lab, SecurityConfig is not loaded into the slice (it needs PermissionAuthorizationManager, a @Component the slice skips). The slice uses Spring Security's default chain: every request must be authenticated and CSRF is on. So the tests need @WithMockUser (or .with(jwt())) and .with(csrf()), even though the real API disables CSRF for /api/**.

Consequence: @WebMvcTest proves the controller is right, not that your authorization rules are. Test authorization with @SpringBootTest (section 5), or @Import(SecurityConfig.class) together with all its dependencies.

Read in post: Testing Spring Boot
Edge caseSeniorWith IDENTITY, save() already ran the INSERT; the constraint error comes from save, not flushThe lab's first unique-(apipath, method) test did save(A), save(A2) and expected the error at flush(). Result: red, because the exception was thrown at save(A2). The reason: with GenerationType.IDENTITY the DB generates the id, so Hibernate must INSERT as soon as you persist to learn the id; it can't wait for the flush

The lab's first unique-(api_path, method) test did save(A), save(A2) and expected the error at flush(). Result: red, because the exception was thrown at save(A2). The reason: with GenerationType.IDENTITY the DB generates the id, so Hibernate must INSERT as soon as you persist to learn the id; it can't wait for the flush. With SEQUENCE the INSERT is deferred to the flush.

Fix: wrap both steps in the assertion, assertThatThrownBy(() -> permissions.saveAndFlush(dup)). The broader lesson: when the error surfaces depends on the id strategy; code that handles DataIntegrityViolationException must sit where it actually receives it.

Read in post: Testing Spring Boot
Edge caseSenior@Transactional on an integration test hides bugsThe course suggests @Transactional to roll back after each test. Three problems: No effect with RANDOMPORT: the request runs on a server thread, really commits, and the data leaks into the next test. Hides LazyInitializationException: the test's transaction stays open, so code that touches a lazy relation after the ser

The course suggests @Transactional to roll back after each test. Three problems:

  • No effect with RANDOM_PORT: the request runs on a server thread, really commits, and the data leaks into the next test.
  • Hides LazyInitializationException: the test's transaction stays open, so code that touches a lazy relation after the service returned still works. Production (with open-in-view=false) blows up.
  • Hides commit-time errors: deferred constraints, and @TransactionalEventListener(AFTER_COMMIT) never runs because nothing commits.

The lab hit exactly the second bug: refresh returned 500 because the controller read user.getRoles() after the transaction closed. AuthFlowIntegrationTest does not use @Transactional, so it caught it. Alternative clean-up: TestDataFactory.reset() in @BeforeEach, or each test creating its own data with unique emails.

Read in post: Testing Spring Boot
TILSeniorAn integration test caught a catch-all handler turning 403 into 500@PreAuthorize throws AccessDeniedException inside the controller call, so @RestControllerAdvice sees it before Spring Security's filters do. An advice with @ExceptionHandler(Exception.class) swallows it and answers 500. In the lab, removing the handler that re-throws AccessDeniedException turned the MethodSecurity test

@PreAuthorize throws AccessDeniedException inside the controller call, so @RestControllerAdvice sees it before Spring Security's filters do. An advice with @ExceptionHandler(Exception.class) swallows it and answers 500. In the lab, removing the handler that re-throws AccessDeniedException turned the MethodSecurity test red: expected 403, got 500. A slice test with mocks never sees this, because it needs the real advice, real method security and the real chain together.

Read in post: Testing Spring Boot
Edge caseMid@MockitoBean is not "new in Boot 4"The course's table says Boot 3 uses @MockBean and Boot 4 uses @MockitoBean. More precisely: @MockitoBean arrived in Spring Framework 6.2 (Boot 3.4), @MockBean was deprecated then, and Boot 4 removed it. A Boot 3.4/3.5 project should switch to @MockitoBean now, before upgrading. Note that @MockitoBean goes on fields of

The course's table says Boot 3 uses @MockBean and Boot 4 uses @MockitoBean. More precisely: @MockitoBean arrived in Spring Framework 6.2 (Boot 3.4), @MockBean was deprecated then, and Boot 4 removed it. A Boot 3.4/3.5 project should switch to @MockitoBean now, before upgrading. Note that @MockitoBean goes on fields of the test class (or @MockitoBean(types = ...) at class level), not inside a @Configuration the way the old @MockBean could.

Read in post: Testing Spring Boot
InterviewMidHow does @WebMvcTest differ from @SpringBootTest?

@WebMvcTest loads only the web layer (controller, advice, Jackson, validation, security) and mocks the rest; @SpringBootTest loads the whole application.

The slice is fast and pinpoints HTTP-layer bugs. @SpringBootTest is slower but checks the real flow through your services, DB and security chain.

Read in post: Testing Spring Boot
InterviewMidWhy call flush() and clear() in a @DataJpaTest?

flush() pushes SQL to the DB so real constraints and mappings run; clear() empties the persistence context so the next read hits the DB instead of returning the object in memory.

Without them a test can be green with a wrong mapping, because you just read back the object you saved.

Read in post: Testing Spring Boot
InterviewMidWhat is the difference between @MockitoBean and @Mock?

@Mock is a plain Mockito mock in a unit test; @MockitoBean replaces a bean in the Spring context with a mock.

Use @MockitoBean in slice/integration tests. Each distinct set of @MockitoBeans makes Spring build a new context, so use them sparingly.

Read in post: Testing Spring Boot
InterviewSeniorShould you put @Transactional on integration tests to roll back data?

With MockMvc it works but hides bugs; with RANDOM_PORT it does nothing. Important tests should really commit and clean up themselves.

@Transactional on the test keeps a transaction open throughout, hiding LazyInitializationException, commit-time errors and AFTER_COMMIT listeners. With a real server the request runs on another thread, so nothing is rolled back. Clean data in @BeforeEach or use unique data per test instead.

Read in post: Testing Spring Boot
InterviewSeniorThe team's Spring Boot test suite takes 15 minutes. How do you investigate?

First count how many Spring contexts get created: the context-cache log shows how many startups happen and why.

  • Align @MockitoBeans, properties and profiles so classes share a context; remove @DirtiesContext.
  • One shared Testcontainers container instead of one per class.
  • Push logic down to unit tests; move integration tests to failsafe and run them in parallel on CI.
Read in post: Testing Spring Boot
InterviewSeniorHow do you test authorization in a REST API that uses JWT?

With @SpringBootTest + MockMvc and real tokens signed by the app's own JwtEncoder, through the real filter chain, for users holding exactly the permissions each test needs.

Cover 401 (no token, broken token, expired), 403 (missing permission, missing role for method security) and 200. A slice test with jwt() or @WithMockUser proves the controller, not the rules.

Read in post: Testing Spring Boot
InterviewSeniorWhen do you choose H2, and when Testcontainers?

Testcontainers with the production DB for anything touching queries, constraints or locking; H2 only when you need raw speed for simple mappings and accept the dialect risk.

H2 differs in syntax, date functions, collation and locking behaviour. The cost of Testcontainers is needing Docker and startup time, reduced with a shared container.

Read in post: Testing Spring Boot
Edge caseSeniorThe expiry job releases inventory without knowing a payment is in progressA naive job looks only at the booking's expiresat, so it releases seats while the customer is still on the gateway page: the customer is charged for seats that no longer exist. Fix it with options (1) and (2) above. Add a metric "successful IPNs for expired bookings": anything above zero means the time windows are set

A naive job looks only at the booking's expires_at, so it releases seats while the customer is still on the gateway page: the customer is charged for seats that no longer exist. Fix it with options (1) and (2) above. Add a metric "successful IPNs for expired bookings": anything above zero means the time windows are set wrong.

Read in post: Payments after the integration
Trade-offSeniorLate IPN: try to keep the booking or refund straight awayTry to keep the booking (another seat in the same class, at the locked-in price): the best experience. But the price may have gone up (who absorbs the difference?), and if only another class is left you need a clear product rule. Automatic refund: simple and always right about the money. The customer has to book again,
  • Try to keep the booking (another seat in the same class, at the locked-in price): the best experience. But the price may have gone up (who absorbs the difference?), and if only another class is left you need a clear product rule.
  • Automatic refund: simple and always right about the money. The customer has to book again, maybe at a higher price, and a card refund takes days.
  • Manual review queue: only fits very small volumes; the customer's money is stuck.

Product and finance decide. The engineer makes the case rare and never silent (the payment is always recorded, there's a REFUND_PENDING status, a metric, an alert).

Read in post: Payments after the integration
Trade-offSeniorWait for the IPN or actively query the gatewayOnly wait for the IPN: cheap. But the IPN can be lost entirely (our endpoint down longer than the gateway's retry window, a wrong IPN URL after a domain change). Only query the gateway (polling every order): certain, but expensive in requests, rate-limited, and slower. IPN as the main path, queries as the safety net: q
  • Only wait for the IPN: cheap. But the IPN can be lost entirely (our endpoint down longer than the gateway's retry window, a wrong IPN URL after a domain change).
  • Only query the gateway (polling every order): certain, but expensive in requests, rate-limited, and slower.
  • IPN as the main path, queries as the safety net: query only overdue payments with no result, or when the return URL beats the IPN. Both paths feed one idempotent function, so duplicates are harmless.
Read in post: Payments after the integration
Edge caseMidCutting reconciliation days in UTC while the gateway's statement uses Vietnam timeDomestic gateways usually cut statement days in Vietnam time (GMT+7). paidat is a timestamptz, so paidat::date = '2026-11-18' cuts the day in the session's time zone (usually UTC on a server). Transactions between 00:00 and 07:00 Vietnam time fall into "the previous day", and every morning reconciliation reports dozens

Domestic gateways usually cut statement days in Vietnam time (GMT+7). paid_at is a timestamptz, so paid_at::date = '2026-11-18' cuts the day in the session's time zone (usually UTC on a server). Transactions between 00 and 07 Vietnam time fall into "the previous day", and every morning reconciliation reports dozens of fake OURS_ONLY and UNKNOWN_TO_US rows. Filter with an explicit, zone-qualified range (paid_at >= '2026-11-18 00:00+07' AND paid_at < '2026-11-19 00:00+07'), and check the neighbouring day's statement for transactions close to midnight.

Read in post: Payments after the integration
InterviewJuniorWhat is payment reconciliation, and why do you need it when you already have IPNs?

Reconciliation compares our data (payments, the ledger) with the gateway's data (statements, payouts) to find discrepancies. You need it because IPNs can be lost, late, or mishandled by a bug.

Only reconciliation catches "the gateway collected but we never recorded it" or "we recorded success but the gateway has nothing". Without it, discrepancies only surface when a customer complains or when accounting closes the books.

Read in post: Payments after the integration
InterviewMidWhy must the payment URL expire before the seat hold does?

So the gateway refuses payment before the seat can be released, which makes late IPNs rare.

If they're equal or the URL lasts longer, a customer can pay at the last moment while the job has already released the seat to someone else. Make vnp_ExpireDate shorter (URL 15 minutes, seats 20 minutes) and give the expiry job a buffer for open payments.

Read in post: Payments after the integration
InterviewMidHow do you run the transaction-query job safely on several instances?

Split batches with FOR UPDATE SKIP LOCKED, commit before any network call, and feed results to the idempotent apply function.

Each run takes a batch of overdue PENDING payments, updates last_queried_at and commits (no locks held while waiting on the gateway). It calls the query API through a rate limiter sized to the gateway's quota. If two instances ever process the same payment, the conditional update still allows only one state transition.

Read in post: Payments after the integration
InterviewMidWhat is settlement and how do you record it in the ledger?

It's when the gateway pays what it collected into the merchant's bank account, typically T+1, after deducting fees and refunds.

Record it as one multi-legged transaction: debit the bank for the net amount, debit a fee expense account, credit the gateway clearing account. After settlement, the clearing account's balance should equal what hasn't been paid out yet; a gap is a signal to reconcile.

Read in post: Payments after the integration
InterviewSeniorA successful IPN arrives after the booking expired and the seat was sold to someone else. What do you do?

Record the payment as successful because the money is real, try to hold another seat in the same class at the locked-in price; if that fails, move to REFUND_PENDING and refund automatically.

Notify the customer either way. More importantly, make it rare: a URL deadline shorter than the hold, an expiry job that doesn't release bookings with open payments, and a gateway query before releasing. Keep a metric and an alert on REFUND_PENDING counts.

Read in post: Payments after the integration
InterviewSeniorHow would you design reconciliation with a payment gateway?

Two rhythms: a near-real-time transaction-query job and a daily statement match; then payout reconciliation.

  • Near real time: query overdue payments with no result, sharing the idempotent function with the IPN.
  • Daily: load the statement, FULL JOIN it with successful payments for the Vietnam-time day, classify rows as matched, missing on our side, missing on the gateway's side, amount mismatch, or unknown; each category has its own procedure.
  • Payouts: record settlement in the ledger and check the clearing account balance.
Read in post: Payments after the integration
InterviewSeniorHow do you test a payment integration without depending on the gateway's sandbox in CI?

Sign IPN parameter sets yourself with the test key and call the endpoint directly; put the gateway's APIs behind an interface and stub them.

  • Test the signature against a fixed parameter set and expected signature.
  • Integration tests with Testcontainers, one BDD scenario per failure mode (success, resend, concurrency, bad signature, wrong amount, late arrival).
  • Stub URL creation and queries with WireMock.
  • Use the real sandbox only for manual smoke tests or a nightly run through a tunnel.
Read in post: Payments after the integration
Edge caseMidReading a relationship in one direction only gets the cardinality wrong"A flight has many bookings" sounds right, so it's tempting to settle on 1–N with a flightid column on booking. Read it backwards, "does a booking belong to exactly one flight?", and it breaks for round trips and connecting itineraries. Settling early leads to repeated columns like departureflightid, returnflightid plu

"A flight has many bookings" sounds right, so it's tempting to settle on 1–N with a flight_id column on booking. Read it backwards, "does a booking belong to exactly one flight?", and it breaks for round trips and connecting itineraries. Settling early leads to repeated columns like departure_flight_id, return_flight_id plus a type flag saying which ones mean something.

Always write both "how many B does one A have" and "how many A does one B have". Any sentence that needs "it depends" or "usually" is a sign you need a junction table.

Read in post: Designing an airline booking database
Edge caseMidStoring flight times without a time zone breaks routes that cross zonesA Hanoi–Tokyo flight leaves at 08:00 Hanoi time (UTC+7) and lands at 15:00 Tokyo time (UTC+9). Store both as timestamp without time zone (or MySQL DATETIME) in local time and arrivaltime - departuretime gives 7 hours instead of 5, and a "lands after it departs" CHECK can fail for westbound flights. Store absolute insta

A Hanoi–Tokyo flight leaves at 08 Hanoi time (UTC+7) and lands at 15 Tokyo time (UTC+9). Store both as timestamp without time zone (or MySQL DATETIME) in local time and arrival_time - departure_time gives 7 hours instead of 5, and a "lands after it departs" CHECK can fail for westbound flights.

Store absolute instants (PostgreSQL timestamptz, or UTC in a MySQL DATETIME), keep the IANA zone on the airport table (Asia/Ho_Chi_Minh, Asia/Tokyo), and convert to local time only for display.

Read in post: Designing an airline booking database
TILSeniorA seat map belongs to a cabin configuration, not to an individual aircraft or a flightTwo A321s with the same cabin configuration share a seat map, so seat is keyed by aircraftcode as a model or configuration, not by each airframe's registration (like VN-A601). Real systems separate three concepts: the aircraft model, the cabin configuration (seats per class, which rows are exit rows) and the actual air

Two A321s with the same cabin configuration share a seat map, so seat is keyed by aircraft_code as a model or configuration, not by each airframe's registration (like VN-A601). Real systems separate three concepts: the aircraft model, the cabin configuration (seats per class, which rows are exit rows) and the actual airframe used in operations.

When the airline does an equipment swap to a configuration with fewer seats, some seats already sold stop existing and passengers must be re-seated. Allowing a flight's aircraft_code to change, with a re-seating procedure, is the difference between a demo and a system that can run.

Read in post: Designing an airline booking database
Trade-offSeniorSeat inventory as one row per seat or as a counterReal airlines usually combine both: they sell against a per-class counter (allows overbooking, handles load well) and use the seat map only for paid seat selection and check-in.
Criterion One row per seat One counter per flight and class
Picking a specific seat Built in: each seat has its own status No, seats are assigned in a separate step
Row count ~180 per flight, ~26 million a year at 400 flights a day 2–3 per flight
Contention at peak Spread over many rows: two people booking different seats don't block each other Concentrated on one hot row: every booking on the flight queues on the same lock
Overbooking Impossible: you can't sell seat 12A twice Natural: it's just sell_limit > capacity
Counting free seats Indexed count(*), cheap but not free Read one row
"No seat sold twice" invariant Guaranteed by the primary key (flight_id, seat_code) Not applicable

Real airlines usually combine both: they sell against a per-class counter (allows overbooking, handles load well) and use the seat map only for paid seat selection and check-in.

Read in post: Designing an airline booking database
Edge caseMidThe overbooking formula in the original notes sells the wrong number of seatsbookedseats < totalseats overbookrate is wrong under both readings: with rate 0.1 a 100-seat flight sells only 10 seats; with rate 1.1 it checks before adding the new booking, so with 109 sold a group of 3 still gets through and the flight is sold to 112, past the 110 limit. The correct rule is booked + q ≤ floor(capac

booked_seats < total_seats * overbook_rate is wrong under both readings: with rate 0.1 a 100-seat flight sells only 10 seats; with rate 1.1 it checks before adding the new booking, so with 109 sold a group of 3 still gets through and the flight is sold to 112, past the 110 limit.

The correct rule is booked + q ≤ floor(capacity × (1 + rate)), placed right in the UPDATE's WHERE so the check and the write are one atomic operation.

Read in post: Designing an airline booking database
Edge caseMidPostgreSQL does not create indexes on foreign key columnsMySQL InnoDB creates an index on a foreign key column if there isn't one; PostgreSQL doesn't. The result: deleting or re-keying a parent row (a flight, a booking) makes PostgreSQL scan the whole child table to check the constraint, and joins along foreign keys (tickets of a booking, money lines of a direction) run as S

MySQL InnoDB creates an index on a foreign key column if there isn't one; PostgreSQL doesn't. The result: deleting or re-keying a parent row (a flight, a booking) makes PostgreSQL scan the whole child table to check the constraint, and joins along foreign keys (tickets of a booking, money lines of a direction) run as Seq Scans.

For each foreign key, ask "does any query or delete go through this column?"; if so, create the index. List unindexed foreign keys by comparing pg_constraint with pg_index.

Read in post: Designing an airline booking database
Trade-offSeniorA partial index on status: small and fast, but you pay on writesWHERE status = 'AVAILABLE' holds only free seats, so the index shrinks as the flight fills up and suits counting free seats and auto-assignment. The cost: every status change moves the row into or out of the index, so PostgreSQL can't use a HOT update (an update that skips the indexes) and creates more dead tuples for

WHERE status = 'AVAILABLE' holds only free seats, so the index shrinks as the flight fills up and suits counting free seats and auto-assignment. The cost: every status change moves the row into or out of the index, so PostgreSQL can't use a HOT update (an update that skips the indexes) and creates more dead tuples for VACUUM.

For booking traffic (each seat changes status a few times) the cost is small. For a job queue flipping status thousands of times a second, measure it and watch n_dead_tup and autovacuum frequency. MySQL has no partial indexes, so use a composite index starting with (flight_id, status).

Read in post: Designing an airline booking database
InterviewJuniorWhy does a flight have two foreign keys to the airport table?

Because there are two different relationships, the departure airport and the arrival airport, and each rests on one column.

Each reads as its own sentence ("a flight has exactly one departure airport", "a flight has exactly one arrival airport"). Add CHECK (departure_airport <> arrival_airport) to block nonsense data.

Read in post: Designing an airline booking database
InterviewJuniorWhy store a booking's passengers in a junction table instead of a column?

Because booking to passenger is N–N, and a column holding a list violates 1NF.

One booking has many passengers, one passenger takes many bookings. A list column can't carry a foreign key and makes "which flights has this passenger taken" hard to query. A booking_passenger (booking_id, passenger_id) table with a composite primary key solves all three.

Read in post: Designing an airline booking database
InterviewJuniorWhat is overbooking and how do you compute the sell limit?

Selling more tickets than seats because you know a share of passengers won't show up; the sell limit is floor(capacity × (1 + rate)).

A booking of q seats is accepted only when booked + q ≤ sell_limit. You must add the new booking's q before comparing, not compare the count already sold.

Read in post: Designing an airline booking database
InterviewMidShould seat inventory be stored per seat or as a counter?

It depends on whether customers pick seats at booking time; airlines often combine them: sell against a per-class counter, select seats and check in against the seat map.

  • Per seat: seat selection works, contention spreads over many rows, the primary key prevents selling a seat twice, but there are many rows and no overbooking.
  • Counter: simple, overbooking comes naturally, but every booking on the flight fights over one hot row.
Read in post: Designing an airline booking database
InterviewMidWhy store departure and arrival times as timestamptz instead of local time?

Because a flight connects two time zones, and local times without a zone give the wrong duration when subtracted.

They can also break a "lands after it departs" CHECK on westbound flights. Store absolute instants (timestamptz, or UTC in a MySQL DATETIME), keep the IANA zone on the airport table, and convert to local time for display.

Read in post: Designing an airline booking database
InterviewMidHow would you index the query that searches flights by route and date?

(departure_airport, arrival_airport, departure_time): the two equality columns first and the time range last.

Columns after a range column can no longer narrow the scan. Verify with EXPLAIN ANALYZE on real data; for a result of a few dozen rows, a Bitmap Index Scan followed by a small Sort is normal.

Read in post: Designing an airline booking database
InterviewSeniorThe original notes accept a booking if booked < total × rate. How do you review that?

It's wrong under both readings; change it to booked + q ≤ floor(capacity × (1 + rate)) inside the UPDATE's WHERE.

  • Rate 0.1 sells only 10% of the seats; rate 1.1 compares the count before adding the new booking, so groups push past the limit.
  • Move the limit into a generated column and add CHECK (booked <= sell_limit) as a safety net.
  • Then discuss: rate per flight and class, zero for business, and the procedure for lowering the rate below what's already sold.
Read in post: Designing an airline booking database
InterviewSeniorAirports use a natural key and flights a surrogate key. Why not pick one style everywhere?

Choose by the nature of the data, not by a blanket rule.

IATA codes are short, stable and meaningful to people and external systems, so they make a good primary key and save joins just to display a code. Flights have no tidy natural key (the number repeats daily, the departure time can change when delayed), so they get an identity key plus UNIQUE (flight_no, departure_time) to block duplicates. If a natural key can change (a schedule change moves the departure time), it shouldn't be the primary key referenced from millions of rows.

Read in post: Designing an airline booking database
Edge caseSeniorPartitioning messages by channel_id aloneThe general channel of a big server gets hundreds of messages a minute. After a few years, one channelid partition holds millions of rows, GBs of data: the first page still reads fast, but compaction, repair and tombstones (delete markers) slow down the whole node. The fix: add a time-window bucket to the partition key

The general channel of a big server gets hundreds of messages a minute. After a few years, one channel_id partition holds millions of rows, GBs of data: the first page still reads fast, but compaction, repair and tombstones (delete markers) slow down the whole node.

The fix: add a time-window bucket to the partition key so every partition has an upper bound. Pick the window so the busiest channel's partition stays under ~100 MB. Discord has said publicly that they do this with 10-day windows.

Read in post: Designing a Discord-style chat system
Trade-offSeniorScyllaDB/Cassandra or PostgreSQL for messagesPostgreSQL: transactions, flexible indexes, familiar; but 330 TB/year and 100K writes/s force you to shard it yourself, and a giant append-only table is hard to run (VACUUM, index bloat). ScyllaDB/Cassandra: LSM writes are very cheap, partitioning and replication are built in, nodes are added online. In exchange: queri

PostgreSQL: transactions, flexible indexes, familiar; but 330 TB/year and 100K writes/s force you to shard it yourself, and a giant append-only table is hard to run (VACUUM, index bloat).

ScyllaDB/Cassandra: LSM writes are very cheap, partitioning and replication are built in, nodes are added online. In exchange: queries only by partition key, no joins, edits and deletes create tombstones, and consistency is chosen per query (QUORUM for message writes). For a "write-heavy, read by channel and time" access pattern, wide-column wins.

Read in post: Designing a Discord-style chat system
TILSeniorCoalesce identical reads in front of the databaseWhen an @everyone message reaches 100K people, a flood of clients reload the same channel's history at once. Put a "data service" in front of the database that merges identical in-flight read requests into a single query (request coalescing, like singleflight) and hands the result to all of them. Discord described doin

When an @everyone message reaches 100K people, a flood of clients reload the same channel's history at once. Put a "data service" in front of the database that merges identical in-flight read requests into a single query (request coalescing, like singleflight) and hands the result to all of them. Discord described doing this (in Rust) when they moved to ScyllaDB, and it's an effective shield for hot partitions.

Read in post: Designing a Discord-style chat system
InterviewMidWhy does chat use WebSockets instead of the client polling the server?

A WebSocket keeps one two-way connection open so the server pushes messages the moment they exist; polling is either late (infrequent) or wasteful (frequent, mostly empty responses).

With 10M people online, polling every 2 seconds is 5M requests/s, mostly useless. Long polling and SSE are fallbacks when WebSockets are blocked.

Read in post: Designing a Discord-style chat system
InterviewMidDesign the message table for scrolling back through history.

Partition by (channel_id, bucket) where the bucket is a time window, cluster by message_id descending; the next page is message_id < cursor LIMIT 50.

The bucket keeps partitions from growing forever. message_id is a Snowflake id, so it's unique and time-sorted.

Read in post: Designing a Discord-style chat system
InterviewMidA flaky network makes the client send a message twice. How do you avoid showing it twice?

The client sends a nonce; the server remembers (user_id, nonce) → message_id for a few minutes and returns the existing message on a repeated nonce.

On the receiving side, clients dedupe by message_id, since delivery is at-least-once.

Read in post: Designing a Discord-style chat system
InterviewSeniorA message lands in a channel of a server with 100K people online. How do you deliver it cheaply?

Fan out per gateway node: the guild service knows which node each session is on, sends one copy plus a session list to each node (~200), and each node delivers to its own connections.

Add lazy presence, send typing only to people with the channel open, and coalesce identical history reads in front of the database.

Read in post: Designing a Discord-style chat system
InterviewSeniorHow do you guarantee message order within a channel?

Assign a Snowflake message_id at write time and always render by id, never by arrival order; publish to a Kafka partition keyed by guild to keep delivery order within a guild.

Two messages in the same millisecond get an arbitrary but consistent order for everyone. On a gap, the client backfills with the cursor.

Read in post: Designing a Discord-style chat system
InterviewSeniorA gateway node holding 50K connections dies. What happens and how do you limit the damage?

50K clients reconnect to other nodes; use backoff with jitter to avoid a stampede, resume with the session id and last event number, and backfill with ?after= if resume fails.

Thanks to the presence grace period, friends don't see a wave of people going "offline" and back "online".

Read in post: Designing a Discord-style chat system
InterviewSeniorWhy ScyllaDB/Cassandra for messages, and what do you have to accept?

Because the access pattern is heavy writes and reads by channel and time: LSM writes are cheap, partitioning and replication are built in, and nodes are added online for data growing ~1 PB/year.

You accept: queries only by partition key, no joins, tombstones on delete, bounding partition size yourself with buckets, and choosing a consistency level per query.

Read in post: Designing a Discord-style chat system
Edge caseSeniorConsumer lag turns into a flood of false alarmsA worker hits a long GC pause or a 20-second rebalance: heartbeats keep arriving in Kafka but nobody reads them, while the worker's clock keeps running. Every deadline expires and 1 million alerts go out. How to stop it: Compute deadlines in data time (the timestamp the gateway puts on the record), and only let timers

A worker hits a long GC pause or a 20-second rebalance: heartbeats keep arriving in Kafka but nobody reads them, while the worker's clock keeps running. Every deadline expires and 1 million alerts go out. How to stop it:

  • Compute deadlines in data time (the timestamp the gateway puts on the record), and only let timers expire up to the "watermark" = the timestamp of the newest record read from that partition, not the machine clock.
  • If a partition's lag > a threshold (say 2 s), pause detection for that partition and raise a single infrastructure alert.
Read in post: Case study
Trade-offSeniorOption B (Redis ZSET) or C (Kafka + timing wheel)B: less code, shared state so any worker can check, no rebalance worries. But every heartbeat is a Redis command (333K/s → a cluster of 8–10 masters), and a slow Redis also produces false alarms. C: the hot path is just Kafka + RAM, it scales linearly with partitions, and replay comes for free. But you have to write th
  • B: less code, shared state so any worker can check, no rebalance worries. But every heartbeat is a Redis command (333K/s → a cluster of 8–10 masters), and a slow Redis also produces false alarms.
  • C: the hot path is just Kafka + RAM, it scales linearly with partitions, and replay comes for free. But you have to write the timing wheel yourself and handle rebalances and watermarks.
  • Below ~100K heartbeats/s, or if the team doesn't run Kafka yet: choose B. From a few hundred thousand heartbeats/s up, or if Kafka is already there: choose C.
Read in post: Case study
InterviewMidWhy not store last_seen in PostgreSQL on every heartbeat and scan it periodically?

333K UPDATEs/s is far beyond what one relational node can write (a few thousand to a few tens of thousands of writes/s), and every UPDATE creates a new row version that has to be VACUUMed.

Scanning WHERE last_seen < ... over 1M rows every few seconds is expensive too. This is transient state, so keep it in RAM or Redis, and let the DB store only state changes.

Read in post: Case study
InterviewMidHow do you detect expired devices with a Redis ZSET?

The score is the deadline: each heartbeat ZADDs and overwrites the score with now + timeout; every second a checker runs ZRANGEBYSCORE key -inf now to get the expired devices, raises alerts and ZREMs them.

Combine the fetch and the delete in Lua so two checkers don't emit duplicates. Split into several ZSETs by hash of device_id once the load exceeds one node.

Read in post: Case study
InterviewMidHow do you make one offline produce exactly one alert?

Emit a state-transition event (only on ONLINE → OFFLINE) and deduplicate at the alert sender with the key deviceId + offlineSince under a unique constraint.

Kafka delivers at least once, so an event can arrive twice; a deterministic key makes the receiver idempotent.

Read in post: Case study
InterviewSeniorA Kafka consumer is 30 seconds behind. How does your liveness system react?

It must not mass-report devices offline: deadlines are in data time and only expire up to the partition's watermark; once lag passes a threshold, detection pauses for that partition and one infrastructure incident is raised.

After it catches up, the worker processes the backlog of heartbeats, deadlines get extended correctly, and only devices that were truly silent get reported.

Read in post: Case study
InterviewSeniorWhy does partitioning by device_id matter in this design?

Every heartbeat from a device lands in the same partition, so exactly one worker holds that device's state and deadline, with no locks and no shared store.

You scale by adding partitions and workers. The price: a rebalance leaves the new worker without state, so you need a grace period or a rebuild from the compacted state topic.

Read in post: Case study
InterviewSeniorA whole region loses its network and 50,000 devices go offline at once. How do you handle alerts?

Group by region/tenant over a short window: once a ratio threshold is crossed, raise one "region disconnected" incident and hold back the per-device alerts.

When the region recovers, close the incident and only report the devices that are still offline. You need region info (cell tower, gateway) in the device data to group at all.

Read in post: Case study
InterviewSeniorHow would you scale the design to 5 million devices?

Load rises to ~1.7M heartbeats/s and state to ~500 MB: add Kafka partitions (say 256) and workers, scale the gateway horizontally; the timing wheel stays the same.

Check bandwidth (~170 MB/s inbound), consider batching heartbeats at the gateway (one record carrying many devices), and lower the heartbeat rate for device types with long thresholds (with a 5-minute threshold, one heartbeat every 60 s is enough).

Read in post: Case study
Edge caseMidThe slides' throughput doesn't match their own problem statementThe slides say "normal 1 QPS, peak 5M QPS". 1 QPS is far too small for 50M DAU; 5M QPS would mean all 50M DAU refreshing every 10 seconds. Derive it yourself from DAU and feed opens as above, then apply a peak factor of 3–5. Interviewers grade how you derive the number, not whether it's exactly right. The second line,

The slides say "normal 1 QPS, peak 5M QPS". 1 QPS is far too small for 50M DAU; 5M QPS would mean all 50M DAU refreshing every 10 seconds. Derive it yourself from DAU and feed opens as above, then apply a peak factor of 3–5. Interviewers grade how you derive the number, not whether it's exactly right.

The second line, "500 B/post", is really 500 bytes per comment (the formula 3 + 0.5 × 10 shows it).

Read in post: Designing a Threads-style news feed
Edge caseSeniorA feed partition that grows foreverfeed is partitioned by userid and only ever appended to. After a few years, a user who follows many people has a partition of tens of MB, which reads slowly and stresses compaction. Keep a TTL (say 30 days, since users only care about 7), or trim it periodically. Likewise, a celebrity's followers with 100M rows is one

feed is partitioned by user_id and only ever appended to. After a few years, a user who follows many people has a partition of tens of MB, which reads slowly and stresses compaction. Keep a TTL (say 30 days, since users only care about 7), or trim it periodically. Likewise, a celebrity's followers with 100M rows is one giant partition: add a bucket, (user_id, bucket).

Read in post: Designing a Threads-style news feed
Trade-offSeniorWhere to put the celebrity thresholdA low threshold (10K followers): less fan-out, but the read path merges more sources and gets slower. A high one (1M): fast reads, but every post from someone with 900K followers is still 900K writes. In practice: pick the threshold so fanning out one post stays under your delay target (for example 5 seconds at 100K wr

A low threshold (10K followers): less fan-out, but the read path merges more sources and gets slower. A high one (1M): fast reads, but every post from someone with 900K followers is still 900K writes.

In practice: pick the threshold so fanning out one post stays under your delay target (for example 5 seconds at 100K writes/s ⇒ ~500K followers), and measure how many celebrities an average user follows. The threshold is configuration, not a constant.

Read in post: Designing a Threads-style news feed
Trade-offMidTracking active users: big savings, more complexityIf only 20% of followers are active, fan-out drops 5× (116K → 23K writes/s) and the Redis inboxes shrink accordingly. The price: a liveness service, a topic, a segmentation service, and a "cold start" path where returning users go through one slower pull. Worth it at this scale; not for a small app.

If only 20% of followers are active, fan-out drops 5× (116K → 23K writes/s) and the Redis inboxes shrink accordingly. The price: a liveness service, a topic, a segmentation service, and a "cold start" path where returning users go through one slower pull. Worth it at this scale; not for a small app.

Read in post: Designing a Threads-style news feed
Edge caseSeniorUPDATE posts SET likes = likes + 1 for a viral postEvery like is a write to the same row: in a relational database that's lock contention on one row, in Redis it's a hot key on one node. 50K likes/s will queue up or choke that node. The fix: batch in the counter service (as above), or split the counter into N sub-keys likes:{id}:{0..15} and sum them on read. Never coun

Every like is a write to the same row: in a relational database that's lock contention on one row, in Redis it's a hot key on one node. 50K likes/s will queue up or choke that node.

The fix: batch in the counter service (as above), or split the counter into N sub-keys likes:{id}:{0..15} and sum them on read. Never count with COUNT(*) on the reactions table at read time.

Read in post: Designing a Threads-style news feed
InterviewMidWhat's the difference between fan-out on write and fan-out on read?

On write (push): publishing copies the post id into every follower's inbox, so reading is very fast. On read (pull): opening the feed gathers posts from everyone you follow, so writes are cheap but reads are slow.

Push breaks on celebrities and inactive users; pull breaks on latency when you follow many people. In practice you go hybrid.

Read in post: Designing a Threads-style news feed
InterviewMidWhy does the feed store only post ids instead of the whole post?

Because one post sits in thousands of inboxes: storing content multiplies memory by thousands, and every edit or delete would have to update thousands of places.

Store the id (8 bytes) and hydrate content, author and counters from cache with one MGET at read time. Deleted posts are filtered during hydration.

Read in post: Designing a Threads-style news feed
InterviewMidWhy paginate the feed with a cursor rather than an offset?

Because new posts keep landing at the top: with an offset, page 2 shifts and users see posts again or miss some.

The cursor is the last post id returned; the next page takes ids smaller than it. With Snowflake post ids, that's time order.

Read in post: Designing a Threads-style news feed
InterviewSeniorA celebrity with 100 million followers posts. What does your system do?

No fan-out. The post only goes into the "recent celebrity posts" cache; when a follower opens their feed, the feed service pulls it and merges it with their inbox.

Notifications go out in rate-limited batches. That post's key will be very hot, so add an in-process cache and replicate the key.

Read in post: Designing a Threads-style news feed
InterviewSeniorDesign the feed read path to stay under 100 ms.

Read the precomputed inbox from Redis, read new posts from followed celebrities from cache, k-way merge to 20 ids, then hydrate in parallel with MGET.

No database read on the hot path. If the inbox is empty (a returning user), build it once by pulling and store it.

Read in post: Designing a Threads-style news feed
InterviewSeniorA user unfollows A. What happens to A's posts in their inbox?

Don't delete them immediately; during hydration, drop posts from authors no longer in the (cached) following set, and let a background job clean the inbox later.

Synchronous deletes across inboxes are unnecessary writes; filtering on read is cheap because the following set is already cached.

Read in post: Designing a Threads-style news feed
InterviewSeniorHow do you cut fan-out cost for hundreds of millions of inactive users?

Track active users with a heartbeat on app open (gated by SET NX EX once a day), push only to active ones, and build the feed by pulling once for anyone returning after a long break.

Fan-out shrinks by the share of active users; the price is a liveness service, a segmentation service and a cold-start path.

Read in post: Designing a Threads-style news feed
InterviewSeniorLike counters for a viral post getting 50K likes per second: how do you design them?

Each like writes one (post_id, user_id) row so it can't be duplicated and emits an event to Kafka; a counter service batches them into one HINCRBY, and periodically copies counts to the DB.

No direct UPDATE ... SET likes = likes + 1 (hot row), no COUNT(*) on read. You can also split the counter into several sub-keys.

Read in post: Designing a Threads-style news feed
Trade-offMidDesign-first vs code-first OpenAPIDesign-first: write the OpenAPI spec (YAML) first, review it, then generate server/client stubs or check the code against the spec. Pros: early contract review, the frontend mocks it right away, breaking changes show up in the spec diff. Cons: one more artefact to keep in sync, and you need tooling (openapi-generator,
  • Design-first: write the OpenAPI spec (YAML) first, review it, then generate server/client stubs or check the code against the spec. Pros: early contract review, the frontend mocks it right away, breaking changes show up in the spec diff. Cons: one more artefact to keep in sync, and you need tooling (openapi-generator, spec checks in CI).
  • Code-first: write the controllers and generate the spec with springdoc-openapi. Pros: fast, the spec always matches the code. Cons: nobody sees the contract until it's implemented, and internals (class names, fields) leak easily.
  • Design-first for public APIs or APIs shared by many teams; code-first is fine for an internal API owned by one team. Either way, run an OpenAPI diff in CI to catch breaking changes.
Read in post: Advanced REST API design
Edge caseMidIdempotency is about server state, not identical responsesThe course slide defines idempotent as "the response is the same", which is imprecise: RFC 9110 talks about the effect on the server. DELETE /users/34 returns 204 the first time and 404 the second, but the state is the same (user 34 is gone), so it's still idempotent. GET /time returns a different body every time and i

The course slide defines idempotent as "the response is the same", which is imprecise: RFC 9110 talks about the effect on the server. DELETE /users/34 returns 204 the first time and 404 the second, but the state is the same (user 34 is gone), so it's still idempotent. GET /time returns a different body every time and is still safe and idempotent. Don't force the second DELETE to return 204 just to "be idempotent".

Read in post: Advanced REST API design
Trade-offSeniorService name in public URLs vs gateway mappingService name in the path (/order-service/v1/orders): the gateway routes with a single prefix rule and each team owns its namespace. Cons: it exposes your internal topology; when you split or merge services (say, pulling payment out of order-service), the public URL changes, which is a breaking change. Gateway maps reso
  • Service name in the path (/order-service/v1/orders): the gateway routes with a single prefix rule and each team owns its namespace. Cons: it exposes your internal topology; when you split or merge services (say, pulling payment out of order-service), the public URL changes, which is a breaking change.
  • Gateway maps resources (/v1/orders → order-service): URLs stay stable and business-oriented, and internal re-architecture doesn't affect clients. Cons: someone has to maintain the gateway route table, and two teams can fight over a prefix.
  • In practice: internal APIs keep the service name; public APIs for mobile or partners are mapped by resource at the gateway or a BFF (a backend dedicated to one kind of client).
Read in post: Advanced REST API design
Edge caseSeniorBase64 is not encryption: clients can edit the cursorA base64 cursor is only "opaque" as a contract; anyone can decode and modify it. If it only carries a position (createdat, id), that's fine, because the server re-applies every filter and permission check on each request. It's dangerous to stuff filters or a tenantid into the cursor and trust them: edit the cursor and

A base64 cursor is only "opaque" as a contract; anyone can decode and modify it. If it only carries a position (created_at, id), that's fine, because the server re-applies every filter and permission check on each request. It's dangerous to stuff filters or a tenant_id into the cursor and trust them: edit the cursor and you read another tenant's data. The fix: keep authorisation conditions out of the cursor, or sign it with an HMAC and reject tampered ones; let cursors expire when you change their format.

Read in post: Advanced REST API design
Edge caseSeniorOn PostgreSQL a deferred join only pays off once the visibility map is vacuumedA deferred join relies on an index-only scan (answering from the index alone, without reading the table). PostgreSQL indexes carry no visibility information, so an index-only scan can skip the heap only for pages the visibility map marks as "all-visible". I ran it right after loading the data (before any VACUUM): the p

A deferred join relies on an index-only scan (answering from the index alone, without reading the table). PostgreSQL indexes carry no visibility information, so an index-only scan can skip the heap only for pages the visibility map marks as "all-visible". I ran it right after loading the data (before any VACUUM): the plan said Heap Fetches: 150010 and the deferred join was actually slower than plain OFFSET (12 ms vs 5 ms). After VACUUM ANALYZE it showed Heap Fetches: 0 and read about 10× fewer pages.

On a heavily updated table don't assume the trick always helps; measure it with EXPLAIN (ANALYZE, BUFFERS). MySQL InnoDB doesn't have this issue, because secondary indexes always contain the primary key and can be read directly.

Read in post: Advanced REST API design
Trade-offMidReturn a total count or notExact total: the UI can render "page 1 of 523". Cost: an extra COUNT() scanning every matching row on every request, sometimes slower than the data query itself. Only hasnext (fetch limit + 1 rows): cheap, enough for infinite scroll and a "Next" button. An estimate: PostgreSQL's reltuples in pgclass or the row estimate
  • Exact total: the UI can render "page 1 of 523". Cost: an extra COUNT(*) scanning every matching row on every request, sometimes slower than the data query itself.
  • Only has_next (fetch limit + 1 rows): cheap, enough for infinite scroll and a "Next" button.
  • An estimate: PostgreSQL's reltuples in pg_class or the row estimate from EXPLAIN; show "about 52,000 results" like search engines do.
  • A capped count: SELECT count(*) FROM (SELECT 1 FROM ... LIMIT 10001) t, rendered as "10,000+". Default for public APIs: has_next + cursor. Admin screens that need page numbers get a capped count or a cached count.
Read in post: Advanced REST API design
Edge caseMidSorting by arbitrary fields is an injection hole and a full scanPassing sort straight from the query string into ORDER BY opens the door to SQL/JPQL injection through the column name and to full scans, even through Spring Data's Sort.by(param) with a user-supplied property name. Always map through an allowlist, limit the number of sort fields (say, 3), and append id as a tie-breake

Passing sort straight from the query string into ORDER BY opens the door to SQL/JPQL injection through the column name and to full scans, even through Spring Data's Sort.by(param) with a user-supplied property name. Always map through an allowlist, limit the number of sort fields (say, 3), and append id as a tie-breaker so pagination doesn't repeat or skip rows when sort values tie.

Read in post: Advanced REST API design
Trade-offSeniorBulk endpoints: all-or-nothing or per-item resultsWhen you add 3 students and s2 doesn't exist: All-or-nothing (one transaction, any error rolls everything back): easy to reason about, the client retries the whole batch. Doesn't fit large batches or cases where partial failure is normal. Partial success: return 207 Multi-Status, or 200 with a list like {"studentid": "

When you add 3 students and s2 doesn't exist:

  • All-or-nothing (one transaction, any error rolls everything back): easy to reason about, the client retries the whole batch. Doesn't fit large batches or cases where partial failure is normal.
  • Partial success: return 207 Multi-Status, or 200 with a list like {"student_id": "s2", "status": "NOT_FOUND"}. Flexible, but the client handles each result and retries must be idempotent (re-adding s1 must not fail), so use upserts or ON CONFLICT DO NOTHING. Whichever you pick, cap the batch size (say, 100) and document the behaviour.
Read in post: Advanced REST API design
InterviewJuniorWhat's the difference between safe and idempotent? Give a method that is idempotent but not safe.

Safe means not changing server state; idempotent means once or N times ends in the same state. PUT and DELETE are idempotent but not safe.

Every safe method (GET, HEAD) is idempotent, but not the other way round: PUT and DELETE change data yet repeating them yields the same state. Idempotency doesn't require identical responses: a second DELETE may return 404.

Read in post: Advanced REST API design
InterviewJuniorWhy must you document whether page starts at 0 or 1?

Because the two sides default differently (Spring Data starts at 0, many UIs at 1), and a mismatch loses or repeats a page without any error.

Document it, validate negative values, and cap size.

Read in post: Advanced REST API design
InterviewMidWhy is OFFSET slow on big tables, and what other problem does it have?

The database reads and discards every row before the offset, so the cost grows linearly with page depth; and data changing between calls makes rows go missing or repeat.

A COUNT(*) for the total also scans every matching row. Resource skipping: rows deleted or inserted between two calls slide across page boundaries. For a data-sync job, a missed row is lost data.

Read in post: Advanced REST API design
InterviewMidWhat does cursor pagination need to be correct?

A unique, stable sort key, an index that matches the ORDER BY, and an opaque cursor.

Add id as a tie-breaker and avoid columns that change often. The cursor is opaque so clients don't depend on internals. The server still re-applies every filter and permission check on each request and never trusts data inside the cursor. The cost is that you can't jump to an arbitrary page.

Read in post: Advanced REST API design
InterviewMidWhat is a deferred join and when doesn't it help?

Paginate over a small index that only returns ids, then join back for full rows for just that page; fewer pages read, but still O(offset).

It doesn't help when the index can't answer the subquery on its own (so the table is read anyway), or on PostgreSQL when the visibility map hasn't been vacuumed, in which case the index-only scan still visits the heap and can be slower than the plain query.

Read in post: Advanced REST API design
InterviewMidWhy allowlist sortable fields?

Because column names in ORDER BY can't be bound like parameters, so concatenating them is SQL injection; and sorting by an unindexed column causes a full scan.

A full scan plus a memory-hungry sort hurts on a big table; an allowlist exposes only indexed fields. Append id as a tie-breaker so the order is deterministic during pagination.

Read in post: Advanced REST API design
InterviewSeniorShould the service name be part of a public URL?

Not for public APIs: splitting or merging services changes the URL, which is a breaking change. For internal APIs it's fine.

A service name in the path lets the gateway route with one prefix rule and each team own its namespace, but it exposes internal structure. I keep service names for internal service-to-service APIs, and map public APIs for mobile or partners by resource at the gateway or a BFF so URLs stay stable and business-oriented.

Read in post: Advanced REST API design
InterviewSeniorHow would you design an endpoint that adds many items at once?

Cap the batch size and pick explicit semantics: all-or-nothing in one transaction, or partial success with a result per item.

All-or-nothing is easy to reason about; the client retries the whole batch. Partial success returns 207, or 200 with a status list; then retries must be idempotent: re-adding an existing item must not fail, so use an upsert or ON CONFLICT DO NOTHING. Document the behaviour and test the failure-in-the-middle case.

Read in post: Advanced REST API design
Edge caseMidThe slides are wrong about Snowflake and random IDsSnowflake IDs don't collide as long as each machine has its own worker id and the clock never goes backwards: 41 bits of time, 10 bits of machine, 12 bits of sequence. The real reasons to drop it: 64 bits need 11 Base62 characters (62¹¹ ≈ 5.2 × 10¹⁹ ≥ 2⁶⁴), over the 8-character limit; and codes grow with time, so they'

Snowflake IDs don't collide as long as each machine has its own worker id and the clock never goes backwards: 41 bits of time, 10 bits of machine, 12 bits of sequence. The real reasons to drop it: 64 bits need 11 Base62 characters (62¹¹ ≈ 5.2 × 10¹⁹ ≥ 2⁶⁴), over the 8-character limit; and codes grow with time, so they're guessable.

Random IDs really do collide: scattering 1.46 × 10¹⁰ codes over 62⁸ slots gives about n²/2N ≈ 490 thousand expected collisions. But you don't need "coordination between servers": a uniqueness constraint in the DB (INSERT ... IF NOT EXISTS) plus a retry is enough. The price is that every write is a conditional write, which in ScyllaDB means a lightweight transaction (Paxos, ~4 round trips).

Read in post: Designing a URL shortener
Trade-offMidToken ranges trade continuity for availabilityYou get: no collisions, short codes, no network call per write, and if the coordinator dies the instances keep going until their blocks run out. You give up: codes aren't ordered by time (instance A issues 5 while instance B issues 1,000,007 at the same moment), numbers are wasted when an instance dies, and there's one

You get: no collisions, short codes, no network call per write, and if the coordinator dies the instances keep going until their blocks run out.

You give up: codes aren't ordered by time (instance A issues 5 while instance B issues 1,000,007 at the same moment), numbers are wasted when an instance dies, and there's one more component (ZooKeeper) to run. If you'd rather not add ZooKeeper, a single PostgreSQL row is enough at this load.

Read in post: Designing a URL shortener
Edge caseSeniorLook up the secondary index, then write: two requests for the same URL create two codesTwo requests to shorten the same URL arrive almost together: both check the index, both see nothing, both create a new code. An asynchronously updated index widens that window. The fix: use the urlbyhash table as the "lock": INSERT INTO urlbyhash (longurlhash, code) VALUES (?, ?) IF NOT EXISTS. The winner goes on to wr

Two requests to shorten the same URL arrive almost together: both check the index, both see nothing, both create a new code. An asynchronously updated index widens that window.

The fix: use the url_by_hash table as the "lock": INSERT INTO url_by_hash (long_url_hash, code) VALUES (?, ?) IF NOT EXISTS. The winner goes on to write urls; the loser reads back the existing code and returns it. Normalise the URL before hashing (lowercase host, drop trailing /, sort query params) so two spellings of the same page hash the same.

Read in post: Designing a URL shortener
Trade-offMid301 or 302 for the redirect301 Moved Permanently: browsers and proxies may remember it. Later clicks go straight to the target and the server never knows. Less load, and SEO link equity passes to the target. You lose analytics and can't change the target any more. 302 Found (or 307): not remembered by default, so every click hits the server. You
  • 301 Moved Permanently: browsers and proxies may remember it. Later clicks go straight to the target and the server never knows. Less load, and SEO link equity passes to the target. You lose analytics and can't change the target any more.
  • 302 Found (or 307): not remembered by default, so every click hits the server. You get analytics and can change or disable links. More load.

There's a hybrid: return 301 with Cache-Control: private, max-age=90 so the browser only remembers briefly (Bitly used to do this). With an "analytics" requirement I'd pick 302 with Cache-Control: private, max-age=0.

Read in post: Designing a URL shortener
InterviewJuniorWhy Base62 rather than Base64 for short codes?

Base62 (a-zA-Z0-9) is the largest alphabet that needs no escaping in URLs; Base64 has + and /, which must be encoded.

A bigger alphabet means shorter codes: 7 Base62 characters hold ~3.5 trillion values, while Base36 needs 8 characters for the same amount.

Read in post: Designing a URL shortener
InterviewJuniorHow long must the code be for 10 million links a day over 4 years?

6 Base62 characters is enough (62⁶ ≈ 5.7 × 10¹⁰ > 1.46 × 10¹⁰ links); pick 7 for about 240× headroom.

The arithmetic: 10⁷ × 365 × 4 ≈ 1.46 × 10¹⁰. The headroom makes random IDs collide less and lets you waste numbers when an instance dies.

Read in post: Designing a URL shortener
InterviewMidCompare four ways to generate short codes and pick one.

Random (collides, needs conditional writes), hash (collides when truncated, same URL gives same code), Snowflake (no collisions but 11 characters and guessable), token range (no collisions, 7 characters, no coordination per write). Pick token ranges and shuffle the number before Base62.

Also state the cost: a coordinator to lease blocks, and wasted numbers when an instance dies.

Read in post: Designing a URL shortener
InterviewMid301 or 302 for a link shortener that tracks clicks?

302: every click goes through the server, so you can count it and change or disable the link. A 301 is remembered by the browser, which cuts load but loses analytics.

Analytics are sent asynchronously through Kafka so they never slow down the redirect.

Read in post: Designing a URL shortener
InterviewMidThe read path takes 35K requests per second at peak. How do you design the cache?

Cache-aside on Redis with a ~1-day TTL; cache empty results or use a Bloom filter for unknown codes; add an in-process cache for viral links.

Memory for hot links is only a few GB. If Redis dies, read straight from ScyllaDB, which can handle this load.

Read in post: Designing a URL shortener
InterviewSeniorToken ranges produce sequential numbers, so codes are guessable. How do you fix that without collisions?

Run the number through a keyed permutation over a fixed domain (for example a 42-bit Feistel network) before Base62; a permutation is a bijection, so codes stay unique but the next one can't be inferred.

To force exactly 7 characters, use cycle-walking. The Sqids library does something similar.

Read in post: Designing a URL shortener
InterviewSeniorNew requirement: each long URL gets exactly one code. How do you stop two concurrent requests from creating two codes?

Use a url_by_hash table with INSERT ... IF NOT EXISTS keyed by the SHA-256 of the normalised URL; the loser reads back the existing code.

Don't rely on a secondary index (asynchronous in ScyllaDB), and don't let a Bloom filter decide (use it only to skip the read when the URL is definitely new).

Read in post: Designing a URL shortener
InterviewSeniorThe ZooKeeper cluster that leases token ranges is down for 30 minutes. What happens?

Almost nothing: every instance still has a block in memory, and at 116 writes/s a block of 1 million lasts over 2 hours. Only an instance that just started or just ran out can't create links.

To be safer, lease the next block when 20% of the current one remains, and keep reads (redirects) completely independent of ZooKeeper.

Read in post: Designing a URL shortener
Edge caseMidPCI DSS 3.2.1 is retired, and the fees on the slide are a snapshotThe slide shows most providers at PCI DSS 3.2.1. That version was retired by the PCI SSC on 31 March 2024; the current version is 4.0.1, whose "future-dated" requirements became mandatory on 31 March 2025 (for example MFA for all access to the cardholder data environment, and control of scripts on payment pages). Ask f

The slide shows most providers at PCI DSS 3.2.1. That version was retired by the PCI SSC on 31 March 2024; the current version is 4.0.1, whose "future-dated" requirements became mandatory on 31 March 2025 (for example MFA for all access to the cardholder data environment, and control of scripts on payment pages). Ask for a valid Attestation of Compliance (AOC) rather than trusting a line on their website. Fee schedules are negotiable and change over time, so record the decision in an ADR (Architecture Decision Record) along with the date the numbers were taken.

Read in post: Third-party integration
Trade-offSeniorOne provider or severalOne provider: integrate once, reconcile one source, easier to negotiate volume pricing. But their incident is your lost revenue, and switching is hard. Several providers: failover when one dies, routing by fee or success rate. The cost is a shared abstraction, reconciling multiple sources, twice the testing. SMS OTP: s
  • One provider: integrate once, reconcile one source, easier to negotiate volume pricing. But their incident is your lost revenue, and switching is hard.
  • Several providers: failover when one dies, routing by fee or success rate. The cost is a shared abstraction, reconciling multiple sources, twice the testing.
  • SMS OTP: several providers is close to mandatory, because delivery rates swing by carrier and time of day.
  • Payment gateways: start with one, behind your own interface (section 4), so adding a second doesn't mean rewriting the checkout flow.
Read in post: Third-party integration
Trade-offSeniorTrust webhooks, polling, or bothWebhooks are low-latency and cost no requests, but may never arrive: your endpoint was down when they called and they ran out of retries, a wrong URL, a firewall. Polling is more dependable but slower and eats quota. A robust design uses both, through the same idempotent update function: 1. The webhook is the main path

Webhooks are low-latency and cost no requests, but may never arrive: your endpoint was down when they called and they ran out of retries, a wrong URL, a firewall. Polling is more dependable but slower and eats quota.

A robust design uses both, through the same idempotent update function:

  1. The webhook is the main path.
  2. When the user comes back, or a request passes its deadline without a result, actively query the status (step 9.2.3 on the course's "improvements" slide).
  3. A scheduled job sweeps stuck requests, for when both paths above are missed.
  4. Daily reconciliation against the provider's files, as in the reconciliation post.
Read in post: Third-party integration
Edge caseSeniorVerifying the signature on re-serialized JSON instead of the raw bodyThe controller takes @RequestBody WebhookEvent event, then computes the HMAC over objectMapper.writeValueAsString(event). The re-serialized string almost certainly differs from the original bytes: field order, whitespace, number formatting, whether Unicode is escaped. The result: a signature that "sometimes fails", unt

The controller takes @RequestBody WebhookEvent event, then computes the HMAC over objectMapper.writeValueAsString(event). The re-serialized string almost certainly differs from the original bytes: field order, whitespace, number formatting, whether Unicode is escaped. The result: a signature that "sometimes fails", until someone turns verification off to make it work.

Always take the raw body (@RequestBody byte[] raw or String), verify against exactly those bytes, and only then parse. For gateways like VNPay that sign the query string, the equivalent bug is re-encoding parameters differently from the gateway.

Read in post: Third-party integration
Edge caseMidWebhooks arrive duplicated, late and out of orderSenders deliver at least once (one or more times). payment.refunded can arrive before payment.succeeded when the first delivery of the latter failed and was retried later. Applying events in arrival order overwrites the newer state with the older one. Dedupe by event id. Move state through a forward-only state machine

Senders deliver at least once (one or more times). payment.refunded can arrive before payment.succeeded when the first delivery of the latter failed and was retried later. Applying events in arrival order overwrites the newer state with the older one.

  • Dedupe by event id.
  • Move state through a forward-only state machine (a conditional UPDATE on the current state).
  • When in doubt, treat the webhook as a "something changed" signal and call their API for the latest state.
Read in post: Third-party integration
TILMidRecording "what we replied" matters as much as "what they sent"In a dispute ("the gateway says it sent the IPN, we say we never got it"), the receiving side's logs often only have the incoming request. The real question is which code you replied with and how fast: reply 99 or time out and they retry, reply 00 and they stop. Storing the reply code and handling time next to the call

In a dispute ("the gateway says it sent the IPN, we say we never got it"), the receiving side's logs often only have the incoming request. The real question is which code you replied with and how fast: reply 99 or time out and they retry, reply 00 and they stop. Storing the reply code and handling time next to the callback record answers that immediately, and exposes subtle bugs like a handler that replies 00 before its transaction commits.

Read in post: Third-party integration
InterviewJuniorWhat is a webhook, and how is it different from polling?

A webhook is the third party calling an endpoint of yours when something happens; polling is you asking them periodically.

Webhooks are fast and cheap in requests, but they can be lost, duplicated or reordered, and they need a public endpoint protected by a signature. Polling is more dependable but slower and eats quota. A good system uses webhooks as the main path and polling as the safety net.

Read in post: Third-party integration
InterviewJuniorWhy must a webhook or IPN handler be idempotent?

Because senders deliver at least once, so the same event can arrive several times, even twice at the same moment.

They resend when they don't get a valid reply in time (a VNPay-style gateway resends up to about 10 times in 5 minutes). A non-idempotent handler credits money twice or decrements stock twice. Dedupe by event id and apply state changes with a conditional UPDATE so the second delivery does nothing.

Read in post: Third-party integration
InterviewMidHow do you protect a webhook endpoint?

Verify the signature on the raw body, block replays with a signed timestamp and the event id, then store and return 2xx fast.

  • Verify the HMAC (or digital signature) on the raw body, with a constant-time comparison.
  • Check a timestamp inside the signed content; dedupe by event id.
  • Filter source IPs as an extra layer.
  • Store the event verbatim, return 2xx fast, process later.
  • A forward-only state machine so duplicates and reordering are harmless.
  • Reply with the documented codes, because they decide whether the sender retries.
Read in post: Third-party integration
InterviewMidWhy wrap a provider behind your own interface?

So the provider's status codes, DTOs, amount units and signing rules don't leak into business code (an anti-corruption layer).

Switching or adding a provider means adding an adapter. Business tests use a fake of the interface. Unknown codes map to an Unknown state that raises an alert instead of being mistaken for success.

Read in post: Third-party integration
InterviewMidA refunded webhook arrives before succeeded. How do you handle it?

Don't apply events in arrival order: a forward-only state machine ignores an older event that arrives late instead of letting it overwrite.

Apply transitions with a conditional UPDATE on the current state. When an event doesn't fit the current state, treat it as a signal, call the provider's API for the latest state, and apply that through the same update function. Store every event verbatim for investigation.

Read in post: Third-party integration
InterviewSeniorHow do you choose between two payment gateways, and how do you keep the option to switch?

Evaluate security, reliability, performance and complexity, plus cost, and record it in an ADR; keep switching possible with your own interface and adapters.

  • Criteria: current PCI DSS (ask for the AOC), how requests are signed and callbacks protected, SLA and incident history, a status-query API and reconciliation files, settlement timing, total fees (per transaction, fixed, refunds), sandbox quality and support.
  • Record the decision in an ADR with the date of the numbers.
  • To keep switching possible: a PaymentGateway interface, one adapter per provider, a provider-independent payment-attempt table, no card data on your side (redirect or hosted fields), contract tests per adapter.
Read in post: Third-party integration
InterviewSeniorAn eKYC integration returns results after 5–60 seconds. Synchronous or asynchronous?

Asynchronous: holding a user request for 60 seconds holds a thread, tends to hit load balancer timeouts and can't absorb retries.

Create the request through a queue and worker, with the request id as the idempotency key. Receive the result via a signed webhook, plus a job that queries the status of requests stuck past their deadline. The frontend shows "verifying" and asks your backend (polling or server-sent events), never the provider directly.

Read in post: Third-party integration
Edge caseMidUpdating payment status from the return URL's parametersThe return URL goes through the browser: the user can edit vnpResponseCode=00 in the address bar, and if they close the tab after paying, the request never arrives. Settling status from the return URL both invites fraud and misses paid orders. Even with signature checks, an attacker can replay another order's successfu

The return URL goes through the browser: the user can edit vnp_ResponseCode=00 in the address bar, and if they close the tab after paying, the request never arrives. Settling status from the return URL both invites fraud and misses paid orders. Even with signature checks, an attacker can replay another order's successful URL unless you check the order id and amount.

The return URL only brings the user to a result page and triggers the frontend to ask the backend. Status is updated by the IPN and the transaction-query job.

Read in post: Integrating a VNPay-style payment gateway
Trade-offSeniorOne txn_ref per booking or one txn_ref per attemptBooking code as vnpTxnRef: simple, easy to look up on the gateway. But a VNPay-style gateway won't accept a used reference again (the docs require uniqueness, at least within the day): a failed first attempt can't be retried, and you can't tell an old attempt's callback from a new one's. One txnref per attempt (PAY-<bo
  • Booking code as vnp_TxnRef: simple, easy to look up on the gateway. But a VNPay-style gateway won't accept a used reference again (the docs require uniqueness, at least within the day): a failed first attempt can't be retried, and you can't tell an old attempt's callback from a new one's.
  • One txn_ref per attempt (PAY-<booking>-<n>): free retries, every callback matches exactly one payment row, clear history. You must handle two attempts both succeeding (two open tabs): the second becomes REFUND_PENDING.
  • A partial unique index (unique only over rows matching its WHERE) allows at most one PENDING payment per booking: clicking "pay" again while the old URL is valid returns that same URL.
Read in post: Integrating a VNPay-style payment gateway
Edge caseSeniorThe signature fails because URL-encoding at signing time differs from the gateway'sThe number one "invalid checksum" error isn't a wrong key but a different string being signed. Java's URLEncoder.encode turns a space into +; JavaScript's encodeURIComponent and many HTTP clients produce %20. Tested: Thanh toan becomes vnpOrderInfo=Thanh+toan versus vnpOrderInfo=Thanh%20toan, two byte strings and so tw

The number one "invalid checksum" error isn't a wrong key but a different string being signed. Java's URLEncoder.encode turns a space into +; JavaScript's encodeURIComponent and many HTTP clients produce %20. Tested: Thanh toan becomes vnp_OrderInfo=Thanh+toan versus vnp_OrderInfo=Thanh%20toan, two byte strings and so two signatures.

Other sources of drift: not sorting by name, signing empty parameters, signing the decoded string while the gateway signs the encoded one, letting the framework decode IPN parameters and re-signing them differently. Write a fixed test with a parameter set and expected signature (from the docs or a real sandbox transaction) so any change to the signing code is caught.

Read in post: Integrating a VNPay-style payment gateway
Edge caseMidForgetting the ×100 or comparing amounts in the wrong unitA VNPay-style gateway takes and returns vnpAmount as the amount times 100 (6,820,000 VND is 682000000). Forget to multiply and the customer pays 68,200 VND for a 6.8 million ticket while the gateway reports success; multiply twice and they're asked for 682 million. On the IPN side, forgetting to divide by 100 before co

A VNPay-style gateway takes and returns vnp_Amount as the amount times 100 (6,820,000 VND is 682000000). Forget to multiply and the customer pays 68,200 VND for a 6.8 million ticket while the gateway reports success; multiply twice and they're asked for 682 million. On the IPN side, forgetting to divide by 100 before comparing with payment.amount rejects every transaction as "invalid amount".

Convert units in exactly one place (a GatewayAmount type or a toGateway/fromGateway pair), use long and Math.multiplyExact, and test with real product amounts.

Read in post: Integrating a VNPay-style payment gateway
Trade-offSeniorStoring the raw callback in its own transaction or together with processingSame transaction as the status change: simple, callback and outcome always consistent. But when processing fails and rolls back (a deadlock, a bug), the callback row disappears too, exactly when you need it to investigate. Separate transaction, committed first (like callbackLog.save above): the callback is always there
  • Same transaction as the status change: simple, callback and outcome always consistent. But when processing fails and rolls back (a deadlock, a bug), the callback row disappears too, exactly when you need it to investigate.
  • Separate transaction, committed first (like callbackLog.save above): the callback is always there, even when processing fails or the signature is wrong. In exchange you may have callback rows with no matching state change, so reply_code is updated afterwards to show what you replied.
  • Centralized logs instead of the DB: no extra DB write load, but hard to join with payments during reconciliation, and dependent on log retention.

For payments, choose a separate transaction: the callback table is your evidence in disputes with the gateway or the customer.

Read in post: Integrating a VNPay-style payment gateway
Edge caseSeniorSlow work in the IPN handler makes the gateway resend and piles up loadThe gateway waits only briefly for an IPN reply; past that it treats the call as failed and resends. Per the course slides, VNPay resends when the merchant replies 01, 04, 97, 99 or doesn't answer in time, up to 10 times within about 5 minutes (check the current docs). So the handler must cope with sequential duplicate

The gateway waits only briefly for an IPN reply; past that it treats the call as failed and resends. Per the course slides, VNPay resends when the merchant replies 01, 04, 97, 99 or doesn't answer in time, up to 10 times within about 5 minutes (check the current docs). So the handler must cope with sequential duplicates and two IPNs arriving at once.

Calling ticketing, email or e-invoicing before replying makes timeouts likely and reruns the whole chain on every resend. The handler should only: store the callback, check the signature, run the state-change transaction, insert an outbox row (a table of pending work written in the same transaction, which a worker processes after commit), and reply. Measure the IPN endpoint's p99 and alert when it nears the gateway's timeout.

Read in post: Integrating a VNPay-style payment gateway
TILMidA redirect flow shrinks the merchant's PCI DSS scopePCI DSS is the security standard for any system that stores, processes or transmits card data. When the customer types the card number on the gateway's page, our servers never see it, and the merchant usually only completes the shortest self-assessment questionnaire (SAQ A) instead of an audit of the whole infrastructu

PCI DSS is the security standard for any system that stores, processes or transmits card data. When the customer types the card number on the gateway's page, our servers never see it, and the merchant usually only completes the shortest self-assessment questionnaire (SAQ A) instead of an audit of the whole infrastructure.

Building your own card form "to look nicer" and sending card numbers through the API pulls the backend, logs and database into audit scope. That's a technical reason, not just convenience, to keep the redirect flow or use the gateway's embedded fields.

Read in post: Integrating a VNPay-style payment gateway
InterviewJuniorWhat is an IPN and how does it differ from the return URL?

The IPN is a signed server-to-server callback and the source of truth; the return URL is the browser coming back, for display only.

An IPN (Instant Payment Notification) goes straight from the gateway to our backend and is resent until the gateway gets a valid reply. The return URL's parameters can be edited, and it may never arrive if the customer closes the tab.

Read in post: Integrating a VNPay-style payment gateway
InterviewJuniorWhy must the backend compute the amount rather than take it from the frontend?

Because the frontend is in the user's hands: editing a request to pay 1,000 VND for a 6 million ticket takes seconds.

The backend computes the amount from the booking in the DB and signs it into the URL. The gateway checks the signature so the amount can't change in transit, and on the IPN the backend compares the amount with the DB again.

Read in post: Integrating a VNPay-style payment gateway
InterviewMidWhat does the HMAC signature on the payment URL protect, and what doesn't it?

It protects integrity and origin; it doesn't stop replay, doesn't hide content, and is useless once the secret leaks.

Without the hash secret nobody can change the amount, order id or return URL, and a forged IPN won't have a valid signature. Replaying a valid message needs the state machine and unique constraints; secrecy needs HTTPS; a leaked secret needs a secret manager and rotation.

Read in post: Integrating a VNPay-style payment gateway
InterviewMidIn what order should an IPN handler check things, and which codes does it reply with?

Store raw → signature (97) → order (01) → amount (04) → already settled (02) → state change (00); system errors reply 99 so the gateway resends.

Compare the amount in the right unit (divide by 100). Failed results are recorded too and answered with 00 so the gateway stops sending.

Read in post: Integrating a VNPay-style payment gateway
InterviewMidWhy keep a payment table separate from the booking?

Because one booking has several payment attempts, and each attempt needs its own reference.

A declined card, an expired URL or a different method each create a new attempt; the gateway won't accept a repeated reference, and each callback must match exactly one attempt. A separate table gives a clear history, allows a partial unique "at most one open attempt", and handles two attempts both succeeding.

Read in post: Integrating a VNPay-style payment gateway
InterviewSeniorWhat do you say when asked to send the confirmation email right inside the IPN handler?

Don't: write an outbox row in the same transaction as the state change, and let a worker send the email after commit.

Email can't join a DB transaction: send before commit and you email about orders that roll back; send after commit and a crash in between loses the email. It also slows the handler, so the gateway times out and resends. The worker sends idempotently per booking; the IPN handler only changes state and replies fast.

Read in post: Integrating a VNPay-style payment gateway
InterviewSeniorA customer reports "I paid but the site says it failed". How do you investigate?

Start from gateway_callback by txn_ref, ask the gateway through the query API in parallel, and check the frontend last.

  • Did the IPN arrive, was the signature valid, what did we reply.
  • No IPN: check the IPN URL registered with the gateway and the reverse proxy logs. Replied 97: suspect an encoding mismatch in signing. Replied 04: suspect the unit conversion.
  • Call the transaction-query API for the gateway's truth and run apply if it says paid.
  • Frontend: does the return page poll the backend when the IPN is late, or conclude from URL parameters?
Read in post: Integrating a VNPay-style payment gateway
Edge caseMidJava's default HTTP clients wait foreverHttpURLConnection and SimpleClientHttpRequestFactory (RestTemplate's default factory when no other HTTP library is present) have connect and read timeouts of 0, meaning they never expire. java.net.http.HttpClient has no request timeout either unless you call .timeout(...). Many provider SDKs wrap these clients and set

HttpURLConnection and SimpleClientHttpRequestFactory (RestTemplate's default factory when no other HTTP library is present) have connect and read timeouts of 0, meaning they never expire. java.net.http.HttpClient has no request timeout either unless you call .timeout(...). Many provider SDKs wrap these clients and set nothing.

Every outbound client needs explicit connect and read timeouts, reviewed as part of the integration, with a test that calls a slow fake server to prove the call is cut off on time.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
Edge caseSeniorRetrying at several layers multiplies requests exponentiallyThe gateway retries 3 times, service A retries 3 times when calling B, and B retries 3 times when calling the provider. When the provider slows down, one user request becomes 27 requests to them, exactly when they're overloaded: a "retry storm". Rule: retry at one layer only, usually the one closest to the third party;

The gateway retries 3 times, service A retries 3 times when calling B, and B retries 3 times when calling the provider. When the provider slows down, one user request becomes 27 requests to them, exactly when they're overloaded: a "retry storm".

Rule: retry at one layer only, usually the one closest to the third party; the layers above fail fast. Add a retry budget (e.g. retries may not exceed 10% of successful requests in the recent window) and a circuit breaker to stop retrying when the other side is clearly down. To see a retry storm before it happens for real, run a stress test (Performance testing).

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
Trade-offSeniorRetry synchronously in the request, or queue it and retry laterSynchronous retries (the user is waiting): simple, and the user gets the final answer right away. But every wait adds to latency, so you can only afford one or two short retries within a deadline of a few seconds. Queueing (the user gets "accepted"): retries can go on for a long time on a long schedule (minutes, hours)
  • Synchronous retries (the user is waiting): simple, and the user gets the final answer right away. But every wait adds to latency, so you can only afford one or two short retries within a deadline of a few seconds.
  • Queueing (the user gets "accepted"): retries can go on for a long time on a long schedule (minutes, hours), with a dead letter for the final failure, and backlogs never touch user requests. The cost is an intermediate state, a way to report the result later (your own webhook, email, polling), and idempotency in the worker.

Rule of thumb: operations that need the answer now (payment, stock check) retry briefly and synchronously, then fail. Operations that can happen later (invoicing, pushing orders to a carrier, notifications) go on a queue.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
TILSeniorResilience4j puts Retry outermost, so every retry passes through the circuit breakerWhen you stack @Retry, @CircuitBreaker, @RateLimiter, @TimeLimiter and @Bulkhead on one method, the default order is Retry outermost, then CircuitBreaker, RateLimiter, TimeLimiter, and Bulkhead innermost. Consequence: the breaker counts each retry as a call. Once the circuit is open, the retries are rejected immediatel

When you stack @Retry, @CircuitBreaker, @RateLimiter, @TimeLimiter and @Bulkhead on one method, the default order is Retry outermost, then CircuitBreaker, RateLimiter, TimeLimiter, and Bulkhead innermost.

Consequence: the breaker counts each retry as a call. Once the circuit is open, the retries are rejected immediately (CallNotPermittedException) instead of hammering a dead service. You can change the order with the *-aspect-order properties; don't unless you understand it, because putting the breaker outside the retry means a whole retry chain counts as a single failure.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
Trade-offSeniorFallback when a third party fails: error out, serve stale data, switch providers, or queueThere's no universal fallback; choose by business need. A fallback in the wrong place is worse than none: showing "payment successful" when the gateway timed out creates orders that were never paid.

There's no universal fallback; choose by business need.

Fallback Fits Also needs
Fail fast (a 503 with a clear message) payments, where guessing is more dangerous than refusing
Stale data from a cache exchange rates, estimated shipping fees the time it was last updated, shown alongside
Backup provider SMS, email the same interface, cost monitoring
Accept now, process later via a queue invoicing, pushing shipments a "processing" state, a way to report the outcome later

A fallback in the wrong place is worse than none: showing "payment successful" when the gateway timed out creates orders that were never paid.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewJuniorWhy must every outbound call have a timeout?

Because without one, a hung service holds threads forever, and a drained thread pool takes the whole service down.

The server's thread pool is finite (Tomcat defaults to 200), so a few minutes later even unrelated APIs stop responding. Set a short connect timeout (1–2 s), a read timeout based on the other side's p99, and an overall deadline that covers retries.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewJuniorWhich errors should you retry, and which not?

Retry transient errors (timeouts, connection errors, 429, 502, 503, 504); don't retry errors caused by the request itself (400, 401, 403, 404, 422).

Honour Retry-After if present. Errors caused by the request fail the same way when resent. And only retry writes when they're guaranteed idempotent, usually thanks to an idempotency key.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewMidWhat are exponential backoff and jitter, and why do you need jitter?

Backoff grows the wait exponentially up to a cap; jitter randomizes the wait so clients don't retry at the same moment.

Backoff (100 ms, 200, 400...) gives the other side time to recover. Without jitter, thousands of clients that failed together retry together, producing synchronized waves of load against an already weak service. Full jitter (random between zero and the cap) spreads load best.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewMidHow does a circuit breaker work?

Three states: CLOSED counts failures, OPEN rejects at once once the threshold is crossed, HALF_OPEN lets a few trial calls decide whether to close again or stay open.

CLOSED usually counts failures as a rate over a sliding window, slow calls included. OPEN lasts for a set time, and every call goes straight to the fallback. The benefit: you fail fast instead of waiting for timeouts, and the other side gets time to recover.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewMidWhat is a bulkhead? Do you still need one with virtual threads?

A bulkhead caps concurrent calls to each dependency; you still need it with virtual threads, because resources other than threads are still finite.

It's a semaphore or a dedicated pool, so a slow provider only consumes its own share instead of the shared pool. Virtual threads make threads cheap, but the HTTP connection pool, memory for waiting requests, and the third party's quota and capacity are still limited. These days it's usually a semaphore rather than a dedicated thread pool.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewSeniorA provider gets 10× slower and takes your whole system down. Analyse and fix.

It's a chain: long timeouts hold resources, multi-layer retries multiply load, and the failure spreads to everything. Fix it with timeouts, single-layer retries, a circuit breaker, bulkheads and fallbacks.

The usual chain: no timeout or one that's too long, threads and connection pools held, retries at several layers multiplying load, user requests queuing up, health checks slowing too, instances restarted, load shifting onto the survivors.

Fix:

  • Timeouts from p99 plus an overall deadline.
  • Retries at one layer with jitter and a retry budget.
  • A circuit breaker that also counts slow calls; a dedicated bulkhead for that provider.
  • Business-driven fallbacks; move calls that don't need to be synchronous onto a queue.
  • Per-provider latency metrics and alerts.
Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
InterviewSeniorA call to create a transaction times out. Do you resend it?

Only with an idempotency key; otherwise query the status first, because a timeout means "unknown" and the other side may already have created it.

With a key, resend with the same key and they'll return the earlier result instead of creating a new one. Without one, don't resend blindly: query the status by your own reference, mark the record UNKNOWN and let the reconciliation job settle it. A connection failure before the request was sent (connect timeout) is much safer to retry than a read timeout.

Read in post: Timeouts, retries, circuit breakers and bulkheads for third-party calls
Edge caseMidREAD UNCOMMITTED is not a "fast mode" for logging systemsA common suggestion: use READ UNCOMMITTED for a logging system because "speed matters more than accuracy". The argument is wrong in two ways. With MVCC, at RC and RR readers already don't block writers and vice versa. Skipping committed versions doesn't make inserts faster. What makes logging slow is fsync, indexes and

A common suggestion: use READ UNCOMMITTED for a logging system because "speed matters more than accuracy". The argument is wrong in two ways.

  • With MVCC, at RC and RR readers already don't block writers and vice versa. Skipping committed versions doesn't make inserts faster. What makes logging slow is fsync, indexes and transaction size.
  • PostgreSQL has no real READ UNCOMMITTED: set RU and it still behaves as READ COMMITTED.

RU has only narrow uses, for example peeking at a running batch on MySQL when you accept the numbers might be rolled back.

Read in post: Transactions from the inside
Edge caseSeniorSERIALIZABLE in MySQL and PostgreSQL works by two different mechanisms"SERIALIZABLE locks every row it reads" is only true for InnoDB. With autocommit off, every plain SELECT is silently turned into SELECT ... FOR SHARE, so writers wait for readers. In the experiment, lost update and write skew here ended in a deadlock (both sides hold S locks, both request X locks). PostgreSQL uses Seri

"SERIALIZABLE locks every row it reads" is only true for InnoDB. With autocommit off, every plain SELECT is silently turned into SELECT ... FOR SHARE, so writers wait for readers. In the experiment, lost update and write skew here ended in a deadlock (both sides hold S locks, both request X locks).

PostgreSQL uses Serializable Snapshot Isolation (SSI): nobody blocks; the database tracks read/write dependencies and aborts one side when it finds a dangerous cycle (SQLState 40001).

The consequence on both: the application must retry the whole transaction. "SERIALIZABLE is rarely used" is fairer for MySQL; on PostgreSQL, SSI plus retry is reasonable for write skew that is hard to lock explicitly.

Read in post: Transactions from the inside
TILSeniorGroup commit: many transactions share a single fsyncfsync is expensive (about 0.1 ms to a few ms depending on the drive). If each commit did its own fsync, throughput would be capped by fsyncs per second. Both InnoDB and PostgreSQL batch transactions that commit at nearly the same time into one fsync (group commit), so throughput goes up while full durability is kept. O

fsync is expensive (about 0.1 ms to a few ms depending on the drive). If each commit did its own fsync, throughput would be capped by fsyncs per second. Both InnoDB and PostgreSQL batch transactions that commit at nearly the same time into one fsync (group commit), so throughput goes up while full durability is kept.

On MySQL with a binlog, a commit goes through a two-phase commit between the redo log and the binlog. sync_binlog = 1 together with innodb_flush_log_at_trx_commit = 1 is the safe pair for money data.

Read in post: Transactions from the inside
Edge caseSeniorIn one REPEATABLE READ transaction, a plain SELECT and a SELECT FOR UPDATE can return different resultsAt InnoDB RR, SELECT balance FROM wallet WHERE id = 1 reads through the read view, while SELECT ... FOR UPDATE or UPDATE is a current read of the latest committed version. If another transaction committed after your snapshot, two statements in the same transaction see two different values. In the experiment in section

At InnoDB RR, SELECT balance FROM wallet WHERE id = 1 reads through the read view, while SELECT ... FOR UPDATE or UPDATE is a current read of the latest committed version. If another transaction committed after your snapshot, two statements in the same transaction see two different values.

In the experiment in section 3.1, on the same row a plain read saw v = 100000 and a FOR SHARE read saw v = 120000. So a decision based on a value you'll write back must use a current read (or live inside the UPDATE's own condition).

Read in post: Transactions from the inside
Edge caseSeniorA read-only transaction can still slow down the whole databaseA transaction with only SELECTs at REPEATABLE READ still holds a read view. As long as it stays open, InnoDB can't purge any old versions newer than that read view, on any table. HLL climbs, undo takes over the buffer pool, and snapshot reads walk long undo chains. Typical sources: a report running for hours in one tra

A transaction with only SELECTs at REPEATABLE READ still holds a read view. As long as it stays open, InnoDB can't purge any old versions newer than that read view, on any table. HLL climbs, undo takes over the buffer pool, and snapshot reads walk long undo chains.

Typical sources: a report running for hours in one transaction, a mysql session on a developer's laptop left after BEGIN, a connection leaked in the pool. Alerting on HLL (or on the age of the oldest transaction in information_schema.innodb_trx) catches this before users notice the slowdown.

Read in post: Transactions from the inside
Trade-offSeniorInnoDB's undo log or PostgreSQL's in-table versionsInnoDB (undo log): the table only holds the latest version, so it doesn't bloat from updates. In exchange, old snapshots walk the undo chain (slow when HLL is large). Rolling back a big transaction is expensive because every undo record has to be applied: killing a transaction that ran for an hour can take about as lon
  • InnoDB (undo log): the table only holds the latest version, so it doesn't bloat from updates. In exchange, old snapshots walk the undo chain (slow when HLL is large). Rolling back a big transaction is expensive because every undo record has to be applied: killing a transaction that ran for an hour can take about as long to roll back.
  • PostgreSQL (tuples in the table): rollback is almost instant (just marked aborted), and reading any version is a direct tuple read. In exchange, tables and indexes bloat with updates and VACUUM must keep up. Transaction ids are 32-bit, so old tuples must be "frozen" to avoid wraparound. Updates that don't touch indexed columns and fit in the page use HOT updates (no index changes), so a lower fillfactor helps update-heavy tables.

Both share one enemy: long-open transactions, because they block purge (InnoDB) or VACUUM (PostgreSQL). Part 2 uses this to find and fix the four kinds of problem transaction you meet in production.

Read in post: Transactions from the inside
InterviewJuniorHow do the redo log and the undo log differ?

The redo log redoes what was committed (durability); the undo log goes back to the previous version (atomicity and MVCC).

After a crash, the redo log lets the database redo what was committed but hadn't reached the data files yet. The undo log is used to roll back uncommitted transactions and to rebuild old versions for snapshot reads.

Read in post: Transactions from the inside
InterviewJuniorWhy does a database write the log before the data files?

Because a sequential append to the log is much faster than random page writes, and it's still enough to lose nothing.

A commit only needs the log safely on disk; data pages are written later in batches. After a crash, the database reads the log to redo whatever is missing. That's write-ahead logging.

Read in post: Transactions from the inside
InterviewMidWhen does InnoDB create the read view at REPEATABLE READ and at READ COMMITTED?

RR: at the first consistent read, reused until the end of the transaction. RC: a new read view for every statement.

At RR the read view isn't created at BEGIN; to create it immediately, use START TRANSACTION WITH CONSISTENT SNAPSHOT. Locking reads and UPDATE/DELETE don't use a read view; they read the latest version (a current read).

Read in post: Transactions from the inside
InterviewMidWhy can two reads of the same row in one MySQL REPEATABLE READ transaction return different results?

Because one is a plain SELECT (a snapshot read) and the other is SELECT ... FOR UPDATE/FOR SHARE (a current read of the latest committed version).

RR only promises repeatability for consistent reads. That's why a decision you're going to write back must be based on a current read, or sit directly in the UPDATE's WHERE clause.

Read in post: Transactions from the inside
InterviewSeniorHistory list length keeps growing. How do you investigate?

Find the old read view holding back purge: the oldest transaction in information_schema.innodb_trx. Then deal with it and fix the root cause in the application.

  • Order innodb_trx by trx_started and join it with the processlist and performance_schema.events_statements_current to get the connection, host and last statement.
  • A leaked connection or forgotten session: kill it (accepting the rollback time), then fix the application.
  • No old transaction: check whether purge keeps up with the write load (innodb_purge_threads).
  • Afterwards, add alerts on HLL and on transaction age.
Read in post: Transactions from the inside
InterviewSeniorCompare MVCC in InnoDB and PostgreSQL, and the operational consequences of each.

InnoDB keeps old versions in the undo log, PostgreSQL keeps them in the table itself; long-open transactions hurt both.

  • InnoDB: the latest version lives in the clustered index, old ones are rebuilt from undo. Tables don't bloat, but old snapshots read slowly when undo chains are long, and rolling back a big transaction takes a long time.
  • PostgreSQL: a new tuple per update, marked with xmin/xmax. Rollback is instant, but tables and indexes bloat, it depends on VACUUM, needs freezing to avoid wraparound, and should take advantage of HOT updates.
Read in post: Transactions from the inside
InterviewSeniorYou choose SERIALIZABLE on PostgreSQL for a business flow. What does the application need?

A retry loop wrapped outside the whole transaction, because SSI doesn't block: it aborts a transaction with SQLState 40001, sometimes right at COMMIT.

  • Cap the attempts and use randomized backoff.
  • The transaction body must be safe to rerun: no emails, no external API calls inside.
  • Keep transactions short to reduce conflicts. Declare read-only transactions READ ONLY (or DEFERRABLE for long reports) to cut false positives.
Read in post: Transactions from the inside
Edge caseMidAn HTTP call inside @Transactional holds locks and a connection for the whole callThe orders row is locked FOR UPDATE from before the payment gateway call until the commit. If the gateway takes 2 seconds, every request touching that order waits 2 seconds. If it hangs for 30 seconds, a connection is held for 30 seconds, the pool drains and the whole service stalls; the database only sees an "idle" tr

The orders row is locked FOR UPDATE from before the payment gateway call until the commit. If the gateway takes 2 seconds, every request touching that order waits 2 seconds. If it hangs for 30 seconds, a connection is held for 30 seconds, the pool drains and the whole service stalls; the database only sees an "idle" transaction.

The fix: a short transaction that records a PAYING status, the gateway call outside any transaction, then a second short transaction that records the result (plus an idempotency key so retries are safe).

Read in post: Harmful transactions
Edge caseSeniorA leaked connection can keep a transaction open for 8 hoursOnce a connection is borrowed and never returned, the pool stops managing it: no keepalive, no replacement at maxLifetime, no rollback. On MySQL it sits in Sleep and is only closed when it hits waittimeout, which defaults to 8 hours. All that time the transaction holds its locks and read view (HLL climbs steadily). Pos

Once a connection is borrowed and never returned, the pool stops managing it: no keepalive, no replacement at maxLifetime, no rollback. On MySQL it sits in Sleep and is only closed when it hits wait_timeout, which defaults to 8 hours. All that time the transaction holds its locks and read view (HLL climbs steadily). PostgreSQL has no default limit like that unless you set idle_in_transaction_session_timeout.

What actually solves it is HikariCP's leakDetectionThreshold (to see where the leak is) and fixing the code (to stop it); lowering wait_timeout for the app's user is only a safety net.

Read in post: Harmful transactions
Trade-offSeniorWhere to put timeouts to stop harmful transactionsThere's no single knob; each layer catches a different kind of failure. Application: Spring's @Transactional(timeout = ...) aborts an expired transaction at its next statement; HTTP client timeouts cap the total request time. Cheap, but it can't catch leaked connections. Pool: HikariCP's leakDetectionThreshold catches

There's no single knob; each layer catches a different kind of failure.

  • Application: Spring's @Transactional(timeout = ...) aborts an expired transaction at its next statement; HTTP client timeouts cap the total request time. Cheap, but it can't catch leaked connections.
  • Pool: HikariCP's leakDetectionThreshold catches connections borrowed for too long; it only logs, it doesn't abort. The pool's other settings (maxLifetime, keepaliveTime, connectionTimeout) are in Connection pooling and HikariCP.
  • Database: innodb_lock_wait_timeout / lock_timeout for lock waits; statement_timeout (PostgreSQL) or max_execution_time (MySQL, SELECT only) per statement; idle_in_transaction_session_timeout (PostgreSQL) cuts off idle transactions. Set them too low and legitimate batch jobs get killed, so set them per role/user: low for the web app, higher for jobs.
  • Monitoring: alert on the age of the oldest transaction and on HLL or dead tuple counts. It catches every kind, but it only warns, it doesn't stop anything.
Read in post: Harmful transactions
Edge caseMidSET TRANSACTION ISOLATION LEVEL without SESSION only applies to one transactionMySQL: SET TRANSACTION ISOLATION LEVEL READ COMMITTED (no keyword) only changes the next transaction. SET SESSION TRANSACTION ... changes every later transaction in the session; SET GLOBAL ... changes new sessions. PostgreSQL: SET TRANSACTION must run inside a transaction (or write BEGIN ISOLATION LEVEL ...). For the w
  • MySQL: SET TRANSACTION ISOLATION LEVEL READ COMMITTED (no keyword) only changes the next transaction. SET SESSION TRANSACTION ... changes every later transaction in the session; SET GLOBAL ... changes new sessions.
  • PostgreSQL: SET TRANSACTION must run inside a transaction (or write BEGIN ISOLATION LEVEL ...). For the whole session use SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL ....
  • Connection pool: a session-level change that isn't reverted "leaks" into later requests that reuse the connection. Spring's @Transactional(isolation = ...) sets it and restores the previous level when the transaction ends.
Read in post: Harmful transactions
InterviewJuniorWhat is autocommit, and why does it matter that it's on by default?

With autocommit on, every statement is its own transaction and commits immediately; MySQL and JDBC enable it by default.

To make several statements one unit you need START TRANSACTION/BEGIN (or setAutoCommit(false), or @Transactional). Forgetting this leads people to believe two UPDATEs are atomic together when they aren't.

Read in post: Harmful transactions
InterviewJuniorCan a transaction with only SELECT statements do any harm?

Yes. At REPEATABLE READ it holds a snapshot, which blocks purge (InnoDB) and VACUUM (PostgreSQL).

While it's open, InnoDB can't purge the undo log and PostgreSQL can't vacuum dead tuples newer than that snapshot. If it's SELECT ... FOR UPDATE, it also holds locks. So read-only transactions must be short too, and long reports belong on a replica.

Read in post: Harmful transactions
InterviewMidWhat is an "idle in transaction" session and why is it dangerous?

It's an open transaction whose client sends nothing; it still holds locks and a snapshot.

It usually happens because the application does other work between statements (an HTTP call) or leaked the connection. It blocks other writers and blocks VACUUM (PostgreSQL) or purge (InnoDB). Find it with pg_stat_activity.state, or innodb_trx plus a Sleep processlist entry; stop it with idle_in_transaction_session_timeout and by fixing the code.

Read in post: Harmful transactions
InterviewMidHow do you fix a million-row UPDATE that is making replicas lag?

Batch it by primary key, a few thousand rows per transaction, because a million rows rarely need to be atomic.

Repeat the condition in each batch so it's safe to rerun, pause between batches and watch replica lag. The price is losing global atomicity, so the operation must be idempotent.

Read in post: Harmful transactions
InterviewMidHow far does SET TRANSACTION ISOLATION LEVEL reach?

On MySQL, with no keyword it only affects the next transaction; SESSION affects the whole session; GLOBAL affects new sessions.

On PostgreSQL it must be set inside the transaction (or via BEGIN ISOLATION LEVEL ...), and for the whole session you use SET SESSION CHARACTERISTICS. With a connection pool, a session-level change that isn't reverted affects later requests; Spring's @Transactional(isolation = ...) restores it automatically.

Read in post: Harmful transactions
InterviewSeniorA service occasionally slows the whole database down for a few minutes, then it recovers. What do you suspect and how do you check?

I'd suspect a periodically long-open transaction (a report, a batch, or a request calling a slow API inside a transaction) holding locks or a snapshot.

  • Check during the incident: sys.innodb_lock_waits (who blocks whom), innodb_trx (age, rows locked), and whether HLL on the dashboard shows a sawtooth at the same times; on PostgreSQL, pg_stat_activity and pg_locks.
  • Fix: shrink transactions to the DB work, batch the batch jobs, set per-user timeouts, run long reports on a replica.
Read in post: Harmful transactions
InterviewSeniorWhy might killing a large transaction on MySQL not end the incident right away?

Because InnoDB rolls back by applying every undo record in reverse, and keeps holding its locks meanwhile.

A transaction that changed millions of rows over an hour can take about as long to roll back. Restarting the server doesn't help either: after startup InnoDB still has to finish the rollback. So the right approach is prevention: batching, capping transaction size, and thinking twice before killing (sometimes letting it finish is faster).

Read in post: Harmful transactions
InterviewSeniorAt which layers do you set timeouts to stop harmful transactions?

At all four: application, pool, database and monitoring; each catches a different failure and none is enough alone.

  • Application: @Transactional(timeout) and HTTP client timeouts.
  • Pool: HikariCP's leakDetectionThreshold to spot connections held too long.
  • Database: innodb_lock_wait_timeout/lock_timeout for lock waits, statement_timeout or max_execution_time per statement, idle_in_transaction_session_timeout on PostgreSQL; set per user so the web app gets low limits and jobs higher ones.
  • Monitoring: alerts on the oldest transaction's age and on HLL/dead tuples.
Read in post: Harmful transactions
Edge caseMidAn application-prod.yml with production URLs and passwords lives in the repoPasswords in Git: anyone who can read the repo has them, and deleting them leaves them in the commit history. The image is tied to environments: adding staging-2 means adding a file and rebuilding. What to do: keep profiles for differences in behaviour (switching a group of beans on or off) if you really need them. Per
  • Passwords in Git: anyone who can read the repo has them, and deleting them leaves them in the commit history.
  • The image is tied to environments: adding staging-2 means adding a file and rebuilding.
  • What to do: keep profiles for differences in behaviour (switching a group of beans on or off) if you really need them. Per-deploy values go through environment variables, ConfigMaps and Secrets; passwords through a secret manager. Add secret scanning (gitleaks, GitHub secret scanning) to CI.
Read in post: The Twelve-Factor App
Trade-offSeniorEnvironment variables vs a secret manager for sensitive valuesEnvironment variables (the original twelve-factor answer): simple, readable from any language, hard to commit by accident. Downsides: they leak through /proc/<pid/environ, docker inspect, kubectl describe, and /actuator/env if it's exposed; every child process inherits them; changing one needs a restart. A secret manag
  • Environment variables (the original twelve-factor answer): simple, readable from any language, hard to commit by accident. Downsides: they leak through /proc/<pid>/environ, docker inspect, kubectl describe, and /actuator/env if it's exposed; every child process inherits them; changing one needs a restart.
  • A secret manager (Vault, AWS Secrets Manager, GCP Secret Manager), mounted as files through Kubernetes Secrets or a CSI driver: access control, auditing, automatic rotation, reloading without a restart. Downsides: one more startup dependency and more complex setup.
  • What I do: plain config through env/ConfigMaps; secrets mounted as files (Spring Boot reads them with spring.config.import=configtree:/run/secrets/) or fetched from a secret manager. The spirit of factor III still holds: config is separate from code and image; "the environment" is just broader than environment variables now.
Read in post: The Twelve-Factor App
Edge caseMid@Scheduled runs on every replica once you scale outA @Scheduled job in a web app runs in every process: scale from 1 to 5 pods and the report goes out 5 times, the refund is paid 5 times. Split it into its own process type: a 1-replica worker Deployment, or a Kubernetes CronJob. Or use a distributed lock for the job (ShedLock on a DB table). Above all, make the job ide

A @Scheduled job in a web app runs in every process: scale from 1 to 5 pods and the report goes out 5 times, the refund is paid 5 times.

  • Split it into its own process type: a 1-replica worker Deployment, or a Kubernetes CronJob.
  • Or use a distributed lock for the job (ShedLock on a DB table).
  • Above all, make the job idempotent (safe to rerun), because even with a lock an expired lease can let two copies overlap.
Read in post: The Twelve-Factor App
Trade-offMidScale with threads inside one JVM, or with more processesInside the process: thread pools and Java 21 virtual threads use one machine well, share heap and caches, and have little overhead. But you're capped by one machine, one JVM crash takes everything down, and a GC pause hits every request in that process. More processes (twelve-factor): near-linear scaling across machine
  • Inside the process: thread pools and Java 21 virtual threads use one machine well, share heap and caches, and have little overhead. But you're capped by one machine, one JVM crash takes everything down, and a GC pause hits every request in that process.
  • More processes (twelve-factor): near-linear scaling across machines, good fault tolerance, each kind of work scaled on its own. The cost: each JVM takes a few hundred MB, startup takes time, local caches are duplicated.
  • In practice: virtual threads or a sensible pool inside each process, and the number of processes (pods) driven by load. Split web and worker into separate Deployments so heavy background work doesn't compete for CPU with user requests.
Read in post: The Twelve-Factor App
Edge caseMidA shell-form ENTRYPOINT means the JVM never receives SIGTERMWith ENTRYPOINT java -jar app.jar (shell form), PID 1 in the container is /bin/sh -c, and the shell doesn't forward SIGTERM to the JVM. After terminationGracePeriodSeconds (30 seconds by default) Kubernetes sends SIGKILL: in-flight requests are cut off, shutdown hooks never run, the last spans and logs are lost. Use th

With ENTRYPOINT java -jar app.jar (shell form), PID 1 in the container is /bin/sh -c, and the shell doesn't forward SIGTERM to the JVM. After terminationGracePeriodSeconds (30 seconds by default) Kubernetes sends SIGKILL: in-flight requests are cut off, shutdown hooks never run, the last spans and logs are lost.

  • Use the exec form, ENTRYPOINT ["java", "-jar", "/app/app.jar"], or end a wrapper script with exec java ....
  • To check: docker stop should stop the container within a few seconds, not after exactly 10 (Docker's default wait before SIGKILL).
Read in post: The Twelve-Factor App
Edge caseSeniorA pod gets SIGTERM before it's removed from the load balancer, so new requests keep arrivingWhen a pod is deleted, Kubernetes sends SIGTERM and removes the pod from Endpoints in parallel; kube-proxy, the ingress and the load balancer need a few seconds to catch up. If the app closes its listener right away, requests still being routed to it get connection errors. A preStop hook that sleeps a few seconds (slee

When a pod is deleted, Kubernetes sends SIGTERM and removes the pod from Endpoints in parallel; kube-proxy, the ingress and the load balancer need a few seconds to catch up. If the app closes its listener right away, requests still being routed to it get connection errors.

  • A preStop hook that sleeps a few seconds (sleep 5, or lifecycle.preStop.sleep since Kubernetes 1.30) before SIGTERM reaches the app.
  • Readiness fails as soon as shutdown begins.
  • terminationGracePeriodSeconds longer than preStop plus Spring's drain time.
Read in post: The Twelve-Factor App
Trade-offMidTest with in-memory H2, or with Testcontainers running the production databaseH2/HSQLDB: starts in milliseconds, no Docker needed. But PostgreSQL compatibility mode is only an approximation: no jsonb, no SKIP LOCKED, no partial indexes, different isolation behaviour; Flyway migrations written for PostgreSQL need separate versions. Green tests prove nothing about production. Testcontainers (real
  • H2/HSQLDB: starts in milliseconds, no Docker needed. But PostgreSQL compatibility mode is only an approximation: no jsonb, no SKIP LOCKED, no partial indexes, different isolation behaviour; Flyway migrations written for PostgreSQL need separate versions. Green tests prove nothing about production.
  • Testcontainers (real PostgreSQL, Kafka, Redis in Docker): the right version and the right behaviour; Spring Boot 3.1+ has @ServiceConnection, so setup is close to zero. The cost: Docker in CI, and a few seconds per container start (share one container across the suite, or use reusable containers locally).
  • I use Testcontainers for every test that touches a database or a broker, and Docker Compose (Spring Boot 3.1+ starts compose.yaml for you in development) so developer machines run the same versions as production.
Read in post: The Twelve-Factor App
Edge caseJuniorWriting log files inside the containerLogs written to /var/log/app.log live on the container's temporary filesystem: kubectl logs can't see them, they vanish with the container, and a growing file can fill the node's disk and get pods evicted. Write to stdout/stderr; if you must write files (a legacy library), mount a volume and run a sidecar that reads th

Logs written to /var/log/app.log live on the container's temporary filesystem: kubectl logs can't see them, they vanish with the container, and a growing file can fill the node's disk and get pods evicted. Write to stdout/stderr; if you must write files (a legacy library), mount a volume and run a sidecar that reads them.

Read in post: The Twelve-Factor App
Trade-offSeniorRun migrations at application startup, or as a separate JobAt startup (Spring Boot's default when Flyway/Liquibase is on the classpath): simple, impossible to forget. Flyway takes a lock in the database so several pods won't migrate twice, but the others wait. A long migration (an index on a big table) makes the pod miss its startup probe and restart in a loop. The app's DB ac
  • At startup (Spring Boot's default when Flyway/Liquibase is on the classpath): simple, impossible to forget. Flyway takes a lock in the database so several pods won't migrate twice, but the others wait. A long migration (an index on a big table) makes the pod miss its startup probe and restart in a loop. The app's DB account needs DDL rights.
  • A separate Job before rollout (a Kubernetes Job, a Helm pre-upgrade hook, a pipeline step): runs once with an account that has DDL rights, the app only needs DML, and a failed migration stops the rollout before any new pod starts. The cost: one more step, and you must guarantee the Job → Deployment order.
  • Either way, migrations must stay backward compatible (expand → migrate → contract), because during a rolling update old and new pods run against the new schema at the same time.
Read in post: The Twelve-Factor App
InterviewJuniorWhat is the Twelve-Factor App, and why does it still matter?

Twelve principles for writing apps that run well on cloud platforms, distilled by Heroku in 2011. It still matters because Docker and Kubernetes assume apps follow most of them.

Concretely: config outside the image, stateless processes that scale horizontally, logs to stdout, graceful shutdown on SIGTERM. An app that breaks them will still run on Kubernetes, but it'll be hard to scale and hard to deploy without errors.

Read in post: The Twelve-Factor App
InterviewJuniorWhy shouldn't you write log files inside a container?

Because the container's filesystem is temporary: logs disappear with the container, kubectl logs can't read files, and growing files fill the node's disk.

The app should write events to stdout and let the platform collect and ship them; the app doesn't need to know where logs end up.

Read in post: The Twelve-Factor App
InterviewMidWhat does twelve-factor config mean? Do Spring profiles break it?

Config is whatever varies between deploys; it must live outside the code and come from the environment. Profiles holding per-environment values break it; profiles for behavioural differences are fine.

Config means URLs, credentials, host names; the test is whether you could open-source the repo right now without leaking secrets. An application-prod.yml with URLs and passwords puts secrets in Git, ties the image to environments, and needs a new file for each new environment. Values should go through env, ConfigMaps and Secrets.

Read in post: The Twelve-Factor App
InterviewMidWhat does "stateless process" mean in a Spring Boot app?

Nothing that has to outlive a request sits in the process's memory or disk.

Sessions go to Redis or into tokens, uploads go to object storage, data goes to the database. Then any request can go to any pod, scaling and restarts lose nothing, and you don't need sticky sessions. Local caches are allowed, as long as they're only caches and losing them doesn't corrupt anything.

Read in post: The Twelve-Factor App
InterviewMidHow do build, release and run differ, and why separate them?

Build produces an artifact (an image), a release is that artifact plus one environment's config with an immutable id, and run starts processes from a release. Separating them lets you build once and promote the same image everywhere.

That way what runs in production is exactly what was tested, rollback is just rerunning the previous release, and nobody edits code on servers. That's why images are tagged with the commit SHA, never latest.

Read in post: The Twelve-Factor App
InterviewMidA slow Redis makes every request hang. What does the "backing services" factor suggest?

A backing service can be slow, down or replaced at any time, so the app must treat that as normal: short timeouts, bounded retries, a circuit breaker, a fallback if Redis is only a cache.

Health checks need the same distinction: Redis being down doesn't mean the process is dead, so keep it out of liveness, or Kubernetes will restart a fleet of healthy pods.

Read in post: The Twelve-Factor App
InterviewSeniorHow do you deploy a Spring Boot service on Kubernetes without dropping a single request?

The app must receive SIGTERM and shut down gracefully; Kubernetes must take the pod out of the load balancer before the app closes its listener, and only send traffic to new pods once they're ready.

  • App: exec-form ENTRYPOINT, graceful shutdown (default since Boot 3.4) with a timeout longer than the longest request, readiness failing as soon as shutdown begins.
  • Kubernetes: a preStop sleep of a few seconds, terminationGracePeriodSeconds longer than preStop plus drain time, a rolling update with maxUnavailable: 0 and a meaningful readiness probe.
  • Workers: don't commit offsets or ack until done, and keep jobs idempotent so reruns are safe.
Read in post: The Twelve-Factor App
InterviewSeniorWhere should database migrations run when you have many replicas and rolling updates?

I prefer a separate Job from the same image before rollout, with an account that has DDL rights. More important than where: migrations must be backward compatible via expand/contract.

A separate Job means a failed migration blocks the rollout and the app only needs DML. Running at startup is simple and Flyway's lock prevents double runs, but a long migration makes pods miss their startup probe. Expand/contract matters because during a rolling update old and new pods run against the new schema together.

Read in post: The Twelve-Factor App
InterviewSeniorWhich parts of twelve-factor do you think are outdated or missing?

The spirit holds, but config and logs need a broader reading, and health checks, service-to-service security, API contracts and resilience to slow backing services are missing.

Config isn't just environment variables but also Secrets mounted as files and secret managers with rotation; logs have grown into structured telemetry including metrics and traces. Kubernetes now handles process management, so the app's job is mostly to stay stateless, keep config external and handle its lifecycle properly.

Read in post: The Twelve-Factor App
InterviewSeniorSomeone adds @Scheduled to a service running 6 replicas. What do you ask in review?

First: the job will run 6 times; is that acceptable? Then idempotency, shutdown and monitoring.

  • If not acceptable: move it to a CronJob or a one-replica worker, or use a distributed lock like ShedLock.
  • Is the job idempotent, since even with a lock an expired lease or a retry can make runs overlap?
  • Does a long run block graceful shutdown, and if the pod is killed halfway, does the next run pick up correctly?
  • Are there metrics and alerts for when the job fails or doesn't run?
Read in post: The Twelve-Factor App
Edge caseMidMirror tests: the test repeats the implementationThe symptom: the test stubs repo.findById(1) to return user, calls service.get(1), asserts the result is user and verifies repo.findById(1) was called once. It is green for every implementation, right or wrong in business terms, and red when you switch to findWithRolesById even though behaviour didn't change. It costs

The symptom: the test stubs repo.findById(1) to return user, calls service.get(1), asserts the result is user and verifies repo.findById(1) was called once. It is green for every implementation, right or wrong in business terms, and red when you switch to findWithRolesById even though behaviour didn't change. It costs maintenance and catches no bug. Delete it, or replace it with a slice test against a real DB.

Read in post: Unit testing with JUnit 5 and Mockito
Trade-offMidArgumentCaptor or argThatargThat(u - !u.getPassword().equals("plain")): short, fits inside verify/InOrder, but on failure it only says "argument didn't match", not which field was wrong. ArgumentCaptor: longer, but asserting field by field with AssertJ gives clear failure messages. Habit: argThat for a single condition inside an ordering check
  • argThat(u -> !u.getPassword().equals("plain")): short, fits inside verify/InOrder, but on failure it only says "argument didn't match", not which field was wrong.
  • ArgumentCaptor: longer, but asserting field by field with AssertJ gives clear failure messages.

Habit: argThat for a single condition inside an ordering check; a captor when checking several fields of the saved object.

Read in post: Unit testing with JUnit 5 and Mockito
TILMidMockitoExtension turns on strict stubs: an unused stub fails the testWith @ExtendWith(MockitoExtension.class), Mockito runs in strict-stubs mode. A when(...) that is never used throws UnnecessaryStubbingException, and calling a stubbed method with different arguments reports PotentialStubbingProblem. Annoying at first, but useful: an unused stub usually means a copy-pasted test, or the

With @ExtendWith(MockitoExtension.class), Mockito runs in strict-stubs mode. A when(...) that is never used throws UnnecessaryStubbingException, and calling a stubbed method with different arguments reports PotentialStubbingProblem. Annoying at first, but useful: an unused stub usually means a copy-pasted test, or the code took a different branch without the test noticing. Use lenient() only for shared stubs that are deliberately optional.

Read in post: Unit testing with JUnit 5 and Mockito
Edge caseMidA unit test can't see the race between the duplicate check and the saveexistsByEmail then save is check-then-act: two parallel requests both see "not there" and both save. A mock will never show this. The real guard is the UNIQUE constraint in the DB, and mapping DataIntegrityViolationException to 409 must be tested against a real DB (part 2).

existsByEmail then save is check-then-act: two parallel requests both see "not there" and both save. A mock will never show this. The real guard is the UNIQUE constraint in the DB, and mapping DataIntegrityViolationException to 409 must be tested against a real DB (part 2).

Read in post: Unit testing with JUnit 5 and Mockito
Edge caseMidHigh coverage does not mean good testsThe course gives a scale where "70–80% is good". Coverage only measures lines/branches that ran, not whether anything was checked: a test that calls service.create(req) and asserts nothing still gives 100% line coverage. Use coverage as a floor to find code nobody touches, not as a target. Branch coverage beats line co

The course gives a scale where "70–80% is good". Coverage only measures lines/branches that ran, not whether anything was checked: a test that calls service.create(req) and asserts nothing still gives 100% line coverage. Use coverage as a floor to find code nobody touches, not as a target. Branch coverage beats line coverage, and the mutation score beats both.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewJuniorWhat is the difference between a mock and a stub?

A stub feeds data into the code under test; a mock is used to check what the code called (side effects).

In Mockito the same object can play both roles: when(repo.exists(..)).thenReturn(true) is a stub, verify(repo).save(..) uses it as a mock. Rule of thumb: stub queries, verify commands; don't verify calls that only fetch data.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewJuniorWhat is AAA?

Arrange – Act – Assert: set up data and dependencies, call exactly one behaviour, then check the result.

Separating the three blocks makes a test read like a scenario and keeps "one test, one behaviour". BDD calls the same idea Given – When – Then.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewMidWhen should you unit-test a service method, and when not?

Unit-test it when it makes decisions (branches, calculations, normalisation, ordering); not when it only forwards calls to the repository.

For pure wiring, mocking the repository just restates the implementation and breaks on refactoring. Cover that with @DataJpaTest or an integration test against a real DB. The check: does a test go red if I delete this logic?

Read in post: Unit testing with JUnit 5 and Mockito
InterviewMidWhen do you use an ArgumentCaptor?

When you need to check the object passed to a dependency, especially one the code builds internally (an entity whose password is hashed before saving).

The captor grabs the real argument so you can assert each field with clear messages. argThat is shorter for a single condition, especially inside InOrder.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewMidWhy does Mockito throw UnnecessaryStubbingException, and how do you handle it?

Because MockitoExtension runs strict stubs and a when(...) was never used by the code. Usually delete the stub rather than turning the check off.

An unused stub hints at a copy-pasted test or a branch that changed. Use lenient() only for shared stubs in @BeforeEach that are deliberately optional.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewMidHow do you test code that depends on the current time?

Inject a java.time.Clock instead of calling Instant.now() directly; tests pass Clock.fixed or Clock.offset.

That lets you check boundaries like "expires exactly now" without Thread.sleep and without depending on the CI machine's time zone.

Read in post: Unit testing with JUnit 5 and Mockito
InterviewSeniorThe team has 85% coverage but bugs still slip through. How do you assess the test suite?

Coverage only says code ran, not that it was checked. I'd run mutation testing (PIT) on the packages with important logic and read the surviving mutants.

  • Look for tests without asserts, mirror tests, happy-path-only tests.
  • Check where the escaped bugs live: logic (missing unit tests) or wiring (missing integration tests against real DB/HTTP).
  • Change the goal from coverage % to: every bug fix comes with a reproducing test, and critical logic keeps a stable mutation score.
Read in post: Unit testing with JUnit 5 and Mockito
InterviewSeniorWould you mock RestTemplate or a payment SDK in a unit test?

No, I don't mock types I don't own. I wrap them behind my own interface (an adapter), mock that interface in unit tests, and test the adapter with an integration test using WireMock or a sandbox.

Mocking the library only checks that the code calls the API the way I assume it behaves; when the library changes behaviour (timeouts, error codes) the test stays green while production breaks.

Read in post: Unit testing with JUnit 5 and Mockito
Edge caseJuniorA UTF-8 character isn't always 1 byteThe slide says "UTF-8 character: 1B". True for English letters and digits, wrong for Vietnamese: "á" is 2 bytes, "ệ" is 3 bytes, an emoji is 4. A 1,000-character Vietnamese post can take 1.3–1.5 KB. In MySQL, VARCHAR(255) with utf8mb4 can take up to 1,020 bytes, which matters for index length limits.

The slide says "UTF-8 character: 1B". True for English letters and digits, wrong for Vietnamese: "á" is 2 bytes, "ệ" is 3 bytes, an emoji is 4. A 1,000-character Vietnamese post can take 1.3–1.5 KB. In MySQL, VARCHAR(255) with utf8mb4 can take up to 1,020 bytes, which matters for index length limits.

Read in post: Back-of-the-envelope estimation
TILMidLittle's Law: one multiplication gives threads, connections, serversL = λ × W: the number of jobs in the system (L) equals the arrival rate (λ, requests per second) times the time each job spends in the system (W). Example: a database gets 2,000 queries/second at 5 ms each → 2,000 × 0.005 = 10 queries running at once. A pool of 10 connections is just enough; when latency jumps to 50 ms

L = λ × W: the number of jobs in the system (L) equals the arrival rate (λ, requests per second) times the time each job spends in the system (W).

Example: a database gets 2,000 queries/second at 5 ms each → 2,000 × 0.005 = 10 queries running at once. A pool of 10 connections is just enough; when latency jumps to 50 ms you need 100, which is how a slowing database drains the application's pool. The law holds for any stable system, regardless of the distribution. What HikariCP does when the pool runs dry, and how to size it, is in Connection pooling and HikariCP.

Read in post: Back-of-the-envelope estimation
Edge caseMidThree corrections to the slide's estimateNo peak load. The slide stops at the 10K QPS average. The design has to survive the peak, at least 2–3×, so size servers and cache for 30K QPS. Egress is a bit high. A redirect is a 301/302 response with a Location header holding the long URL; it doesn't send the whole 1.1 KB record plus another 1 KB. Roughly 1–1.3 KB
  • No peak load. The slide stops at the 10K QPS average. The design has to survive the peak, at least 2–3×, so size servers and cache for 30K QPS.
  • Egress is a bit high. A redirect is a 301/302 response with a Location header holding the long URL; it doesn't send the whole 1.1 KB record plus another 1 KB. Roughly 1–1.3 KB per response, ~13 MB/s. Overestimating beats underestimating, but say that you're doing it.
  • The cache is sized on new links, not hot links. What gets read most is whatever is going viral, possibly created last week. A better estimate counts distinct links read per day and takes 20%. Even at 10× (22 GB), one Redis node holds it, so the conclusion stands.
Read in post: Back-of-the-envelope estimation
Trade-offSeniorOverestimate or underestimateOverestimate: safe, with room for peaks and growth. The cost is infrastructure money and extra complexity (early sharding is the most expensive thing to undo). Underestimate: cheap at first, but the outage arrives exactly when business is best. The balance: overestimate what's hard to change (schema, shard key, code le
  • Overestimate: safe, with room for peaks and growth. The cost is infrastructure money and extra complexity (early sharding is the most expensive thing to undo).
  • Underestimate: cheap at first, but the outage arrives exactly when business is best.

The balance: overestimate what's hard to change (schema, shard key, code length), size tightly what's easy to add (stateless instances, cache nodes). With spare resources add ~20%; with tight ones, have a plan B such as shedding non-core features under overload.

Read in post: Back-of-the-envelope estimation
InterviewJuniorHow many requests per second is 1 million requests a day?

About 12 requests/second, since a day has ~86,400 ≈ 10⁵ seconds.

That's the average; peak hours are usually 2–3×, so design for about 30–40 RPS.

Read in post: Back-of-the-envelope estimation
InterviewJuniorHow much downtime does 99.99% availability allow?

About 52 minutes a year, or 4.3 minutes a month.

Short enough that manual recovery is out: you need automatic failover and zero-downtime deployments.

Read in post: Back-of-the-envelope estimation
InterviewMidWhat is Little's Law and how do you use it?

L = λ × W: requests in flight equal arrival rate times time in the system. I use it to size connection pools, thread pools and server counts.

Example: 3,000 queries/second at 5 ms each → 15 busy connections. The important consequence: if latency goes up 10×, you need 10× the connections, which is how a slow database drains the pools of the whole application cluster.

Read in post: Back-of-the-envelope estimation
InterviewMidEstimate 4 years of storage for a URL shortener with 10 million links a day.

About 1.1 KB per record × 10⁷ × 365 × 4 ≈ 16 TB, times 3 replicas ≈ 50 TB.

Conclusion: writes are only 100 TPS, so no sharding for writes, but 50 TB means planning time-based partitioning or a distributed key-value store.

Read in post: Back-of-the-envelope estimation
InterviewMidHow long should the URL shortener's code be?

7 base62 characters: 62⁷ ≈ 3.5 trillion codes, about 240× the 15 billion links needed over 4 years.

6 characters (~57 billion) still fits but with only ~4× headroom, which gets tight if load grows or if codes are random (collisions rise as the space fills up).

Read in post: Back-of-the-envelope estimation
InterviewSeniorYou've estimated 30K read QPS. What do you decide next?

Put a cache in front of the database and recompute what still reaches the database, then choose replica and application instance counts.

At a 90% hit ratio the database sees only ~3K QPS, so one primary with 1–2 replicas is enough. Application instances come from Little's Law with the target latency, plus spare capacity for losing a zone.

Read in post: Back-of-the-envelope estimation
InterviewSeniorWhen do you overestimate and when do you size tightly?

Overestimate what's hard to change (shard key, schema, ID length), size tightly what's easy to add (stateless instances, cache nodes).

Underestimating something hard to change means migrating data while live, which is very expensive. Easy-to-add things are handled by autoscaling, so overestimating them only costs money.

Read in post: Back-of-the-envelope estimation
Edge caseSeniorAn oversized request may get its connection cut instead of an error pageWhen it rejects a multipart request halfway, Tomcat only reads and discards up to server.tomcat.max-swallow-size (default 2MB) of the remaining body. If more is left, Tomcat closes the connection, and a browser still uploading may report "connection reset" instead of showing the 400 page. In my experiment the client st

When it rejects a multipart request halfway, Tomcat only reads and discards up to server.tomcat.max-swallow-size (default 2MB) of the remaining body. If more is left, Tomcat closes the connection, and a browser still uploading may report "connection reset" instead of showing the 400 page. In my experiment the client still read the 400, but don't count on it.

Reject early at the reverse proxy (Nginx's client_max_body_size, see the reverse proxy post) and check file.size in JavaScript before sending.

Read in post: File upload in Spring MVC
Trade-offSeniorUpload through the app or with a presigned URL straight to object storageThrough the app: the browser sends the file to Spring, Spring pushes it to S3. Easy to inspect the content (you have the bytes), one place holds the access rules. But the app pays the bandwidth and a thread for the whole upload. Presigned URL: the app signs a URL valid for a few minutes for exactly one key; the browser
  • Through the app: the browser sends the file to Spring, Spring pushes it to S3. Easy to inspect the content (you have the bytes), one place holds the access rules. But the app pays the bandwidth and a thread for the whole upload.
  • Presigned URL: the app signs a URL valid for a few minutes for exactly one key; the browser PUTs straight to S3, then tells the app the key. The app stays light and big files never touch it. But the content isn't checked on arrival, so you need a scan step afterwards (bucket event, magic-byte job, virus scan) and you only publish the file once it passes.
  • Avatars of a few hundred KB: through the app is fine. Videos, large documents: presigned URLs.
Read in post: File upload in Spring MVC
Edge caseMidgetRealPath is not a place for long-lived filesgetRealPath returns the running web app's directory. With java -jar, Spring Boot points it at a temp directory (or returns null), so every redeploy loses the old images. In a war on Tomcat, a redeploy also deletes the old directory. The upload directory must live outside the application and be configurable, e.g. app.up

getRealPath returns the running web app's directory. With java -jar, Spring Boot points it at a temp directory (or returns null), so every redeploy loses the old images. In a war on Tomcat, a redeploy also deletes the old directory. The upload directory must live outside the application and be configurable, e.g. app.upload.dir=/var/lib/shop/uploads, like any other config (Twelve-factor app).

Read in post: File upload in Spring MVC
Edge caseMidPutting getOriginalFilename into the path is path traversalThe client chooses the filename. Send filename="../../../WEB-INF/views/index.jsp" and the joined path points out of the image folder and overwrites another file. Even without .., names can contain odd characters, collide, or leak information (the user's real name). The server generates the name (UUID) and chooses the e

The client chooses the filename. Send filename="../../../WEB-INF/views/index.jsp" and the joined path points out of the image folder and overwrites another file. Even without .., names can contain odd characters, collide, or leak information (the user's real name).

The server generates the name (UUID) and chooses the extension from the content. If you want to show the original name, store it in its own column, sanitised, and never use it as a path.

Read in post: File upload in Spring MVC
Edge caseMidgetBytes() loads the whole file into memorygetBytes() allocates an array the size of the file on the heap. Ten people uploading 100MB files means 1GB of heap just for temporary arrays, an easy route to OutOfMemoryError. Use getInputStream() with Files.copy(in, target), or transferTo(path): data moves in small chunks. Also close streams with try-with-resources.

getBytes() allocates an array the size of the file on the heap. Ten people uploading 100MB files means 1GB of heap just for temporary arrays, an easy route to OutOfMemoryError. Use getInputStream() with Files.copy(in, target), or transferTo(path): data moves in small chunks.

Also close streams with try-with-resources. Code that opens a BufferedOutputStream and calls close() at the end leaks a file handle when write throws halfway.

Read in post: File upload in Spring MVC
Edge caseMidTrusting the Content-Type the browser sendsgetContentType() is just a header the client declares. An HTML file containing <script renamed to .png still arrives as Content-Type: image/png. If the server saves it with an .html extension (from the original name) or serves it with the declared type, the browser may run that script on your domain: stored XSS. Detect

getContentType() is just a header the client declares. An HTML file containing <script> renamed to .png still arrives as Content-Type: image/png. If the server saves it with an .html extension (from the original name) or serves it with the declared type, the browser may run that script on your domain: stored XSS.

Detect the type from the first few bytes (magic bytes): PNG starts with 89 50 4E 47, JPEG with FF D8 FF, WebP with RIFF....WEBP. Accept only types on the allowlist. The test uploadRejectsHtmlDisguisedAsPng sends exactly such a file and gets 400.

Read in post: File upload in Spring MVC
Edge caseMidMap.of(...).get(null) throws NullPointerExceptionThe first version of the service read ext = ALLOWED.get(sniff(bytes)). For an unrecognised file sniff returns null, and Map.of(...) (Java 9+ immutable map) throws NPE on a null key, unlike HashMap, which returns null. Result: an HTML file posing as PNG got a 500 page instead of a 400. The test uploadRejectsHtmlDisguise

The first version of the service read ext = ALLOWED.get(sniff(bytes)). For an unrecognised file sniff returns null, and Map.of(...) (Java 9+ immutable map) throws NPE on a null key, unlike HashMap, which returns null. Result: an HTML file posing as PNG got a 500 page instead of a 400. The test uploadRejectsHtmlDisguisedAsPng caught it on the first run.

Lesson: check for null before looking up an immutable collection (Map.of, Set.of, List.of all reject null), and always test the rejection path, not only the happy one.

Read in post: File upload in Spring MVC
Edge caseSeniorAccepting SVG or HTML uploads and serving them from your own domainSVG is XML and can contain <script. Open https://shop.example/files/x.svg directly and the script runs with your domain's cookies. HTML, XML and PDFs with JavaScript are similar. Defend with at least one of: don't accept those types; serve user uploads from a separate domain (e.g. usercontent.example, with no login coo

SVG is XML and can contain <script>. Open https://shop.example/files/x.svg directly and the script runs with your domain's cookies. HTML, XML and PDFs with JavaScript are similar.

Defend with at least one of: don't accept those types; serve user uploads from a separate domain (e.g. usercontent.example, with no login cookie); send Content-Disposition: attachment so the browser downloads instead of opening; add Content-Security-Policy: sandbox to the file-serving path.

Read in post: File upload in Spring MVC
InterviewJuniorWhat does a file upload form need that a normal form doesn't?

method="post" and enctype="multipart/form-data"; the controller takes a MultipartFile (or List<MultipartFile> for several files).

Without enctype the browser sends x-www-form-urlencoded, which carries only the filename, not the content.

Read in post: File upload in Spring MVC
InterviewJuniorWhy not use getOriginalFilename() as the filename on disk?

Because the client chose it: it can contain ../ to write outside the folder (path traversal), collide with another file, or contain odd characters.

The server generates the name (UUID) with an extension chosen from the content. The original name, if you need to display it, goes into its own database column.

Read in post: File upload in Spring MVC
InterviewMidHow do you know an uploaded file really is an image?

Read the first few bytes (magic bytes) and compare them with the signatures of allowed types; don't trust the extension or the client's Content-Type.

More thorough: decode the image with an imaging library, check the pixel dimensions, then write a fresh image to strip metadata and stray data.

Read in post: File upload in Spring MVC
InterviewMidWhat happens in Spring Boot when an upload exceeds the limit, and how do you handle it?

Spring throws MaxUploadSizeExceededException while parsing the multipart body, before the controller runs; catch it in a @ControllerAdvice and return a 400 with a clear message.

The limits are spring.servlet.multipart.max-file-size (default 1MB) and max-request-size (default 10MB). A very large request may have its connection cut by Tomcat (max-swallow-size), so also limit it at the reverse proxy and in JavaScript.

Read in post: File upload in Spring MVC
InterviewMidHow do getBytes() and getInputStream() differ when saving a file?

getBytes() loads the whole file into a heap array; getInputStream() lets you copy in chunks with roughly constant memory.

Many concurrent large uploads with getBytes() can easily cause OutOfMemoryError. Use Files.copy(in, target) or transferTo, and close streams with try-with-resources.

Read in post: File upload in Spring MVC
InterviewSeniorThe app runs three instances behind a load balancer. Where should uploaded images go?

Object storage (S3, MinIO, GCS), with only the key in the database. Local disk doesn't work because each instance sees only its own files.

Serve public images through a CDN, and private files through short-lived presigned URLs after a permission check. Large files can go up directly with a presigned PUT, followed by a scan once they arrive.

Read in post: File upload in Spring MVC
InterviewSeniorHow can user-uploaded files cause XSS, and how do you stop it?

An SVG, HTML file or anything served with the wrong Content-Type gets opened by the browser as a page on your domain, and its script runs with the viewer's cookies.

Stop it with: an allowlist checked by magic bytes, extension and Content-Type chosen by the server, nosniff, Content-Disposition: attachment for non-images, and serving user content from a separate cookieless domain.

Read in post: File upload in Spring MVC
InterviewSeniorThe file was saved but the database transaction rolled back. What do you do with the file?

Register an afterCompletion callback: on rollback delete the new file, on commit delete the replaced old one; add a periodic job that removes files nothing points to.

The file system and the database don't share a transaction, so the callback is best effort. The cleanup job uses an age threshold (say 24 hours) so it never deletes a file belonging to a request still in flight.

Read in post: File upload in Spring MVC
Edge caseJuniorReturning 403 for unauthenticated requests and 401 for missing permissions401 Unauthorized means not authenticated and must carry a WWW-Authenticate header; 403 Forbidden means the server knows who you are but you lack permission. Mixing them up breaks clients: on 401 they refresh or log in again, on 403 that's pointless. If a resource's mere existence is sensitive (someone else's order), re

401 Unauthorized means not authenticated and must carry a WWW-Authenticate header; 403 Forbidden means the server knows who you are but you lack permission. Mixing them up breaks clients: on 401 they refresh or log in again, on 403 that's pointless. If a resource's mere existence is sensitive (someone else's order), returning 404 instead of 403 is acceptable.

Read in post: Authentication
Trade-offMidAPI key or OAuth2 client credentials for machine-to-machine integrationAPI key: one header and you're done, no auth server needed; but keys are long-lived, a leaked key works until revoked, and every service looks keys up itself. OAuth2 client credentials: the client trades clientid + secret for a short-lived access token; services only verify the signature and the root secret rarely cros
  • API key: one header and you're done, no auth server needed; but keys are long-lived, a leaked key works until revoked, and every service looks keys up itself.
  • OAuth2 client credentials: the client trades client_id + secret for a short-lived access token; services only verify the signature and the root secret rarely crosses the network. The price: running an auth server, and partners add a token-fetching step.
  • Public API for many small partners: API keys. An auth server already exists and you need short-lived tokens and central auditing: client credentials.
Read in post: Authentication
Edge caseMidNot changing the session ID after login invites session fixationThe attacker plants an unauthenticated session ID in the victim's browser (a link with ;jsessionid=, or a subdomain writing a cookie onto the parent domain). The victim logs in, the server attaches the user to that same ID, and the attacker is now logged in too. Fix: issue a new ID on login or privilege change (Spring

The attacker plants an unauthenticated session ID in the victim's browser (a link with ;jsessionid=, or a subdomain writing a cookie onto the parent domain). The victim logs in, the server attaches the user to that same ID, and the attacker is now logged in too. Fix: issue a new ID on login or privilege change (Spring Security does changeSessionId() by default), disable session IDs in URLs, use the __Host- prefix.

Read in post: Authentication
Trade-offSeniorSessions in Redis or stateless JWTSession + Redis: instant revocation, a small cookie, no data handed to the client, "log out everywhere" is easy. The price: every request depends on Redis, and it only fits when services trust the same store. JWT: services verify the signature themselves with no outbound call, which suits many services owned by many te
  • Session + Redis: instant revocation, a small cookie, no data handed to the client, "log out everywhere" is easy. The price: every request depends on Redis, and it only fits when services trust the same store.
  • JWT: services verify the signature themselves with no outbound call, which suits many services owned by many teams, and mobile. The price: no revocation before expiry without adding state, bigger tokens, many configuration traps.
  • A monolith or a few services: session + Redis. Many services, many client types, a dedicated auth server: short-lived access JWTs plus stateful refresh tokens.
Read in post: Authentication
Edge caseSeniorTokens in localStorage turn any XSS bug into account takeoverThe slides suggest storing the token in local storage, but every script on your origin (an XSS bug, a compromised npm package) can read it and ship the token off to be used from another machine until it expires. With an HttpOnly cookie, XSS can only send requests while the page is open. If tokens must live on the clien

The slides suggest storing the token in local storage, but every script on your origin (an XSS bug, a compromised npm package) can read it and ship the token off to be used from another machine until it expires. With an HttpOnly cookie, XSS can only send requests while the page is open. If tokens must live on the client, keep the access token in JavaScript memory and the refresh token in an HttpOnly cookie whose Path is limited to the refresh endpoint.

Read in post: Authentication
Trade-offSeniorHS256 or RS256/ES256 for JWTsHS256: fast and simple, but every service that verifies tokens must hold the same secret, and anyone holding the secret can also sign tokens. Ten services with the secret are ten places that can leak the ability to forge an admin token. RS256/ES256: only the auth server holds the private key; services fetch the public
  • HS256: fast and simple, but every service that verifies tokens must hold the same secret, and anyone holding the secret can also sign tokens. Ten services with the secret are ten places that can leak the ability to forge an admin token.
  • RS256/ES256: only the auth server holds the private key; services fetch the public key from a JWKS endpoint (a published JSON list of public keys) and can only verify. Rotate keys by publishing a new key under a new kid and keeping the old one until old tokens expire.
  • Use HS256 when one service both issues and verifies; otherwise use asymmetric keys, preferably ES256 or EdDSA.
Read in post: Authentication
Edge caseSeniorLetting the token pick its algorithm leads to alg none and algorithm confusionalg none: a token with "alg":"none" and an empty signature, which old libraries accept. Algorithm confusion: the service uses RS256 and its public key is, well, public; the attacker switches the header to HS256 and signs an HMAC with that public key. A library with a generic verify(token, key) uses the public key as th

alg none: a token with "alg":"none" and an empty signature, which old libraries accept. Algorithm confusion: the service uses RS256 and its public key is, well, public; the attacker switches the header to HS256 and signs an HMAC with that public key. A library with a generic verify(token, key) uses the public key as the HMAC secret and accepts it. Fix: the server pins the algorithm and key type in configuration and never reads them from the token.

Read in post: Authentication
Edge caseSeniorChecking the signature but skipping aud, iss and expA valid signature proves the auth server issued the token, not that it was issued for you. A token for a low-stakes service can be replayed against the payment service unless that service checks aud. Always check iss, aud, exp and nbf with 30–60 seconds of clock skew. Libraries usually check exp by default, not aud.

A valid signature proves the auth server issued the token, not that it was issued for you. A token for a low-stakes service can be replayed against the payment service unless that service checks aud. Always check iss, aud, exp and nbf with 30–60 seconds of clock skew. Libraries usually check exp by default, not aud.

Read in post: Authentication
TILJuniorJWTs aren't encrypted: the payload is just Base64urlMost JWTs are JWS (JSON Web Signature): the header and payload are only Base64url-encoded, so anyone holding the token can read them with base64 -d. The signature guarantees nobody can change the content undetected; it doesn't hide it. Hiding requires JWE (JSON Web Encryption), five parts instead of three. Saying "JWTs

Most JWTs are JWS (JSON Web Signature): the header and payload are only Base64url-encoded, so anyone holding the token can read them with base64 -d. The signature guarantees nobody can change the content undetected; it doesn't hide it. Hiding requires JWE (JSON Web Encryption), five parts instead of three. Saying "JWTs are encrypted, so they're safe" is a red flag.

Read in post: Authentication
Edge caseSeniorRotating refresh tokens without a grace period logs real users outA mobile app loses connectivity right as the refresh response arrives: the server has marked r1 used and issued r2, the client never got it and resends r1, and strict reuse detection revokes the whole family. Two SPA tabs refreshing at once do the same. The usual fix: a grace period of a few dozen seconds during which

A mobile app loses connectivity right as the refresh response arrives: the server has marked r1 used and issued r2, the client never got it and resends r1, and strict reuse detection revokes the whole family. Two SPA tabs refreshing at once do the same. The usual fix: a grace period of a few dozen seconds during which reusing r1 returns the same r2 already issued, and on the client only one refresh in flight at a time.

Read in post: Authentication
TILSeniorSpring Security 6 no longer saves the SecurityContext to the session automaticallySince Spring Security 6, SecurityContextHolderFilter replaces SecurityContextPersistenceFilter and does not automatically save the SecurityContext into the session at the end of the request. A hand-written login endpoint that only calls SecurityContextHolder.getContext().setAuthentication(auth) will see the next reques

Since Spring Security 6, SecurityContextHolderFilter replaces SecurityContextPersistenceFilter and does not automatically save the SecurityContext into the session at the end of the request. A hand-written login endpoint that only calls SecurityContextHolder.getContext().setAuthentication(auth) will see the next request as unauthenticated. You must call securityContextRepository.saveContext(context, request, response). A common bug when upgrading from Spring Boot 2 to 3.

Read in post: Authentication
Trade-offSeniorHow long access tokens should live5 minutes: a leaked token is useful for only minutes, and revocation needs almost no state; but three times as many refreshes, more load on the auth server and more refresh races. 1 hour or more: few refreshes; but a denylist or token version becomes practically mandatory, i.e. you're stateful again. 10–15 minutes is t
  • 5 minutes: a leaked token is useful for only minutes, and revocation needs almost no state; but three times as many refreshes, more load on the auth server and more refresh races.
  • 1 hour or more: few refreshes; but a denylist or token version becomes practically mandatory, i.e. you're stateful again.
  • 10–15 minutes is the common sweet spot; highly sensitive APIs add a sid check or step-up re-authentication instead of shortening the TTL for the whole system.
Read in post: Authentication
InterviewJuniorHow does authentication differ from authorization?

Authentication verifies who you are; authorization decides what you may do.

Missing or bad credentials get 401 with WWW-Authenticate; authenticated but not permitted gets 403.

Read in post: Authentication
InterviewJuniorIs Basic auth secure?

Only acceptable over TLS for internal tools or service-to-service calls, because Base64 is just encoding.

Over HTTPS nobody reads it on the wire, but the raw password travels with every request and there's no logout.

Read in post: Authentication
InterviewJuniorWhat are the parts of a JWT? Is the payload secret?

Three Base64url parts: header, payload, signature. The payload isn't secret; anyone holding the token can read it.

The header has the algorithm and kid; the payload has claims like iss, sub, aud, exp; the signature only prevents tampering. Keep sensitive data out of the payload.

Read in post: Authentication
InterviewMidWhich flags should a session cookie have, and why?

HttpOnly, Secure, SameSite=Lax/Strict and the __Host- prefix.

HttpOnly so scripts can't read it, Secure so it only travels over HTTPS, SameSite to mitigate CSRF, __Host- so subdomains can't overwrite it. Add idle and absolute timeouts, and change the session ID on login to block session fixation.

Read in post: Authentication
InterviewMidAre sessions really hard to scale?

No, only when sessions live in each instance's RAM.

Spring Session + Redis lets every instance share them; the real cost is the dependency on Redis.

Read in post: Authentication
InterviewMidWhere should an SPA keep its tokens?

Not in localStorage; best is a BFF that keeps tokens on the server while the browser only has an HttpOnly cookie.

One XSS bug is enough to steal tokens from localStorage. Without a BFF, keep the access token in memory and the refresh token in an HttpOnly cookie scoped to the refresh endpoint.

Read in post: Authentication
InterviewMidHow do refresh token rotation and reuse detection work?

Each refresh marks the old token used and issues a new one in the same family; if a used token shows up again, the whole family is revoked.

A reused token means two parties hold it. You need a short grace period for clients that lost the response.

Read in post: Authentication
InterviewSeniorHow do you revoke a JWT before it expires?

You have to add state; typically a short TTL for most APIs and a state check for sensitive ones.

The options: a short TTL plus refresh token revocation; a jti denylist in Redis; a per-user token_version; or a sid claim pointing at a server-side session.

Read in post: Authentication
InterviewSeniorWhat is JWT algorithm confusion and how do you prevent it?

The attacker switches alg from RS256 to HS256 and signs with the public key as the secret; prevent it by pinning the algorithm on the server.

An RS256 public key is available to everyone, and a generic verify call accepts such a token. Pin the algorithm and key type on the server (e.g. NimbusJwtDecoder.jwsAlgorithm(...)), never read alg from the token, and reject none.

Read in post: Authentication
InterviewSeniorWhen do you choose sessions and when JWTs?

A monolith or a few services trusting one store: session + Redis. Many services, several client types, a dedicated auth server: short-lived JWTs.

Session + Redis gives instant revocation and fewer traps. With JWTs: short-lived, asymmetrically signed access tokens verified via JWKS, plus stateful refresh tokens.

Read in post: Authentication
InterviewSeniorDesign "log out of all devices" in a JWT-based system

Revoke all of the user's refresh token families and bump their token_version; services reject access tokens with an older ver.

Services cache the version for a few dozen seconds. The revocation delay equals the cache time, not the TTL.

Read in post: Authentication
TILJuniorInterfaces can have default, static and private methodsThe slides are outdated here: "interfaces only contain abstract methods" was true only up to Java 7. Java 8 added default and static methods, and Java 9 added private methods. Interfaces still have no instance state (no regular fields) and no constructors. Default methods exist to evolve a published interface without b

The slides are outdated here: "interfaces only contain abstract methods" was true only up to Java 7. Java 8 added default and static methods, and Java 9 added private methods. Interfaces still have no instance state (no regular fields) and no constructors.

Default methods exist to evolve a published interface without breaking existing implementations: Java 8 added them so Collection could gain stream().

Read in post: Object-oriented programming
Trade-offJuniorAbstract class vs interfaceWhat they share: both express abstraction, both can be used as types (for variables and parameters), and neither can be instantiated directly.
Abstract class Interface
Instance state (fields) Yes No (only public static final constants)
Constructors Yes No
Methods with bodies Yes default, static, private (Java 8/9+)
Inheritance A class extends only one A class implements many
Member access Anything public by default
Use it when Subclasses of one family share code and state Defining a capability or contract for unrelated classes

What they share: both express abstraction, both can be used as types (for variables and parameters), and neither can be instantiated directly.

Read in post: Object-oriented programming
Edge caseMidTwo interfaces with the same default method force the class to override itWhen a class implements two interfaces with default methods of the same signature, the compiler reports types A and B are incompatible and makes the class override the method. Inside the override, call each interface's version with A.super.method(): When there's no conflict, precedence rules apply: a class method (incl

When a class implements two interfaces with default methods of the same signature, the compiler reports types A and B are incompatible and makes the class override the method. Inside the override, call each interface's version with A.super.method():

interface A { default String hello() { return "A"; } }
interface B { default String hello() { return "B"; } }
class C implements A, B {
    @Override public String hello() { return A.super.hello() + B.super.hello(); }   // "AB"
}

When there's no conflict, precedence rules apply: a class method (including one inherited from a superclass) always beats an interface default ("class wins"), and a more specific interface beats its parent. That's how Java solves the "diamond problem" (inheriting the same thing through two branches, with no way to pick one) for behavior, while still not allowing multiple inheritance of state.

Read in post: Object-oriented programming
Edge caseSeniorCalling an overridable method from a constructor exposes uninitialized subclass fieldsThe parent's constructor runs before the subclass fields are assigned. If it calls a method the subclass overrides, dynamic dispatch (picking the method by the object's runtime type) still chooses the subclass version. That version reads its own fields while they still hold default values. One confusing exception: a fi

The parent's constructor runs before the subclass fields are assigned. If it calls a method the subclass overrides, dynamic dispatch (picking the method by the object's runtime type) still chooses the subclass version. That version reads its own fields while they still hold default values.

class Parent {
    Parent() { describe(); }                 // calls an overridable method
    void describe() { }
}
class Child extends Parent {
    private String name = "child";
    @Override void describe() {
        System.out.println(name.length());   // NullPointerException: name is still null
    }
}
new Child();

One confusing exception: a final primitive/String field initialized with a constant (final int size = 42;) does read as 42, because the compiler inlined the constant.

How to avoid it: call only private, static or final methods from a constructor; if setup depends on the subclass, use a factory method or a template method invoked after construction. This is an Effective Java rule, and it is also why this should never escape a constructor (registering listeners, starting threads).

Read in post: Object-oriented programming
InterviewJuniorCan an abstract class have a constructor? Must it have an abstract method?

Yes, it can have constructors, and no, it doesn't need an abstract method.

You can't call the constructors with new directly, but they run through super(...) when a subclass object is created, to initialize and validate the shared state. An abstract class may have no abstract methods and exist just to forbid direct instantiation. Conversely, a class with an abstract method must be abstract, and so must a subclass that doesn't implement all of them.

Read in post: Object-oriented programming
InterviewMidAbstract class versus interface: what's the difference, and when do you use each?

An abstract class has state and constructors and supports single inheritance. An interface has no instance state, and a class can implement many.

Since Java 8 interfaces also have default/static methods. Use an abstract class when subclasses of one family share code and state (e.g. the Template Method pattern). Use an interface to define a contract or capability, and as the seam for dependency injection.

Read in post: Object-oriented programming
InterviewMidOn the first new Child(), in what order do static blocks, instance blocks and constructors run?

Static before instance, parent before child, initializers before the constructor body.

In detail: Parent's statics, Child's statics (only when the class is first initialized), then Parent's field initializers and { } blocks, Parent's constructor, Child's field initializers and { } blocks, and finally Child's constructor. A second new skips the static part.

Read in post: Object-oriented programming
InterviewMidWhat happens when a class implements two interfaces with the same default method?

If neither interface is more specific, the compiler reports an error and forces the class to override; inside the override you can call A.super.hello() or B.super.hello().

If the class's superclass already has that method, the class method wins and nothing is needed ("class wins"). If one interface extends the other, the more specific interface wins. That's how Java allows multiple inheritance of behavior through interfaces while still avoiding the diamond problem for state.

Read in post: Object-oriented programming
InterviewSeniorHow do sealed interfaces (Java 17) help with domain modeling?

They restrict the set of implementations, so you can model "one of these cases" (a sum type) and the compiler checks that a switch covers every case.

For example PaymentResult = Success | Failure. Combined with records and pattern-matching switch, the compiler checks exhaustiveness. Add a new case and every switch that doesn't handle it fails to compile, instead of silently falling into default at runtime.

Read in post: Object-oriented programming
InterviewSeniorWhy is calling an overridable method from a constructor dangerous?

The parent's constructor runs before the subclass fields are initialized, yet dynamic dispatch still calls the subclass override.

That override reads fields that are still null/0, which leads to a NullPointerException or subtly wrong state that is hard to track down. To avoid it, call only private/static/final methods from constructors, use a factory method for subclass-specific setup, and don't let this escape (listeners, threads) before construction finishes.

Read in post: Object-oriented programming
TILMidArrays.sort uses Dual-Pivot Quicksort for primitives and TimSort for objectsArrays.sort(int[]): Dual-Pivot Quicksort, fast; primitives don't need stability. Arrays.sort(Object[]) and List.sort: TimSort, stable, O(n) on nearly sorted data.
  • Arrays.sort(int[]): Dual-Pivot Quicksort, fast; primitives don't need stability.
  • Arrays.sort(Object[]) and List.sort: TimSort, stable, O(n) on nearly sorted data.
Read in post: Algorithm practice
Trade-offMidMemoization (top-down) or tabulation (bottom-up)Memoization: keeps the recursive shape and adds a cache. Easy to write, computes only the states you need, but uses O(depth) stack and can overflow for large n. Tabulation: a loop from the small cases up. No stack, often less memory, but you work out the evaluation order yourself and may compute states you never need.
  • Memoization: keeps the recursive shape and adds a cache. Easy to write, computes only the states you need, but uses O(depth) stack and can overflow for large n.
  • Tabulation: a loop from the small cases up. No stack, often less memory, but you work out the evaluation order yourself and may compute states you never need.

In an interview: write the memoized version first to get it right, then offer to convert it to tabulation for large n.

Read in post: Algorithm practice
Edge caseSeniorRecursing inside HashMap.computeIfAbsent throws ConcurrentModificationExceptioncache.computeIfAbsent(n, k - fib(k - 1) + fib(k - 2)) is wrong: the mapping function modifies the very map it runs in, which the Javadoc forbids. HashMap (since Java 9) detects it and throws ConcurrentModificationException. I ran fib(30) on JDK 21: it throws immediately. ConcurrentHashMap is worse: it can hang forever

cache.computeIfAbsent(n, k -> fib(k - 1) + fib(k - 2)) is wrong: the mapping function modifies the very map it runs in, which the Javadoc forbids.

  • HashMap (since Java 9) detects it and throws ConcurrentModificationException. I ran fib(30) on JDK 21: it throws immediately.
  • ConcurrentHashMap is worse: it can hang forever or throw IllegalStateException.

Use a separate get then put, or an array like fibMemo.

Read in post: Algorithm practice
Edge caseMidDeep recursion throws StackOverflowError and Java doesn't optimise tail callsEach call takes a stack frame (the memory slot holding that call's parameters and local variables). The default stack is around 512 KB–1 MB per thread, so recursion a few tens of thousands of levels deep (sum(100000)) throws StackOverflowError. Java does not optimise tail calls (a tail call is a recursive call that is

Each call takes a stack frame (the memory slot holding that call's parameters and local variables). The default stack is around 512 KB–1 MB per thread, so recursion a few tens of thousands of levels deep (sum(100_000)) throws StackOverflowError. Java does not optimise tail calls (a tail call is a recursive call that is the function's last action), so rewriting in that form won't save you.

Read in post: Algorithm practice
Edge caseJuniorlong overflows silentlypowerOfTwo(64) returns 0 with no error. Use Math.multiplyExact to detect it, or BigInteger for big numbers.

powerOfTwo(64) returns 0 with no error. Use Math.multiplyExact to detect it, or BigInteger for big numbers.

Read in post: Algorithm practice
Trade-offMidRecursion or a loopSimple linear problems on real data (summing 1..n, summing even numbers, checking symmetry) should be loops. Recursion pays off when the data is recursive by nature (trees, graphs) or for divide and conquer (merge sort, fast exponentiation).

Simple linear problems on real data (summing 1..n, summing even numbers, checking symmetry) should be loops. Recursion pays off when the data is recursive by nature (trees, graphs) or for divide and conquer (merge sort, fast exponentiation).

Read in post: Algorithm practice
InterviewJuniorWhat is the base case of a recursive function? What happens if it's missing or wrong?

It's the smallest case where the function returns immediately without calling itself (say n == 0). If it's missing or wrong, the function keeps calling itself until it throws StackOverflowError.

Every recursive step has to move closer to the base case. A step that doesn't shrink the problem (a negative n against an n == 0 check) also recurses forever. That's why invalid input should be rejected at the top of the function.

Read in post: Algorithm practice
InterviewJuniorWhat is a stable sort, and when does it matter?

Stable means elements with equal keys keep their original relative order. It matters when you sort in several passes by several criteria.

Example: sort orders by time, then stable-sort by status, and within each status they stay in time order. In Java, List.sort and Arrays.sort(Object[]) use TimSort, which is stable. Arrays.sort(int[]) uses Dual-Pivot Quicksort, which isn't, but two equal primitives are indistinguishable, so it doesn't matter.

Read in post: Algorithm practice
InterviewMidWhat is the complexity of fast exponentiation and of naive Fibonacci? Explain with recurrences.

Fast exponentiation: T(n) = T(n/2) + O(1), so O(log n) time and stack. Naive Fibonacci: T(n) = T(n−1) + T(n−2) + O(1), calls grow exponentially around 1.618ⁿ, while the stack is only O(n).

  • pow(x, n) makes exactly one call to pow(x, n/2) plus O(1) work. Writing pow(x, n/2) * pow(x, n/2) (two calls) gives T(n) = 2T(n/2) + O(1) = O(n) and throws the advantage away.
  • fib(30) takes about 2.7 million calls.
Read in post: Algorithm practice
InterviewMidHow do memoization and tabulation differ?

Both store subproblem results so nothing is computed twice; memoization goes top-down with recursion, tabulation goes bottom-up with a loop.

  • Memoization: keep the recursive function and check the cache before computing. Easy to derive from the formula and computes only the states needed, but uses stack and can overflow.
  • Tabulation: fill a table from the small cases upwards. No stack and often less memory, but you work out the evaluation order. Fibonacci shrinks to two variables, O(1) memory.
Read in post: Algorithm practice
InterviewMidWhy does Arrays.sort use different algorithms for int[] and Object[]?

Primitives don't need stability, so it uses the fast Dual-Pivot Quicksort; objects do, so it uses TimSort.

  • Dual-Pivot Quicksort: fast in practice, sorts in place, cache-friendly.
  • TimSort: elements "equal" under the comparator are still different objects. TimSort is stable, O(n log n) worst case and close to O(n) on nearly sorted data, at the cost of O(n) extra memory.
  • A comparator that breaks the contract (not transitive) can make TimSort throw IllegalArgumentException: Comparison method violates its general contract.
Read in post: Algorithm practice
InterviewSeniorA recursive function passes its tests but crashes in production with StackOverflowError. What do you do?

Switch to a loop with an explicit stack or queue (ArrayDeque), or change the algorithm so the depth is O(log n). Raising -Xss is only a band-aid.

Usually the recursion depth grows with the real data size: a long list, a tree degenerated into a line, cyclic data with no stop condition. Java doesn't optimise tail calls, so a tail-recursive rewrite won't help. Also: test with production-sized data and detect cycles with a visited set.

Read in post: Algorithm practice
Edge caseJuniorThe slide's E-Learning diagram has typos and contradicts itself on Teacher–CourseThe physical diagram says Tearcher, tearcherid, UserCourseLession and lesson type SLICE; they should be Teacher, teacherid, UserCourseLesson and SLIDE. Typos in names are not harmless: once in production, renaming means a migration with downtime or a period of supporting both names. The Chen diagram in the review secti

The physical diagram says Tearcher, tearcher_id, User_Course_Lession and lesson type SLICE; they should be Teacher, teacher_id, User_Course_Lesson and SLIDE. Typos in names are not harmless: once in production, renaming means a migration with downtime or a period of supporting both names.

The Chen diagram in the review section draws Course–Teacher as N–M, while the physical diagram has course.teacher_id, which is 1–N (one teacher per course). The two levels of design must agree; if a course can have several instructors, you need a course_teacher join table.

Read in post: SQL exercises on the E-Learning database
Trade-offMidRanking by average rating: a minimum count or a weighted averageRanking by average rating puts a course with a single 5-star rating on top. A minimum count (HAVING COUNT(uc.rating) = 10) is a product decision. Real platforms often use a weighted (Bayesian) average — it pulls the score of a course with few ratings towards the overall mean — to balance score against volume.

Ranking by average rating puts a course with a single 5-star rating on top. A minimum count (HAVING COUNT(uc.rating) >= 10) is a product decision. Real platforms often use a weighted (Bayesian) average — it pulls the score of a course with few ratings towards the overall mean — to balance score against volume.

Read in post: SQL exercises on the E-Learning database
Edge caseMidFan-out from joining down to a child table inflates COUNTFan-out (parent rows multiplied when you join down to a child table): joining course → chapter → lesson repeats each chapter once per lesson, so COUNT(ch.id) gives the number of lessons, not chapters. To count a parent after joining down to its children, use COUNT(DISTINCT ch.id), or count each level in its own subquer

Fan-out (parent rows multiplied when you join down to a child table): joining course → chapter → lesson repeats each chapter once per lesson, so COUNT(ch.id) gives the number of lessons, not chapters. To count a parent after joining down to its children, use COUNT(DISTINCT ch.id), or count each level in its own subquery/CTE and join the results.

Read in post: SQL exercises on the E-Learning database
Edge caseMidupdated_date is not the completion timeupdateddate is when the row was last modified, not when it became DONE. A data-fix job, or a new column (say, seconds watched) being updated, silently breaks the "most recent" order. The column is also nullable, and MySQL sorts NULLs last under ORDER BY ... DESC. A business event that matters deserves its own column: c

updated_date is when the row was last modified, not when it became DONE. A data-fix job, or a new column (say, seconds watched) being updated, silently breaks the "most recent" order. The column is also nullable, and MySQL sorts NULLs last under ORDER BY ... DESC. A business event that matters deserves its own column: completed_at, written once when the status flips to DONE.

Read in post: SQL exercises on the E-Learning database
Edge caseJuniororder is a reserved word, so a column named order has to be quotedThe chapter and lesson tables have a column called order, which clashes with ORDER BY. After a dot (ch.order) MySQL still reads it as a column name, but unqualified it is a syntax error: CREATE TABLE ... (order INT), INSERT INTO chapter(order, ...) and ORDER BY order all fail. You must quote it: order in MySQL, "order"

The chapter and lesson tables have a column called order, which clashes with ORDER BY. After a dot (ch.order) MySQL still reads it as a column name, but unqualified it is a syntax error: CREATE TABLE ... (order INT), INSERT INTO chapter(order, ...) and ORDER BY order all fail.

You must quote it: `order` in MySQL, "order" in PostgreSQL. An ORM that generates unquoted SQL breaks too (in JPA you declare a quoted column name or turn on global quoting). Calling the column position or sort_order from day one avoids the whole mess.

Read in post: SQL exercises on the E-Learning database
Edge caseSeniorThe redundant course_id in user_course_lesson can disagree with lesson → chapter → courseusercourselesson has a foreign key (userid, courseid) → usercourse and lessonid → lesson, but nothing guarantees that lessonid belongs to that courseid (a lesson belongs to a course through lesson.chapterid → chapter.courseid). One application bug can record progress on a Java lesson against a SQL enrolment, and every

user_course_lesson has a foreign key (user_id, course_id) → user_course and lesson_id → lesson, but nothing guarantees that lesson_id belongs to that course_id (a lesson belongs to a course through lesson.chapter_id → chapter.course_id). One application bug can record progress on a Java lesson against a SQL enrolment, and every report that trusts ucl.course_id will be quietly wrong.

Options:

  • When computing, join back through lesson → chapter and check ch.course_id = ucl.course_id (as in Q9).
  • Validate in the service before writing.
  • Add course_id to lesson with a UNIQUE (id, course_id), so a composite foreign key (lesson_id, course_id) → lesson(id, course_id) can enforce it.
Read in post: SQL exercises on the E-Learning database
Trade-offSeniorE-Learning accounts: separate user/teacher/admin tables or one account table with rolesThree separate tables (as on the slide): each type gets its own columns without NULL-filled ones, and the foreign key course.teacherid → teacher guarantees the instructor is a teacher. The cost: duplicated login columns, one person can't both learn and teach with one account, usernames can collide across tables, and lo

Three separate tables (as on the slide): each type gets its own columns without NULL-filled ones, and the foreign key course.teacher_id → teacher guarantees the instructor is a teacher. The cost: duplicated login columns, one person can't both learn and teach with one account, usernames can collide across tables, and login checks several places.

One account table plus a role (or an account_role table if a person can hold several roles): login, authorisation and account locking live in one place, which maps neatly onto Spring Security. The cost: a foreign key can't check "teacher_id must have the TEACHER role"; you check it in the service, or add a profile table such as teacher_profile(account_id PK/FK, bio, ...) for the foreign key to point at. Real systems usually go with the second option plus role-specific profile tables.

Read in post: SQL exercises on the E-Learning database
Edge caseSeniorMySQL ignores REFERENCES written inline in a column definitionIf you write teacherid BIGINT NOT NULL REFERENCES account(id) (an inline foreign key, as the SQL standard allows), MySQL 8.x, including 8.4 LTS, parses it and throws it away: no error, no constraint, and inserting a non-existent teacherid = 999 succeeds. I hit exactly this while test-running the E-Learning schema. Post

If you write teacher_id BIGINT NOT NULL REFERENCES account(id) (an inline foreign key, as the SQL standard allows), MySQL 8.x, including 8.4 LTS, parses it and throws it away: no error, no constraint, and inserting a non-existent teacher_id = 999 succeeds. I hit exactly this while test-running the E-Learning schema.

PostgreSQL enforces inline REFERENCES normally, so a script ported from Postgres can lose its foreign keys without anyone noticing. In MySQL always declare them at table level: FOREIGN KEY (teacher_id) REFERENCES account(id), then verify with SHOW CREATE TABLE or information_schema.REFERENTIAL_CONSTRAINTS.

Read in post: SQL exercises on the E-Learning database
InterviewJuniorIn the E-Learning schema, why does the course rating live on user_course rather than on course?

Because a rating is one learner's opinion of one course, an attribute of the N–M relationship, so it belongs on the join table (the enrolment).

The course table can only hold an aggregate (average score, number of ratings) as denormalised data for fast reads. That number has to be recomputed from user_course whenever a new rating arrives.

Read in post: SQL exercises on the E-Learning database
InterviewJuniorWhy is naming a column order asking for trouble?

ORDER is a reserved SQL keyword, so unquoted it is a syntax error and you have to quote it everywhere.

CREATE TABLE, the column list of an INSERT and ORDER BY order all break without quotes (`order` in MySQL, "order" in PostgreSQL), including in ORM-generated SQL. Name it position or sort_order and you never have to remember.

Read in post: SQL exercises on the E-Learning database
InterviewMidHow would you compute each learner's completion percentage in a course, and which traps do you avoid?

Compute the course's lesson total (through chapter → lesson) and each enrolment's DONE count in two separate CTEs, then LEFT JOIN both onto the enrolment table.

The traps:

  • Joining everything and then counting: fan-out.
  • status = 'DONE' in WHERE after a LEFT JOIN: learners who haven't started disappear.
  • Integer division: returns 0.
  • A course with no lessons: divide by zero (use NULLIF).
  • Numerator and denominator filtering hidden lessons differently: the ratio goes past 100%.
Read in post: SQL exercises on the E-Learning database
InterviewMidWould you store statuses (ACTIVE/INACTIVE, START/PROCESSING/DONE) as varchar, ENUM, CHECK or a lookup table?

Not free-form varchar, because it lets bad values in; choose between ENUM, varchar + CHECK and a lookup table depending on how often the list changes.

  • MySQL ENUM is compact and rejects bad values, but adding a value means an ALTER TABLE, and it sorts by declaration order rather than alphabetically.
  • varchar plus CHECK (status IN (...)) is readable and portable (MySQL enforces it since 8.0.16).
  • A lookup table with a foreign key suits lists that change often or need extra attributes (display name, ordering).
  • On the Java side, map it with @Enumerated(EnumType.STRING), never ORDINAL.
Read in post: SQL exercises on the E-Learning database
InterviewMidYou count chapters and lessons per course in one query and COUNT(ch.id) comes out wrong. Why?

Joining course → chapter → lesson produces one row per lesson, so each chapter repeats once per lesson and COUNT(ch.id) actually counts lessons.

Use COUNT(DISTINCT ch.id) for chapters and COUNT(l.id) for lessons, or count each level in its own subquery. That is the fan-out trap; for SUM there is no DISTINCT to rescue you, so aggregating before joining is the safe habit.

Read in post: SQL exercises on the E-Learning database
InterviewSeniorThe progress table user_course_lesson stores both course_id and lesson_id. What is the risk, and how do you handle it?

course_id is redundant (derivable via lesson → chapter → course) and nothing forces the two paths to agree, so the data can go silently wrong.

An application bug can record progress on a course-A lesson against a course-B enrolment, and every report that trusts course_id is wrong. Fixes: validate in the service before writing; join back to cross-check when computing; or put course_id on lesson with a UNIQUE (id, course_id) so a composite foreign key (lesson_id, course_id) is enforced by the database.

The reason to keep course_id here at all is the foreign key to the enrolment (user_id, course_id), which guarantees progress is only recorded for enrolled learners.

Read in post: SQL exercises on the E-Learning database
InterviewSeniorWould you split user, teacher and admin into three tables as the slide's E-Learning schema does?

Usually not: I'd use one account table with a role, plus role-specific profile tables when needed.

Three tables duplicate the login columns, one person can't both learn and teach with one account, usernames can collide across tables, and the login flow looks in several places. One account table with a role (or an account_role table) puts authentication and authorisation in one place; teacher_profile holds teacher-specific data. The cost: a foreign key pointing straight at account can't check "the instructor has the TEACHER role", so either point it at teacher_profile or check it in the service.

Read in post: SQL exercises on the E-Learning database
InterviewSeniorA "my courses" page shows progress for every course. Do you compute it with SQL on every request or store it?

For a read-heavy platform I'd store it, and keep the computing query as the source of truth for reconciliation.

  • Computing: always correct, but every page view recounts, and the cost grows with lessons and learners.
  • Storing: done_lessons and total_lessons on the enrolment, updated in the same transaction when a lesson flips to DONE; O(1) reads.
  • The cost of storing: when a course adds or hides lessons the denominator changes for every learner, and you need a periodic reconciliation job to fix drift.
Read in post: SQL exercises on the E-Learning database
Trade-offSeniorNormalise or denormalise deliberatelyNormalise to avoid update anomalies. Denormalise deliberately (pre-computed totals, price snapshots in orders, read models for reports) for fast reads, as long as you know who's responsible for keeping the copies in sync.

Normalise to avoid update anomalies. Denormalise deliberately (pre-computed totals, price snapshots in orders, read models for reports) for fast reads, as long as you know who's responsible for keeping the copies in sync.

Read in post: SQL practice
Edge caseMidCOUNT(*) after a LEFT JOIN counts an unmatched row as 1When counting across a LEFT JOIN (say, books per publisher), use COUNT(b.bookid), not COUNT(). A publisher with no books still produces one row (with NULLs on the right), so COUNT() counts it as 1.

When counting across a LEFT JOIN (say, books per publisher), use COUNT(b.book_id), not COUNT(*). A publisher with no books still produces one row (with NULLs on the right), so COUNT(*) counts it as 1.

Read in post: SQL practice
Trade-offMidFetching the max and min rows: a window function or two subqueriesTo fetch the rows with the highest and lowest price (keeping ties), two subqueries, price = (SELECT MAX(...)) OR price = (SELECT MIN(...)), also work. The window-function version with RANK() OVER (ORDER BY price ...) (MySQL 8+) scans the table only once.

To fetch the rows with the highest and lowest price (keeping ties), two subqueries, price = (SELECT MAX(...)) OR price = (SELECT MIN(...)), also work. The window-function version with RANK() OVER (ORDER BY price ...) (MySQL 8+) scans the table only once.

Read in post: SQL practice
Edge caseMidWrapping a column in a function makes the predicate non-sargableWriting the condition as duedate < (a constant) instead of DATEDIFF(NOW(), duedate) 7 lets MySQL use an index on duedate. An expression that wraps the column is non-sargable: the database can't look it up in the index and has to evaluate the function on every row.

Writing the condition as due_date < (a constant) instead of DATEDIFF(NOW(), due_date) > 7 lets MySQL use an index on due_date. An expression that wraps the column is non-sargable: the database can't look it up in the index and has to evaluate the function on every row.

Read in post: SQL practice
Edge caseMidA WHERE condition on the right-hand table turns a LEFT JOIN into an INNER JOINThe classic LEFT JOIN trap: putting a condition on the right-hand table (say, the invoice date) in WHERE removes the left-hand rows with no match (their right-hand columns are NULL). The result can never contain a 0. Conditions on the right-hand table belong in ON. Using the range [today, tomorrow) instead of DATE(date

The classic LEFT JOIN trap: putting a condition on the right-hand table (say, the invoice date) in WHERE removes the left-hand rows with no match (their right-hand columns are NULL). The result can never contain a 0. Conditions on the right-hand table belong in ON.

Using the range [today, tomorrow) instead of DATE(date_out) = CURDATE() keeps the index usable (and is correct even if date_out is a DATETIME).

Read in post: SQL practice
InterviewJuniorWHERE vs HAVING?

WHERE filters individual rows before GROUP BY; HAVING filters groups after aggregation.

WHERE can't use aggregate functions, while HAVING can use COUNT(*) >= 2. If a filter can go in WHERE, put it there: fewer rows to group.

Read in post: SQL practice
InterviewJuniorHow do INNER JOIN and LEFT JOIN differ? Give an example that needs a LEFT JOIN.

INNER JOIN keeps only the row pairs that match in both tables; LEFT JOIN keeps every row of the left table, filling the right-hand columns with NULL when there's no match.

You need a LEFT JOIN when the result must include entities that "have nothing": every publisher with its book count, including publishers with no books (count with COUNT(b.book_id) to get 0).

Read in post: SQL practice
InterviewMidWhy does putting a right-table condition in WHERE break a LEFT JOIN?

Because WHERE runs after the join and drops the unmatched rows, so the LEFT JOIN becomes an INNER JOIN.

A LEFT JOIN keeps unmatched left rows by filling the right side with NULLs. A condition such as i.date_out = today evaluates to unknown for NULL, so the row is dropped. To keep unmatched rows (so they count as 0), put the condition in the ON clause.

Read in post: SQL practice
InterviewMidHow do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?

COUNT(*) counts rows, COUNT(col) only counts rows where col isn't NULL, and COUNT(DISTINCT col) counts distinct values.

  • COUNT(*) counts even rows full of NULLs. After a LEFT JOIN, COUNT(right_column) gives 0 for an unmatched row while COUNT(*) gives 1.
  • COUNT(DISTINCT col) is how you counter fan-out (parent rows multiplied by joining down to a child table), for example counting chapters after joining down to lessons.
  • Performance: InnoDB keeps no stored row count, so COUNT(*) on a big table still scans an index.
Read in post: SQL practice
InterviewMidHow do ROW_NUMBER, RANK and DENSE_RANK differ?

All three are window functions that number rows by the ORDER BY inside OVER; they differ in how they treat ties.

For scores 10, 9, 9, 8:

  • ROW_NUMBER gives 1, 2, 3, 4: always distinct. Which of two equal rows comes first is undefined without a tie-breaker.
  • RANK gives 1, 2, 2, 4: ties, then a gap.
  • DENSE_RANK gives 1, 2, 2, 3: ties, no gap.

"Top 5 including ties" uses DENSE_RANK or RANK depending on the reading. "Exactly one latest row per group" uses ROW_NUMBER() OVER (PARTITION BY ...).

Read in post: SQL practice
InterviewSeniorWhen would you deliberately denormalise data?

When an important read has to join many tables or re-aggregate constantly, or when data must be frozen at a point in time.

  • Heavy reads: course progress, comment counts, order totals.
  • Frozen data: prices in an order, the shipping address.
  • The conditions: you know the source of truth, you have a sync mechanism (same transaction, events, a reconciliation job), and the extra write cost or lag is acceptable.
Read in post: SQL practice
InterviewSeniorA report query using DATE(created_at) = CURDATE() keeps getting slower. Why, and how do you fix it?

Wrapping the column in a function makes the predicate non-sargable, so MySQL scans everything; fix it by rewriting the condition as a range on the bare column.

  • Why: MySQL can't use the B-tree index on created_at, so it gets slower as the table grows.
  • Fix: created_at >= CURDATE() AND created_at < CURDATE() + INTERVAL 1 DAY, confirmed with EXPLAIN.
  • Alternatives: a functional index (MySQL 8.0.13+) or an indexed generated column. Rewriting the condition is still the simplest.
Read in post: SQL practice
Edge caseMidRecords are only shallowly immutableRecords are only shallowly immutable: fields can't be reassigned, but the objects inside can still change. A record holding a mutable List still needs List.copyOf in its compact constructor.

Records are only shallowly immutable: fields can't be reassigned, but the objects inside can still change. A record holding a mutable List still needs List.copyOf in its compact constructor.

Read in post: Object-oriented programming
Edge caseJuniorOverriding equals without hashCode breaks HashMap and HashSetIf you override equals, you must override hashCode: objects that are equals must have the same hashCode. The slides leave this out, but it's a classic interview question. Break it and you put an object into a HashSet, then contains returns false. Why? HashMap uses hashCode to find the bucket (a slot) first, then equals

If you override equals, you must override hashCode: objects that are equals must have the same hashCode. The slides leave this out, but it's a classic interview question. Break it and you put an object into a HashSet, then contains returns false.

public final class Point {
    private final int x, y;
    public Point(int x, int y) { this.x = x; this.y = y; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Point p)) return false;   // pattern matching; also handles null
        return x == p.x && y == p.y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }
    @Override public String toString() { return "Point(" + x + ", " + y + ")"; }
}

Why? HashMap uses hashCode to find the bucket (a slot) first, then equals to compare within it. Two equal objects with different hashes land in different buckets and are never compared. Records generate all three methods correctly for you.

Read in post: Object-oriented programming
Edge caseJuniorA final reference doesn't make the object immutablefinal locks the reference, not the object it points to. If the contents must not change either, use List.copyOf(...), List.of(...) (calling add throws UnsupportedOperationException), or a record with defensive copies.

final locks the reference, not the object it points to.

private final List<String> tags = new ArrayList<>();

tags.add("vip");               // fine: the ArrayList itself is still mutable
// tags = new ArrayList<>();   // compile error: the reference can't be reassigned

If the contents must not change either, use List.copyOf(...), List.of(...) (calling add throws UnsupportedOperationException), or a record with defensive copies.

Read in post: Object-oriented programming
TILSeniorPrimitive/String static final constants get inlined into other classesA static final field of a primitive type or String, initialized with a constant expression (static final int MAX = 10;), is a compile-time constant (its value is known at compile time). The compiler copies the value 10 straight into the bytecode of every class that uses Config.MAX (this is called inlining). The consequ

A static final field of a primitive type or String, initialized with a constant expression (static final int MAX = 10;), is a compile-time constant (its value is known at compile time). The compiler copies the value 10 straight into the bytecode of every class that uses Config.MAX (this is called inlining).

The consequence: change it to MAX = 20, rebuild only Config, and other classes still see 10 until they are recompiled too. In a shared library, don't expose values that may change as public constants; use a method (static int max()) or a non-constant type (Integer, a value loaded from config) so the value is read at runtime.

Read in post: Object-oriented programming
InterviewJuniorCan you still add elements to a final List<String> items field?

Yes. final only forbids reassigning the reference; the underlying ArrayList is still mutable.

It's items = new ArrayList<>() that won't compile. If the contents must not change, assign an immutable list (List.copyOf, List.of) and never hand out a mutable one.

Read in post: Object-oriented programming
InterviewJuniorWhat's the difference between == and equals?

== compares values for primitives and identity (is it the same object?) for references; equals compares content when the class overrides it.

  • Classes that override equals: String, Integer, records. Object's default is just ==.
  • Compare strings with equals ("a" == new String("a") is false); enums can use == because each constant is unique.
  • Write "ACTIVE".equals(status) or Objects.equals(a, b) to avoid an NPE when a value may be null.
Read in post: Object-oriented programming
InterviewMidWhy must you override hashCode when you override equals?

Because the contract says equal objects must have equal hash codes, and HashMap/HashSet find the bucket by hash before calling equals.

With different hashes, the objects land in different buckets, and contains/get give wrong answers even though the objects are "equal".

Read in post: Object-oriented programming
InterviewMidHow do you write an immutable class, and why are immutable objects useful?

private final fields, no setters, a final class, and defensive copies of mutable fields on the way in and out; or use a record (still copying collections).

Benefits: thread safety without locks, safe map keys, easier reasoning, cacheability, and free sharing.

Read in post: Object-oriented programming
InterviewMidHow does a record differ from a hand-written immutable class? Is a record fully immutable?

A record generates everything an immutable class needs, but it's only shallowly immutable: a mutable List component can still be modified.

  • A record (Java 16) generates private final fields, a canonical constructor, accessors, and equals/hashCode/toString over all components; the class is implicitly final and can't declare extra instance fields.
  • Validation and List.copyOf go in the compact constructor.
  • Records don't suit JPA entities (no-arg constructor, proxies, mutable fields), but they're great for DTOs, value objects and map keys.
Read in post: Object-oriented programming
InterviewSeniorYou change a public static final int in a shared library and redeploy the library, but another service still uses the old value. Why?

Because it's a compile-time constant: javac copied the value straight into the service's bytecode, with no reference to the library field left.

Swapping the library jar without recompiling the service leaves the old value in place. To avoid it, don't expose values that may change as public constants; use a method like static int maxRetry(), read it from config, or use a non-constant type (Integer.valueOf(3)). For values that truly never change (Math.PI, HTTP status codes), inlining is fine.

Read in post: Object-oriented programming
Edge caseJuniorCommon misconceptions about Java primitive typesA few things the slides get slightly wrong: boolean is not 1 bit. The JVM specification leaves its size open. HotSpot uses one byte per element of a boolean[] and treats a boolean on the stack as an int. Defaults exist only for fields and array elements. Local variables have no default: reading one before assigning it

A few things the slides get slightly wrong:

  • boolean is not 1 bit. The JVM specification leaves its size open. HotSpot uses one byte per element of a boolean[] and treats a boolean on the stack as an int.
  • Defaults exist only for fields and array elements. Local variables have no default: reading one before assigning it is a compile error.
  • '\u0000' is the NUL character, not an "empty character". Java has no '' literal.
  • float/double are precise to 6–7 / 15 significant digits (counted from the first non-zero digit), not "decimal places": 0.123456789f becomes 0.12345679, 1234.56789f becomes 1234.5679.
  • A char is not always one user-visible character. The emoji 😀 takes two chars (a surrogate pair — two UTF-16 units joined together), so "😀".length() == 2.
Read in post: Java basics
Edge caseJuniorUnboxing a null wrapper throws NullPointerExceptionMap<String, Integer stock = new HashMap<(); int q = stock.get("x"); throws NullPointerException: get returns null and the compiler inserted .intValue(). Since Java 14 the message says exactly that: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null. The fix: get

Map<String, Integer> stock = new HashMap<>(); int q = stock.get("x"); throws NullPointerException: get returns null and the compiler inserted .intValue(). Since Java 14 the message says exactly that: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null.

The fix: getOrDefault("x", 0), or keep the Integer and check for null. The Integer cache and the other wrapper traps are in wrapper classes, BigDecimal and String.

Read in post: Java basics
Trade-offJuniorWhen to use varvar is still static typing; you just don't spell the type out. Use it when the right-hand side makes the type obvious (var users = new ArrayList<User()). Avoid it when the right-hand side is a method call whose return type the reader can't guess.

var is still static typing; you just don't spell the type out. Use it when the right-hand side makes the type obvious (var users = new ArrayList<User>()). Avoid it when the right-hand side is a method call whose return type the reader can't guess.

Read in post: Java basics
Edge caseJuniorNarrowing casts and double money lose data silentlyIn production, use Math.toIntExact wherever a long is narrowed to an int (ids, sizes, time units). For money, don't use double: use BigDecimal or store integers in the smallest currency unit (cents, đồng). 0.1 + 0.2 is 0.30000000000000004.

In production, use Math.toIntExact wherever a long is narrowed to an int (ids, sizes, time units). For money, don't use double: use BigDecimal or store integers in the smallest currency unit (cents, đồng). 0.1 + 0.2 is 0.30000000000000004.

Read in post: Java basics
Edge caseJuniorAn integer literal with a leading zero is octalint code = 010; prints 8, not 10, because a literal starting with 0 is base 8. And int month = 09; doesn't compile at all, since 8 and 9 aren't octal digits. This bites people who type months (08), postal codes or branch codes as numbers. Values like these are identifiers, so store them as String: the leading zero matt

int code = 010; prints 8, not 10, because a literal starting with 0 is base 8. And int month = 09; doesn't compile at all, since 8 and 9 aren't octal digits.

This bites people who type months (08), postal codes or branch codes as numbers. Values like these are identifiers, so store them as String: the leading zero matters and you never do arithmetic on them.

Read in post: Java basics
Trade-offMidGreedy vs dynamic programming for making changeGreedy (take as many of the largest note as possible, then move down) is optimal for 500, 200, 100, 20, 10, 5, 2, 1 because this is a "canonical" coin system. For arbitrary denominations, say {1, 3, 4} and an amount of 6, greedy picks 4+1+1 (3 coins) while the optimum is 3+3 (2 coins). Then you need dynamic programming

Greedy (take as many of the largest note as possible, then move down) is optimal for 500, 200, 100, 20, 10, 5, 2, 1 because this is a "canonical" coin system. For arbitrary denominations, say {1, 3, 4} and an amount of 6, greedy picks 4+1+1 (3 coins) while the optimum is 3+3 (2 coins). Then you need dynamic programming.

Read in post: Java basics
InterviewJuniorWhat are Java's 8 primitive types? Is String one of them?

byte, short, int, long, float, double, char, boolean. String is not: it is an immutable class (a reference type).

The compiler just gives String special support for "..." literals and the + operator.

Read in post: Java basics
InterviewJuniorWhich of these are valid identifiers: 1abc, _123, $if, ab-c, if?

Valid: _123 and $if. Invalid: 1abc (starts with a digit), ab-c (- is an operator), if (a keyword).

The rules: only letters, digits, _ and $; no leading digit; not a keyword or true/false/null; a lone _ has been a keyword since Java 9. Legal isn't the same as conventional: variables use camelCase, constants UPPER_SNAKE_CASE.

Read in post: Java basics
InterviewJuniorWhat are wrapper classes for? What is autoboxing?

Wrappers turn a primitive into an object so it works with collections and generics, can be null, and has utility methods. Autoboxing is the compiler converting int to Integer for you.

Autoboxing calls Integer.valueOf; unboxing is the reverse, via intValue(). The traps: unboxing null throws NullPointerException, and comparing two wrappers with == compares references.

Read in post: Java basics
InterviewJuniorDo local variables have default values?

No. Only object fields and array elements get defaults (0, false, null...).

Reading a local variable before assigning it is a compile error ("variable might not have been initialized"). That's how the compiler prevents C-style use of garbage values.

Read in post: Java basics
InterviewJuniorWhat is the type of 'a' + 1? Why does c = c + 1 fail for a char c while c += 1 compiles?

'a' + 1 is an int (98), because a char is promoted to int before arithmetic. c += 1 includes an implicit cast back to char; c = c + 1 doesn't.

byte and short are promoted the same way. Assigning an int to a char is a narrowing conversion that needs c = (char) (c + 1). For the same reason, 'A' + 'B' prints 131 rather than AB.

Read in post: Java basics
InterviewMidWhat is the difference between implicit and explicit casting? Give an example of data loss.

Implicit (widening) casts go from a narrower to a wider type automatically. Explicit (narrowing) casts go the other way, need (type), and can lose data.

Examples: (byte) 200 == -56 (only the low 8 bits survive) and (int) 3.99 == 3 (truncation). Even the implicit long → float conversion can lose precision.

Read in post: Java basics
InterviewMidWhy is 0.1 + 0.2 != 0.3? How do you handle money?

Because double is IEEE 754 binary floating point, and 0.1 has no exact binary representation. For money, use BigDecimal or a long in the smallest unit.

Create BigDecimal from a String with an explicit RoundingMode. With a long, store cents or đồng.

Read in post: Java basics
InterviewMidDoes var make Java dynamically typed?

No. var is compile-time type inference for local variables; the type is still fixed.

var list = new ArrayList<String>() has the type ArrayList<String>, and assigning list = 5 later is a compile error. var can't be used for fields, method parameters or return types, and it needs an initializer (no var x; or var x = null;).

Read in post: Java basics
InterviewMidWhere do primitive variables and objects live in memory?

Local variables, primitive or reference, live in the running method's stack frame. Objects, arrays included, live on the heap.

A reference variable only holds the object's address. A primitive that is a field of an object lives inside that object, so on the heap. One nuance: the JIT performs escape analysis (checking whether an object "escapes" the method), so an object that never escapes can be broken into scalar values and never allocated on the heap.

Read in post: Java basics
InterviewSeniorDoes integer overflow throw an exception? How do you guard against it in production code?

No. Integers are stored in two's complement, so overflow silently wraps: Integer.MAX_VALUE + 1 == Integer.MIN_VALUE.

Guards:

  • Math.addExact, multiplyExact and toIntExact throw ArithmeticException on overflow.
  • Use long for money, counters and timestamps; BigInteger when there's no known bound.
  • Classic bug: the binary-search midpoint (lo + hi) / 2 overflows. Write lo + (hi - lo) / 2 or (lo + hi) >>> 1.
Read in post: Java basics
InterviewSeniorWhy is there no List<int>, and how expensive is boxing with large data?

Generics are erased to Object (type erasure), and primitives aren't objects. With large data, boxing costs 4–5 times the memory of a primitive array.

A List<Integer> with a million elements is an array of references (4–8 bytes each) plus a million Integer objects (around 16 bytes each) scattered across the heap. An int[] is just 4 contiguous MB. The result: more memory, many more cache misses, extra GC pressure.

For large numeric data, use primitive arrays, IntStream, or primitive-specialised collection libraries (fastutil, Eclipse Collections). Project Valhalla aims to allow generics over value types.

Read in post: Java basics
Trade-offMidCopying a file: byte by byte, buffered, transferTo or Files.copyCopying a 20 MB file on JDK 21 (my machine, only the ranking matters): Unbuffered byte by byte is for demos only. Buffered but still calling read() per byte still pays one method call per byte. Stream to stream (say, an HTTP request body into a file): in.transferTo(out). File to file: Files.copy. The JDK and the OS can

Copying a 20 MB file on JDK 21 (my machine, only the ranking matters):

Approach Time
FileInputStream.read() one byte at a time, no buffer ~37 seconds
Wrapped in BufferedInputStream/BufferedOutputStream, still one byte at a time ~150 ms
Reading into a byte[8192] yourself ~15 ms
in.transferTo(out) (Java 9) ~10 ms
Files.copy(src, dst) ~4 ms
  • Unbuffered byte by byte is for demos only. Buffered but still calling read() per byte still pays one method call per byte.
  • Stream to stream (say, an HTTP request body into a file): in.transferTo(out).
  • File to file: Files.copy. The JDK and the OS can copy inside the kernel, so the data never passes through the Java heap.
Read in post: Java I/O
Edge caseJuniorInputStream.available() is not the file sizeavailable() returns an estimate of how many bytes can be read right now without blocking (without waiting), not the total size. On a local file it often equals the remaining bytes, so wrong code still "works" on a dev machine. It's an int: files over 2 GB are capped at Integer.MAXVALUE. After a partial read it only rep

available() returns an estimate of how many bytes can be read right now without blocking (without waiting), not the total size.

  • On a local file it often equals the remaining bytes, so wrong code still "works" on a dev machine.
  • It's an int: files over 2 GB are capped at Integer.MAX_VALUE. After a partial read it only reports what's left.
  • Sockets, System.in, compressed streams, HTTP bodies: usually 0, or only what has reached the buffer.

File size: Files.size(path). Whole stream: in.readAllBytes() (Java 9) or transferTo; never new byte[in.available()].

Read in post: Java I/O
Edge caseSeniorDeserializing untrusted data can lead to remote code executionObjectInputStream.readObject() instantiates any serializable class on the classpath named in the data and runs hooks such as their readObject methods. Attackers chain classes that already exist in libraries (Commons Collections, Spring...) into a gadget chain (a sequence of abused classes) that runs arbitrary commands.

ObjectInputStream.readObject() instantiates any serializable class on the classpath named in the data and runs hooks such as their readObject methods. Attackers chain classes that already exist in libraries (Commons Collections, Spring...) into a gadget chain (a sequence of abused classes) that runs arbitrary commands. The (User) cast happens only after the object graph is built, so it stops nothing. This was behind several critical vulnerabilities (WebLogic, Jenkins, JBoss around 2015–2016).

  • Never deserialize data from an untrusted source (requests, cookies, an open message queue) with Java serialization.
  • If you must: an allow-list with ObjectInputFilter (JEP 290, Java 9), e.g. ObjectInputFilter.Config.createFilter("com.myapp.dto.*;java.base/*;!*"), or a JVM-wide filter via -Djdk.serialFilter=....
Read in post: Java I/O
Trade-offSeniorJava serialization vs JSON/ProtobufDefault: JSON for APIs, caches, messages. Protobuf/Avro when you need a strict schema, high throughput, many services (gRPC, Kafka). Redis cache in Spring: configure GenericJackson2JsonRedisSerializer (or an equivalent JSON serializer) instead of the default JDK serializer. Java serialization only when forced to stay c
Java serialization JSON (Jackson) Protobuf/Avro
Human-readable No Yes No
Readable from other languages Java only Every language Every language (with the schema)
Class evolution Brittle (serialVersionUID, renaming a package breaks it) Flexible: ignores unknown fields, has defaults Clear rules based on field numbers
Security High risk (gadget chains) Safe with polymorphic default typing turned off Safe
Size, speed Large, slow Medium Small, fast
  • Default: JSON for APIs, caches, messages.
  • Protobuf/Avro when you need a strict schema, high throughput, many services (gRPC, Kafka).
  • Redis cache in Spring: configure GenericJackson2JsonRedisSerializer (or an equivalent JSON serializer) instead of the default JDK serializer.
  • Java serialization only when forced to stay compatible with a legacy system, and always with an ObjectInputFilter.
Read in post: Java I/O
TILSeniorRecords are deserialized through their canonical constructorAn ordinary class is deserialized without running its constructor, so every check in the constructor is skipped: tweak a few bytes and you get amount = -5 even though the constructor forbids negatives. Records (Java 16) are different: the JVM reads the component values and then calls the canonical constructor. A compac

An ordinary class is deserialized without running its constructor, so every check in the constructor is skipped: tweak a few bytes and you get amount = -5 even though the constructor forbids negatives.

Records (Java 16) are different: the JVM reads the component values and then calls the canonical constructor. A compact constructor like record Money(long amount, String currency) { Money { if (amount < 0) throw ... } } still runs, and tampered data throws InvalidObjectException. If you're stuck with Java serialization, records are safer than ordinary classes.

Read in post: Java I/O
InterviewJuniorWhat's the difference between byte streams and character streams, and when do you use each?

Byte streams read and write raw bytes for binary data; character streams work with decoded characters and are meant for text.

Byte streams (InputStream/OutputStream) suit images, audio, zip files. Character streams (Reader/Writer) decode through a charset. InputStreamReader/OutputStreamWriter bridge the two, and you should always pass an explicit charset (StandardCharsets.UTF_8).

Read in post: Java I/O
InterviewJuniorWhat is a marker interface? Does Serializable have any methods?

A marker interface has no methods; it just tags a class with a capability. Serializable has none.

The JVM or a library checks the tag at runtime: ObjectOutputStream checks instanceof Serializable and throws NotSerializableException if it's missing. Cloneable works the same way. Today annotations usually serve this purpose, because they can carry extra information.

Read in post: Java I/O
InterviewMidWhy is copying a file with byte-by-byte read() slow? How does BufferedInputStream help? Can available() tell you the file size?

Each read() is a system call; a buffer fetches 8 KB at a time to cut the number of calls. available() does not give you the file size.

A 20 MB file costs tens of millions of switches into the kernel. BufferedInputStream reads 8 KB blocks into RAM and serves later read() calls from there. In real code, use in.transferTo(out) or Files.copy. available() is only an estimate of the bytes readable without blocking; it's an int capped at 2 GB and is usually 0 for sockets. Get the file size with Files.size.

Read in post: Java I/O
InterviewMidWhat are serialVersionUID and transient for?

serialVersionUID is a class's version number, checked for compatibility on read; transient keeps a field out of the serialized data.

If the number in the data differs from the current class's, you get InvalidClassException. If you don't declare it, the JVM derives one from the class structure, so a small change breaks compatibility; declare it explicitly. A transient field (password, cache, connection) reads back with its default value, and its initializer doesn't run.

Read in post: Java I/O
InterviewMidWhy are java.io classes wrapped in so many layers?

It's the Decorator pattern: each layer adds exactly one capability while keeping the same type (InputStream or Reader).

FileInputStream reads bytes from a file, BufferedInputStream adds a buffer, InputStreamReader adds charset decoding, BufferedReader adds readLine. That lets you combine them freely (buffering for a socket, GZIPInputStream for a compressed HTTP body) without a dedicated class for every combination. Closing the outermost layer is enough; it closes the chain inward.

Read in post: Java I/O
InterviewSeniorWhy is Java serialization considered a security risk, and what do you use instead?

Because readObject() instantiates any class on the classpath named in the data and runs its hooks before your cast, so a gadget chain can achieve remote code execution. Use JSON or Protobuf/Avro instead.

On top of that, the format is Java-only, brittle when classes change, and bulky. With Jackson, keep polymorphic default typing off. If you're stuck with it, set an allow-list with ObjectInputFilter (JEP 290), and prefer records, which go through the canonical constructor on deserialization.

Read in post: Java I/O
InterviewSeniorHow do you correctly measure how long a file copy (or any piece of code) takes?

Use System.nanoTime(), run many iterations with a warm-up, and use JMH for micro-benchmarks.

currentTimeMillis() can jump when the clock is adjusted; nanoTime is a monotonic clock. Discard the first runs so the JIT can compile the code; for I/O, also mind the OS page cache (a second read never touches the disk). Measure on hardware and a filesystem like production's. JMH handles warm-up, forks the JVM and stops the JIT from eliminating "unused" code. Report a distribution (p50, p99), not just one average.

Read in post: Java I/O
Edge caseJuniorJava arrays always live on the heap, not the stackThe slides say a static array is "allocated at compile time" and "lives on the stack". That's true for local arrays in C/C++, but not in Java. Every Java array is an object, created at runtime with new, and it lives on the heap. Only the reference variable scores sits on the stack. The length can be a variable (new int

The slides say a static array is "allocated at compile time" and "lives on the stack". That's true for local arrays in C/C++, but not in Java.

  • Every Java array is an object, created at runtime with new, and it lives on the heap. Only the reference variable scores sits on the stack.
  • The length can be a variable (new int[n]); it just can't change after creation.
  • The JIT may optimize small arrays away through escape analysis, but that's a JVM detail, not language semantics.
  • The correct syntax is int[] nums = new int[10];, not int nums = new int[10].
Read in post: Linear data structures
Trade-offJuniorArray/ArrayList vs linked list
Criterion Array / ArrayList Linked list
Memory Contiguous; a raw array has a fixed size Scattered, grows one node at a time
Access by index O(1), direct address math O(n), must traverse
Insert/delete in the middle O(n), elements shift O(1) once you have the node, but finding it is O(n)
Insert/delete at the front O(n) O(1)
Append O(1) amortized O(1) with a tail
Cache behavior Very CPU-cache friendly Poor, nodes can be anywhere
Overhead per element 1 reference (4 bytes with compressed oops) 1 node object: header + 2–3 references (~24 bytes)
Good for Read-heavy work, random access, known size Lots of inserts/removals at the ends, unknown size
Read in post: Linear data structures
TILMidCache locality makes ArrayList usually faster than LinkedList, even for middle insertsThe CPU doesn't read RAM byte by byte; it pulls in whole cache lines (usually 64 bytes). Scanning an int[]: one fetch brings in 16 elements, and the hardware prefetcher can predict the next address. Walking a linked list: every step chases a pointer to some other place (pointer chasing), which tends to miss the cache.

The CPU doesn't read RAM byte by byte; it pulls in whole cache lines (usually 64 bytes).

  • Scanning an int[]: one fetch brings in 16 elements, and the hardware prefetcher can predict the next address.
  • Walking a linked list: every step chases a pointer to some other place (pointer chasing), which tends to miss the cache. One trip to main memory costs roughly 100 ns, hundreds of times more than an addition.
  • So even for middle inserts at moderate sizes, ArrayList is often still faster than LinkedList: System.arraycopy shifts one contiguous block very quickly, while LinkedList spends most of its time just getting to the insertion point.

Rule of thumb: default to ArrayList. Need a stack or queue? Use ArrayDeque. LinkedList is rarely the best choice.

Read in post: Linear data structures
Edge caseJuniorInserting into a doubly linked list must update all four referencesA singly list insert touches two references. A doubly list insert touches four: node.prev = pred; node.next = succ; pred.next = node; succ.prev = node;. The classic bug: forgetting succ.prev = node. A forward walk looks fine, but a backward walk (or a get that starts from tail) skips the new node, and the next delete c

A singly list insert touches two references. A doubly list insert touches four: node.prev = pred; node.next = succ; pred.next = node; succ.prev = node;.

  • The classic bug: forgetting succ.prev = node. A forward walk looks fine, but a backward walk (or a get that starts from tail) skips the new node, and the next delete corrupts the list.
  • The safe order: capture pred and succ in local variables, set the new node's two references, and only then fix pred.next and succ.prev.
  • Delete is the same story: fix both pred.next and succ.prev.
  • Quick self-check: after every operation, a forward walk and a backward walk must yield the same sequence (reversed).
Read in post: Linear data structures
Trade-offMidSentinel nodes vs null checks in every operationSentinels: you pay for one or two permanent nodes (a few dozen bytes per list) and get insert/delete code with a single path: no if (head == null), no if (node == tail). Fewer branches mean fewer bugs and code that's easier to prove correct. A good fit when you build the structure yourself: an LRU cache, LeetCode's "De
  • Sentinels: you pay for one or two permanent nodes (a few dozen bytes per list) and get insert/delete code with a single path: no if (head == null), no if (node == tail). Fewer branches mean fewer bugs and code that's easier to prove correct. A good fit when you build the structure yourself: an LRU cache, LeetCode's "Design Linked List", intrusive lists in an OS kernel.
  • No sentinels (null ends): no extra nodes, but every operation must handle the empty list, the first element and the last element separately. java.util.LinkedList takes this route: first/last can be null, and linkFirst, linkLast and unlink all branch on it.
  • With sentinels, a traversal stops at cur != tail, not cur != null; forget that and you'll print the sentinel's dummy value.
Read in post: Linear data structures
TILMidjava.util.LinkedList has no sentinels, but get(i) also starts from the closer endjava.util.LinkedList keeps first and last, which may be null (no dummy nodes). Its internal node(int index) checks index < (size 1): if true it walks forward from first, otherwise backward from last. So list.get(size - 1) is O(1), but a get in the middle still costs about n/2 steps. Looping over a LinkedList with for (

java.util.LinkedList keeps first and last, which may be null (no dummy nodes). Its internal node(int index) checks index < (size >> 1): if true it walks forward from first, otherwise backward from last.

So list.get(size - 1) is O(1), but a get in the middle still costs about n/2 steps. Looping over a LinkedList with for (int i...) list.get(i) is O(n²); use for-each or an Iterator.

Read in post: Linear data structures
Trade-offJunioroffer/poll/peek vs add/remove/element on a QueueIn Java, Queue is an interface, not a class. Each operation comes in two flavors: For bounded queues (e.g. ArrayBlockingQueue), offer is the safer choice.

In Java, Queue is an interface, not a class. Each operation comes in two flavors:

Throws on failure Returns a special value
Insert add(e) offer(e) → false
Remove remove() poll() → null
Examine element() peek() → null

For bounded queues (e.g. ArrayBlockingQueue), offer is the safer choice.

Read in post: Linear data structures
Edge caseMidReversing a string char by char breaks emoji (surrogate pairs)Reversing a string char by char (e.g. pushing each char onto a stack and popping them) breaks characters outside the BMP such as emoji (surrogate pairs), whereas StringBuilder.reverse() handles them correctly.

Reversing a string char by char (e.g. pushing each char onto a stack and popping them) breaks characters outside the BMP such as emoji (surrogate pairs), whereas StringBuilder.reverse() handles them correctly.

Read in post: Linear data structures
InterviewJuniorWhat's the difference between an array and an ArrayList?

An array has a fixed length and can hold primitives; an ArrayList is a dynamic array that grows on its own and only holds objects.

ArrayList wraps an Object[], so int gets boxed to Integer. In return it is generic and comes with lots of convenience methods.

Read in post: Linear data structures
InterviewJuniorHow do a stack and a queue differ? Give a use case for each.

A stack is LIFO and you only work at the top; a queue is FIFO, adding at the rear and removing at the front.

Stack: call stacks, undo, bracket matching, DFS. Queue: BFS, job queues, producer/consumer buffers.

Read in post: Linear data structures
InterviewJuniorWhy is reading the i-th element O(1) for an array but O(n) for a linked list?

An array is contiguous, so the address is just base + i * size; a linked list has no address formula.

With a linked list you follow next from head through i nodes.

Read in post: Linear data structures
InterviewJuniorWhat's the difference between a singly and a doubly linked list?

A singly linked node only has next; a doubly linked node also has prev, so you can walk both ways and removing a node you hold is O(1).

A singly list only walks forward, and to remove a node you need the node before it; removing the last element is still O(n) even with a tail. A doubly list removes the last one in O(1), at the price of one extra reference per node. java.util.LinkedList is doubly linked.

Read in post: Linear data structures
InterviewMidWhat's the difference between offer/poll/peek and add/remove/element?

offer/poll/peek report failure through the return value (false/null); add/remove/element throw.

The exceptions are IllegalStateException (full) and NoSuchElementException (empty). Use the first group when a bounded queue or an empty queue is a normal situation.

Read in post: Linear data structures
InterviewMidHow do you build a queue out of two stacks, and what does it cost?

Use an in stack to receive and an out stack to hand out; when out is empty, pour all of in into out. The amortized cost is O(1) per operation.

offer pushes onto in. When you poll and out is empty, pour everything from in into out; pouring reverses the order, so the top of out is the oldest element. A single poll can cost O(n), but every element moves from in to out exactly once. The question checks that you understand LIFO versus FIFO and amortized analysis.

Read in post: Linear data structures
InterviewMidWhat is a sentinel (dummy) node and why does it simplify linked list code?

A sentinel is a fake node that holds no real data and always exists, so every real node has a non-null prev and next and insert/delete become a single code path.

Insert is pred.next = node; succ.prev = node, delete is pred.next = succ; succ.prev = pred. There are no separate branches for the empty list, the first element or the last element. The cost is one or two extra nodes and remembering to stop traversals at cur != tail. A real-world use: a hand-written LRU cache built from a HashMap plus a doubly linked list with sentinels.

Read in post: Linear data structures
InterviewSeniorWhy can cache locality matter more than Big-O?

Because Big-O ignores constants, and a cache miss costs around 100 ns versus about 1 ns for an L1 hit.

Scanning a contiguous array uses whole 64-byte cache lines and the prefetcher; walking a linked list is pointer chasing where each step can miss. That's why ArrayList's O(n) middle insert (one contiguous arraycopy) often beats the O(n) walk to the insertion point in a LinkedList, even though both are O(n).

Read in post: Linear data structures
Edge caseMidCron expressions aren't portable between Unix, Spring and Quartz1. The same number can mean two different days. 5L in Spring is "last Friday of the month"; in Quartz it's "last Thursday". Use names (MON, FRI, SAT) so the dialect doesn't matter. 2. Copying between systems means translating. crontab.guru only understands 5-field Unix syntax; paste a 6-field Spring expression in and y
  1. The same number can mean two different days. 5L in Spring is "last Friday of the month"; in Quartz it's "last Thursday". Use names (MON, FRI, SAT) so the dialect doesn't matter.
  2. Copying between systems means translating. crontab.guru only understands 5-field Unix syntax; paste a 6-field Spring expression in and you get the wrong answer. Cronmaker produces Quartz syntax.
  3. Day and weekday combine differently. Spring's 0 0 0 13 * FRI is "midnight on Friday the 13th" (AND); Unix's 0 0 13 * 5 is "every 13th and every Friday" (OR).
Read in post: Cron jobs
TILnW in cron never crosses into another monthnW (Spring 5.3+, Quartz) is the weekday (Mon-Fri) nearest to day n. For 10W: The 10th is a weekday: run on the 10th. The 10th is a Saturday: run on Friday the 9th. The 10th is a Sunday: run on Monday the 11th. Edge case: for 1W, if the 1st is a Saturday it runs on Monday the 3rd, not on the last day of the previous mon

nW (Spring 5.3+, Quartz) is the weekday (Mon-Fri) nearest to day n. For 10W:

  • The 10th is a weekday: run on the 10th.
  • The 10th is a Saturday: run on Friday the 9th.
  • The 10th is a Sunday: run on Monday the 11th.
  • Edge case: for 1W, if the 1st is a Saturday it runs on Monday the 3rd, not on the last day of the previous month.
Read in post: Cron jobs
TILA bare L in day-of-week: an error in Spring, Saturday in QuartzA bare L in the day-of-week field is invalid in Spring ("No day-of-week before 'L'"). In Quartz it means Saturday. In Spring you name the weekday, e.g. FRIL or 5L for the last Friday of the month.

A bare L in the day-of-week field is invalid in Spring ("No day-of-week before 'L'"). In Quartz it means Saturday. In Spring you name the weekday, e.g. FRIL or 5L for the last Friday of the month.

Read in post: Cron jobs
Edge caseMidSpring cron has no year field, so Quartz-style expressions failA few examples in the course material don't work in Spring: 0 0 0 1 ? 2024 and 0 0 0 1 1 ? 2024 have a year field (Quartz syntax): Spring fails with "Cron expression must consist of 6 fields". If you need a year restriction, check the year in code. 0 0 0 1-5 ? has 7 fields and is wrong in both Spring and Quartz. The co

A few examples in the course material don't work in Spring:

  • 0 0 0 1 * ? 2024 and 0 0 0 1 1 ? 2024 have a year field (Quartz syntax): Spring fails with "Cron expression must consist of 6 fields". If you need a year restriction, check the year in code.
  • 0 0 0 1-5 * * ? has 7 fields and is wrong in both Spring and Quartz. The correct form is 0 0 0 1-5 * ? (or 0 0 0 1-5 * * in Spring).
  • 0 0 0 10W * * works in Spring but is invalid in Quartz, which requires ? in the day-of-week field once day-of-month is set.
  • The examples that use numbers for weekdays (2#2, 1#3, 6#3, 5L) only mean what they say in Spring; in Quartz they're off by one day.
Read in post: Cron jobs
Edge caseMidfixedRate runs don't overlap with the default schedulerThe course material says fixedRate reruns "regardless of whether the previous run has finished". With the default scheduler that's wrong: Spring Boot uses ThreadPoolTaskScheduler (backed by ScheduledThreadPoolExecutor) by default. Executions of the same fixed-rate task never run concurrently: if a run takes longer than

The course material says fixedRate reruns "regardless of whether the previous run has finished". With the default scheduler that's wrong:

  • Spring Boot uses ThreadPoolTaskScheduler (backed by ScheduledThreadPoolExecutor) by default. Executions of the same fixed-rate task never run concurrently: if a run takes longer than the period, the next one just starts late, right after the previous one finishes.
  • For cron, Spring computes the next fire time after the current run finishes, so fire times missed while the job was running are skipped, not caught up.

Overlap only happens when you cause it:

  • The method is also @Async: the scheduler hands the work to another executor and considers it "done".
  • Virtual threads are on (spring.threads.virtual.enabled=true, Boot 3.2+): Boot switches to SimpleAsyncTaskScheduler, which runs each fixed-rate or cron execution on a new thread, so runs can overlap. fixedDelay stays sequential.
Read in post: Cron jobs
Edge caseMidAll @Scheduled jobs share one thread by defaultBy default spring.task.scheduling.pool.size=1: every @Scheduled job shares one thread. A cleanup job that takes 40 minutes makes the every-minute OTP expiry job wait 40 minutes. Heavy jobs should hand work off to a dedicated, bounded executor; the scheduler only keeps time.

By default spring.task.scheduling.pool.size=1: every @Scheduled job shares one thread. A cleanup job that takes 40 minutes makes the every-minute OTP expiry job wait 40 minutes.

spring:
  task:
    scheduling:
      pool:
        size: 4
      thread-name-prefix: sched-
      shutdown:
        await-termination: true
        await-termination-period: 60s

Heavy jobs should hand work off to a dedicated, bounded executor; the scheduler only keeps time.

Read in post: Cron jobs
Edge caseMidExceptions in @Scheduled are logged and swallowed, so jobs fail silentlyFor repeating tasks, the default ErrorHandler logs and swallows exceptions; the next run still happens. Without metrics and alerts, the job can fail silently for weeks. Catch errors at the job boundary, log with context and emit metrics (Micrometer: since Spring 6.1, @Scheduled methods get observations automatically).

For repeating tasks, the default ErrorHandler logs and swallows exceptions; the next run still happens. Without metrics and alerts, the job can fail silently for weeks. Catch errors at the job boundary, log with context and emit metrics (Micrometer: since Spring 6.1, @Scheduled methods get observations automatically).

Read in post: Cron jobs
Edge caseSenior@Scheduled runs on every instance, so 3 pods means 3 runs@Scheduled knows nothing about clusters. With 3 pods the job runs 3 times at once: emails go out three times, reconciliation writes duplicates, deletes fight each other for locks. You need a distributed lock (ShedLock) or a cluster-aware scheduler, and the job still has to be idempotent.

@Scheduled knows nothing about clusters. With 3 pods the job runs 3 times at once: emails go out three times, reconciliation writes duplicates, deletes fight each other for locks. You need a distributed lock (ShedLock) or a cluster-aware scheduler, and the job still has to be idempotent.

Read in post: Cron jobs
Trade-offSeniorPreventing duplicate runs across instances: ShedLock, Quartz cluster, Kubernetes CronJob
Approach Idea Trade-offs
ShedLock A lock in DB/Redis/ZooKeeper; whichever instance gets it runs the job Simple, enough for most cases. It only guarantees "not at the same time"; it isn't a real distributed scheduler (no catch-up, no work distribution)
Quartz cluster (JDBC JobStore) A real distributed scheduler keeping trigger state in the DB Has misfire policies (catch-up), but heavyweight with many tables
Dedicated worker / enable on one instance only Turn the job on via a property for one deployment Single point of failure
Kubernetes CronJob The platform runs a container on a schedule Fully separate from the app; has concurrencyPolicy: Forbid, startingDeadlineSeconds, timeZone
External scheduler (Airflow, Temporal, JobRunr, db-scheduler) Stateful workflows/queues Most powerful, but one more system to operate
Read in post: Cron jobs
Edge caseSeniorDaylight saving time makes a cron job skip a day or run twiceI tried the Spring cron 0 30 2 with zone = "Europe/Berlin" (which has DST, daylight saving time): On the spring-forward day (2:00 jumps to 3:00), 02:30 doesn't exist, and Spring skips that day. On the fall-back day (3:00 goes back to 2:00), 02:30 happens twice, Spring returns both times, and the job runs twice. Asia/Ho

I tried the Spring cron 0 30 2 * * * with zone = "Europe/Berlin" (which has DST, daylight saving time):

  • On the spring-forward day (2 jumps to 3), 02 doesn't exist, and Spring skips that day.
  • On the fall-back day (3 goes back to 2), 02 happens twice, Spring returns both times, and the job runs twice.

Asia/Ho_Chi_Minh has no DST. If you serve several countries, avoid scheduling between 01 and 03 local time, or use UTC, and keep jobs idempotent.

Read in post: Cron jobs
InterviewJuniorWhat is a cron job? Give a few backend examples.

A task that runs on a recurring schedule or at a specific time.

Examples: cleaning up old data, sending summary emails, end-of-day payment reconciliation, refreshing caches, expiring unpaid orders.

Read in post: Cron jobs
InterviewJuniorHow many fields does a Spring cron expression have?

Six: second, minute, hour, day of month, month, day of week.

No year field (unlike Quartz), and one more field (seconds) than the 5-field Unix crontab.

Read in post: Cron jobs
InterviewJuniorWhat's the difference between fixedRate and fixedDelay?

fixedRate measures the interval between starts; fixedDelay measures from the end of one run to the start of the next.

With the default scheduler neither overlaps; a late fixed-rate run starts immediately after the previous one finishes.

Read in post: Cron jobs
InterviewJuniorWhat does 0 0/15 9-17 * * MON-FRI mean?

Every 15 minutes (minutes 0, 15, 30, 45) from 9 to 17, Monday through Friday.

Read in post: Cron jobs
InterviewMidWhy can one slow job delay all the others?

Because Spring Boot's default scheduler has a single thread shared by every @Scheduled method.

Increase spring.task.scheduling.pool.size, or have heavy jobs hand off work to their own executor.

Read in post: Cron jobs
InterviewMidWhich day is day-of-week 1?

It depends: Monday in Spring and Unix, Sunday in Quartz.

That's why you should use names (MON) instead of numbers.

Read in post: Cron jobs
InterviewMidWhat happens when a @Scheduled method throws?

For repeating tasks, the default ErrorHandler logs and swallows the exception, and the next run still happens.

You need your own logging, metrics and alerts, or the job can fail silently for a long time.

Read in post: Cron jobs
InterviewMidIf the app is down when a job should fire, does Spring catch up?

No. @Scheduled keeps no state; a missed fire time is simply gone.

For catch-up, use Quartz (misfire policies), or design the job to run frequently with a data-driven condition so it catches up on its own.

Read in post: Cron jobs
InterviewSeniorYou deploy 3 instances. How many times does a @Scheduled job run, and what do you do about it?

Three times, once per instance. Add a distributed lock and still keep the job idempotent.

Use ShedLock on a DB or Redis so only one instance runs it; or a Quartz cluster, a Kubernetes CronJob with concurrencyPolicy: Forbid, or a dedicated worker. Even with a lock, the job must be idempotent, because locks can expire and people run jobs by hand.

Read in post: Cron jobs
InterviewSeniorHow do you choose ShedLock's lockAtMostFor?

Longer than the job's longest possible runtime, but not absurdly long.

Too short and the lock expires mid-run, so another instance starts in parallel. Too long and, if a pod dies, the job is blocked until the lock expires. Pair it with a time budget inside the job itself.

Read in post: Cron jobs
InterviewSeniorHow do time zones and DST affect cron jobs?

Cron is evaluated in zone, which defaults to the JVM time zone (usually UTC in containers), so set it explicitly.

In DST time zones, a fire time inside the skipped hour doesn't run, and one inside the repeated hour can run twice. Avoid the transition window, use UTC, and keep jobs idempotent.

Read in post: Cron jobs
InterviewSeniorWhen would you move off @Scheduled to something else?

When I need what @Scheduled lacks: catch-up runs, schedules that change at runtime, a history of each execution, controlled retries, work spread across workers, or multi-step workflows.

Then consider a Quartz cluster, db-scheduler/JobRunr, Kubernetes CronJobs, or Temporal/Airflow.

Read in post: Cron jobs
Edge caseJuniorThe slides' "Data Types" table lists Hibernate types, not MySQL column typesThe slide shows names like integer, long, bigdecimal, yesno and truefalse, each with a Java type and an ANSI SQL type. That's Hibernate 5's mapping-type table, not MySQL column types: MySQL has no yesno or long column. yesno and truefalse were Hibernate 5's way of storing a boolean as CHAR(1) 'Y'/'N' or 'T'/'F'. Hibern

The slide shows names like integer, long, big_decimal, yes_no and true_false, each with a Java type and an ANSI SQL type. That's Hibernate 5's mapping-type table, not MySQL column types: MySQL has no yes_no or long column.

yes_no and true_false were Hibernate 5's way of storing a boolean as CHAR(1) 'Y'/'N' or 'T'/'F'. Hibernate 6 dropped those names in favour of converters: @Convert(converter = YesNoConverter.class), TrueFalseConverter, NumericBooleanConverter (package org.hibernate.type). Design tables in the DBMS's column types; the Java mapping is the ORM's job.

Read in post: Databases
Edge caseMidMySQL's utf8 stores at most 3 bytes per character, so emoji failIn MySQL, utf8 is an alias for utf8mb3: at most 3 bytes per character, so no emoji or some rare CJK characters (which need 4 bytes). Strict mode fails the insert with Incorrect string value; without it the string is truncated. Always use utf8mb4 (the default since MySQL 8.0) for the database, tables, columns and the JD

In MySQL, utf8 is an alias for utf8mb3: at most 3 bytes per character, so no emoji or some rare CJK characters (which need 4 bytes). Strict mode fails the insert with Incorrect string value; without it the string is truncated.

Always use utf8mb4 (the default since MySQL 8.0) for the database, tables, columns and the JDBC connection. Changing a big table's charset later means copying the whole table.

Read in post: Databases
Edge caseMidThe default collation utf8mb4_0900_ai_ci treats e, E and ê as equalA collation is the rule set for comparing and sorting strings; aici means accent-insensitive, case-insensitive. So WHERE name = 'le' also matches 'Lê', and UNIQUE(email) rejects An@x.com once an@x.com exists. For email that's usually what you want; for discount codes, tokens or hashes it isn't. Use utf8mb4bin (or utf8m

A collation is the rule set for comparing and sorting strings; ai_ci means accent-insensitive, case-insensitive. So WHERE name = 'le' also matches 'Lê', and UNIQUE(email) rejects An@x.com once an@x.com exists.

For email that's usually what you want; for discount codes, tokens or hashes it isn't. Use utf8mb4_bin (or utf8mb4_0900_as_cs) on columns that need exact comparison. PostgreSQL is the other way round: case-sensitive by default, so use citext or a unique index on lower(email) for case-insensitive matching.

Read in post: Databases
Trade-offJuniorNatural vs surrogate primary keyA natural key has business meaning (national ID, email). A surrogate key is a generated id with no meaning. Use a surrogate primary key and put UNIQUE on the natural key, because natural keys tend to be "immutable until they aren't" (users change their email).

A natural key has business meaning (national ID, email). A surrogate key is a generated id with no meaning. Use a surrogate primary key and put UNIQUE on the natural key, because natural keys tend to be "immutable until they aren't" (users change their email).

Read in post: Databases
Edge caseMidRandom UUID v4 primary keys fragment InnoDB's clustered indexIn InnoDB the primary key is the clustered index: the whole row lives in the leaves of a B+tree ordered by the PK. So the PK should be short and increasing. A random UUID v4 makes inserts land anywhere in the tree, causing page splits and fragmentation. If you need UUIDs, use UUID v7 or ULID (time-ordered), stored as B

In InnoDB the primary key is the clustered index: the whole row lives in the leaves of a B+tree ordered by the PK. So the PK should be short and increasing. A random UUID v4 makes inserts land anywhere in the tree, causing page splits and fragmentation.

If you need UUIDs, use UUID v7 or ULID (time-ordered), stored as BINARY(16). More in the indexes post.

Read in post: Databases
TILMidMySQL DDL commits implicitly; PostgreSQL DDL is transactionalIn MySQL, DDL (CREATE, ALTER, DROP...) implicitly commits the open transaction, so you can't roll back an ALTER TABLE. PostgreSQL has transactional DDL: an ALTER TABLE inside a transaction can be rolled back, which is very handy for migrations.

In MySQL, DDL (CREATE, ALTER, DROP...) implicitly commits the open transaction, so you can't roll back an ALTER TABLE. PostgreSQL has transactional DDL: an ALTER TABLE inside a transaction can be rolled back, which is very handy for migrations.

Read in post: Databases
Edge caseJuniorUPDATE/DELETE without WHERE hits the whole tableThe MySQL client has --safe-updates to block it. In production code, always check the affected row count.

The MySQL client has --safe-updates to block it. In production code, always check the affected row count.

Read in post: Databases
Trade-offJuniorDELETE vs TRUNCATE vs DROPDELETE: removes rows one by one, logged, can be rolled back, fires triggers. Use it when you need a condition or a rollback. TRUNCATE: wipes everything fast by recreating the table, resets AUTOINCREMENT, can't be rolled back in MySQL. Use it to empty a large table (e.g. a staging table). DROP: removes the table itself,
  • DELETE: removes rows one by one, logged, can be rolled back, fires triggers. Use it when you need a condition or a rollback.
  • TRUNCATE: wipes everything fast by recreating the table, resets AUTO_INCREMENT, can't be rolled back in MySQL. Use it to empty a large table (e.g. a staging table).
  • DROP: removes the table itself, when you want it gone.
Read in post: Databases
TILMidMySQL only enforces CHECK constraints from 8.0.16CHECK (price = 0) is only actually enforced from MySQL 8.0.16. Older versions parse it and silently ignore it, so bad data still gets in.

CHECK (price >= 0) is only actually enforced from MySQL 8.0.16. Older versions parse it and silently ignore it, so bad data still gets in.

Read in post: Databases
Edge caseJuniorNOT IN returns nothing if the subquery contains a NULLWHERE id NOT IN (SELECT x FROM t) returns nothing if the subquery yields even one NULL, because id < NULL is UNKNOWN. Use NOT EXISTS or LEFT JOIN ... WHERE right.id IS NULL.

WHERE id NOT IN (SELECT x FROM t) returns nothing if the subquery yields even one NULL, because id <> NULL is UNKNOWN. Use NOT EXISTS or LEFT JOIN ... WHERE right.id IS NULL.

Read in post: Databases
Edge caseJuniorLIMIT without ORDER BY has no guaranteed orderIt looks right today; tomorrow the plan changes and your pages shift. When paginating, always ORDER BY a unique key (e.g. append id).

It looks right today; tomorrow the plan changes and your pages shift. When paginating, always ORDER BY a unique key (e.g. append id).

Read in post: Databases
Edge caseSeniorAn "online" ALTER TABLE can still freeze the whole table through a metadata lockEvery ALTER TABLE, even ALGORITHM=INSTANT, needs an exclusive metadata lock (MDL) for a moment. A long-running transaction that has read the table holds a shared MDL until it commits, so the ALTER waits. Worse: while the ALTER waits, every new SELECT/UPDATE on the table queues behind it, and the application looks down.

Every ALTER TABLE, even ALGORITHM=INSTANT, needs an exclusive metadata lock (MDL) for a moment. A long-running transaction that has read the table holds a shared MDL until it commits, so the ALTER waits. Worse: while the ALTER waits, every new SELECT/UPDATE on the table queues behind it, and the application looks down.

To prevent it: check for long transactions before migrating (information_schema.innodb_trx), and set SET SESSION lock_wait_timeout = 5; so the ALTER gives up early and retries instead of holding the queue for a minute.

Read in post: Databases
Trade-offSeniorChanging a big table's schema: plain ALTER, an online tool, or expand/contractPlain ALTER: the simplest. Use it when the operation is INSTANT/INPLACE without blocking writes, or the table is small enough that the lock time is acceptable. Online tools (gh-ost, pt-online-schema-change): create a "shadow" table with the new schema, copy data gradually, keep new changes in sync (gh-ost reads the bin
  • Plain ALTER: the simplest. Use it when the operation is INSTANT/INPLACE without blocking writes, or the table is small enough that the lock time is acceptable.
  • Online tools (gh-ost, pt-online-schema-change): create a "shadow" table with the new schema, copy data gradually, keep new changes in sync (gh-ost reads the binlog, pt-osc uses triggers), and finally swap names atomically. No long write lock, but double the disk space, hours of runtime and extra load on the DB. Use them for COPY operations such as changing a column type.
  • Expand/contract in the application: several deploys, dual-write code and a backfill job, but every step can be rolled back and running code never breaks. Mandatory for backward-incompatible changes like renaming or splitting a column.
Read in post: Databases
InterviewJuniorHow is a primary key different from a unique key?

Both prevent duplicates; a PK can't be NULL and there's only one per table.

You can have many unique keys per table and (in MySQL/Postgres) they allow multiple NULLs. In InnoDB the PK is also the clustered index that determines how rows are laid out on disk.

Read in post: Databases
InterviewJuniorDELETE vs TRUNCATE vs DROP?

DELETE removes matching rows and can be rolled back; TRUNCATE wipes all rows very fast; DROP removes the table.

DELETE logs each row and fires triggers. TRUNCATE resets auto-increment and, in MySQL, is DDL, so no rollback. DROP removes both data and structure.

Read in post: Databases
InterviewJuniorWhy use a database instead of storing data in files yourself?

Because files have no transactions, constraints, fine-grained permissions or concurrency control; crash halfway and you're left with half old, half new data.

Files also lead to redundancy and inconsistency (the same data copied in several places), every query means hand-written code, and concurrent writers overwrite each other. A DBMS gives you a query language, constraints, fine-grained permissions, concurrency control, ACID and backup/recovery.

Read in post: Databases
InterviewJuniorHow do CHAR, VARCHAR and TEXT differ?

CHAR(n) is fixed-length, VARCHAR(n) is variable-length (the default choice), TEXT is for long strings.

  • CHAR(n): pads shorter values with spaces; suits fixed-size codes like CHAR(2).
  • VARCHAR(n): adds a 1–2 byte length prefix.
  • TEXT in MySQL: can't be fully indexed (you need a prefix index), can't have a literal DEFAULT, and may be stored off the main data page.
  • In PostgreSQL, TEXT and VARCHAR perform the same.
Read in post: Databases
InterviewJuniorWhat column types do boolean, BigDecimal and Instant fields become in MySQL?

Hibernate 6 defaults: boolean becomes BIT(1), BigDecimal becomes DECIMAL(38,2), Instant becomes DATETIME(6)/TIMESTAMP(6) stored as UTC.

  • Hand-written migrations often use BOOLEAN (= TINYINT(1)) for booleans.
  • Always declare precision/scale for money.
  • MySQL can't keep the offset, hence the UTC convention; PostgreSQL has timestamptz.
  • String defaults to VARCHAR(255); store enums as strings with EnumType.STRING.
  • yes_no and true_false are Hibernate 5 mapping types, not column types.
Read in post: Databases
InterviewMidWhat's the trap with NOT IN?

If the subquery returns even one NULL, x NOT IN (...) is UNKNOWN for every x and the result is empty.

Use NOT EXISTS or LEFT JOIN ... WHERE right.id IS NULL (an anti-join) instead.

Read in post: Databases
InterviewMidWhat does AVG(score) return on a column with NULLs?

AVG ignores NULLs, so it divides by the rows that have a score, not the total row count.

Four students where one has no score yet gives an average over three. If "no score" should count as 0, write AVG(COALESCE(score, 0)). Likewise, COUNT(score) differs from COUNT(*). The question checks that you know NULL means "unknown", not 0.

Read in post: Databases
InterviewMidWhat's the difference between utf8 and utf8mb4 in MySQL?

MySQL's utf8 is really utf8mb3, at most 3 bytes per character, so no emoji; utf8mb4 is real UTF-8.

utf8mb4 is the default since MySQL 8.0; set it at every layer: database, table, column and connection. Also watch the default collation utf8mb4_0900_ai_ci, which is case- and accent-insensitive and affects comparisons and unique constraints.

Read in post: Databases
InterviewSeniorChoosing a primary key: auto-increment, UUID v4 or UUID v7/ULID?

On InnoDB, pick an increasing key: auto-increment, or UUID v7/ULID when ids must be generated in a distributed way; avoid UUID v4.

  • Auto-increment: small and increasing, ideal for a clustered index; but it leaks record counts, can't be generated client-side, and makes merging shards awkward.
  • UUID v4: can be generated anywhere, but random, so inserts scatter across the B+tree, causing page splits and poor buffer pool usage, and its 16 bytes repeat in every secondary index.
  • UUID v7/ULID: a time prefix keeps them roughly increasing while staying globally unique.
  • Store as BINARY(16) (MySQL) or uuid (Postgres), never VARCHAR(36).
Read in post: Databases
InterviewSeniorWhat types do you use for money and for time?

Money: DECIMAL (or an integer in the smallest unit). Time: store UTC.

  • Never FLOAT/DOUBLE for money, because of binary rounding.
  • MySQL: DATETIME has no time zone (the application must guarantee UTC), TIMESTAMP converts but stops at 2038. Postgres: use timestamptz.
  • Java: map to Instant/OffsetDateTime, not LocalDateTime, for absolute points in time.
Read in post: Databases
InterviewSeniorHow do you add a column or change a column type on a 100-million-row table without downtime?

Find out whether the operation is INSTANT, INPLACE or COPY; use gh-ost/pt-online-schema-change for COPY, and expand/contract for backward-incompatible changes.

  • Adding a column or changing a default: INSTANT. Adding an index: INPLACE without blocking writes. Changing a column type: COPY, blocks writes.
  • State ALGORITHM=INSTANT/LOCK=NONE so MySQL errors out instead of silently copying; set a low lock_wait_timeout, because the ALTER still needs a metadata lock for a moment.
  • Renaming or splitting a column: add the new column, dual-write, backfill in batches, switch reads, then drop the old one.
  • All of it managed with Flyway/Liquibase.
Read in post: Databases
TILMidMySQL has no partial index: emulate it with a generated column + UNIQUEA partial index only contains rows that match a condition. MySQL doesn't have one, so I use a generated column (a column the database computes from others): openbookid equals bookid while the loan is open and NULL once returned. MySQL allows many NULLs in a unique index, so only open loans are checked. PostgreSQL makes

A partial index only contains rows that match a condition. MySQL doesn't have one, so I use a generated column (a column the database computes from others): open_book_id equals book_id while the loan is open and NULL once returned. MySQL allows many NULLs in a unique index, so only open loans are checked.

PostgreSQL makes this a one-liner: CREATE UNIQUE INDEX ... ON loan(book_id) WHERE returned_at IS NULL.

Read in post: Databases
Edge caseMidAn application-level check-then-insert can't stop two concurrent loansThe unique index uqloanoneopenperbook stops the database from lending a book that's already out: Two librarians click "lend" at the same moment: a check-then-insert (check first, then write) in the application lets both through, the unique index doesn't. See race conditions in transactions and locking.

The unique index uq_loan_one_open_per_book stops the database from lending a book that's already out:

ERROR 1062 (23000): Duplicate entry 'B0001' for key 'loan.uq_loan_one_open_per_book'

Two librarians click "lend" at the same moment: a check-then-insert (check first, then write) in the application lets both through, the unique index doesn't. See race conditions in transactions and locking.

Read in post: Databases
Trade-offMidDeleting rows that have history: skip, delete the history, or soft deleteA plain DELETE FROM book WHERE price < 10 fails on the FK if the book has ever been lent ("Little Lantern" at 8.5 is currently on loan). Three options: Skip books with history (the solution to 11). Delete the loan history first: loses audit data, not recommended. Soft delete (isactive = 0): mark the row as deleted inst

A plain DELETE FROM book WHERE price < 10 fails on the FK if the book has ever been lent ("Little Lantern" at 8.5 is currently on loan). Three options:

  • Skip books with history (the solution to #11).
  • Delete the loan history first: loses audit data, not recommended.
  • Soft delete (is_active = 0): mark the row as deleted instead of removing it. For a library I'd do this.

The question to ask whoever wrote the requirement is what "delete" actually means.

Read in post: Databases
Edge caseMidWrapping a column in a function makes the predicate non-sargableWrite duedate < <constant rather than DATEDIFF(...) 7 (27). Wrapping the column in a function means the predicate is no longer sargable (able to use an index), so the index on duedate is ignored. Comparing the bare column to a precomputed constant can use it.

Write due_date < <constant> rather than DATEDIFF(...) > 7 (#27). Wrapping the column in a function means the predicate is no longer sargable (able to use an index), so the index on due_date is ignored. Comparing the bare column to a precomputed constant can use it.

Read in post: Databases
Edge caseMidCounting "today": condition in ON, a half-open range, and the time zone28 counts the slips each staff member issued "today" with employee LEFT JOIN loan. Three things are easy to get wrong: The date condition goes in ON, not WHERE, so staff who issued nothing still show up with 0. A half-open range [today, tomorrow) instead of DATE(dateout) = CURRENTDATE lets the (empid, dateout) index be

#28 counts the slips each staff member issued "today" with employee LEFT JOIN loan. Three things are easy to get wrong:

  • The date condition goes in ON, not WHERE, so staff who issued nothing still show up with 0.
  • A half-open range [today, tomorrow) instead of DATE(date_out) = CURRENT_DATE lets the (emp_id, date_out) index be used.
  • CURRENT_DATE uses the MySQL session time zone. If the server runs in UTC and the library is in Vietnam (UTC+7), anything between midnight and 7 a.m. lands on the previous day. Compute the day boundaries in the application using the business time zone and pass them in as parameters.
Read in post: Databases
Edge caseJuniorLIKE is case-insensitive on MySQL 8 but case-sensitive on PostgreSQLMySQL 8's default collation (utf8mb40900aici) is case-insensitive, so 'the%' matches too. PostgreSQL is case-sensitive; use ILIKE or lower().

MySQL 8's default collation (utf8mb4_0900_ai_ci) is case-insensitive, so 'the%' matches too. PostgreSQL is case-sensitive; use ILIKE or lower().

Read in post: Databases
Trade-offMidEXISTS vs JOIN for "has at least one"EXISTS is a semi-join: it stops at the first matching loan and never duplicates rows. With JOIN loan, a book borrowed twice appears twice and you'd need DISTINCT.

EXISTS is a semi-join: it stops at the first matching loan and never duplicates rows. With JOIN loan, a book borrowed twice appears twice and you'd need DISTINCT.

Read in post: Databases
Edge caseJuniorORDER BY ... LIMIT 1 misses tiesFiltering WHERE price = (SELECT MAX(price) FROM book) OR price = (SELECT MIN(price) FROM book) returns every book tied for first or last. ORDER BY price DESC LIMIT 1 would return just one and could miss ties.

Filtering WHERE price = (SELECT MAX(price) FROM book) OR price = (SELECT MIN(price) FROM book) returns every book tied for first or last. ORDER BY price DESC LIMIT 1 would return just one and could miss ties.

Read in post: Databases
TILMidWITH ROLLUP adds a total row; GROUPING() tells it apart from real NULLsWITH ROLLUP adds a grand-total row (with the group column set to NULL). PostgreSQL writes it as GROUP BY ROLLUP (p.name). COALESCE gets confused if the group column has real NULLs; use GROUPING(p.name) to tell them apart.

WITH ROLLUP adds a grand-total row (with the group column set to NULL). PostgreSQL writes it as GROUP BY ROLLUP (p.name). COALESCE gets confused if the group column has real NULLs; use GROUPING(p.name) to tell them apart.

Read in post: Databases
Edge caseMidReturning a book twice: without returned_at IS NULL the return date and penalty get overwrittenWithout AND returnedat IS NULL, the second click also succeeds: it overwrites the real return date with a later one and adds to the penalty. With it, the statement becomes a compare-and-set (write only if the data is still what you expect): the first call updates 1 row, any later call updates 0. The application checks

Without AND returned_at IS NULL, the second click also succeeds: it overwrites the real return date with a later one and adds to the penalty.

With it, the statement becomes a compare-and-set (write only if the data is still what you expect): the first call updates 1 row, any later call updates 0. The application checks that executeUpdate() returned 0 and reports "this loan has already been returned" instead of a generic error. That's what makes "return a book" idempotent (calling it many times has the same effect as once).

Read in post: Databases
Trade-offSeniorcard_no as the primary key, or a BIGINT surrogate keyThe brief makes the VARCHAR(5) card number the primary key of member: a natural key (taken from business data). Pros: no extra column, and the data is easy to read. Cons: A card number will change one day (lost card, reissue, a switch to 8 characters). Changing a PK means updating every FK in loan and every external sy

The brief makes the VARCHAR(5) card number the primary key of member: a natural key (taken from business data). Pros: no extra column, and the data is easy to read.

Cons:

  • A card number will change one day (lost card, reissue, a switch to 8 characters). Changing a PK means updating every FK in loan and every external system that stored it.
  • In InnoDB every secondary index carries the PK, so a long PK makes every index bigger.

The safer choice: id BIGINT AUTO_INCREMENT PRIMARY KEY (a surrogate key that never changes) plus UNIQUE (card_no) to keep the business rule. Keep a natural key only when it's truly immutable (ISO country codes, currency codes).

Read in post: Databases
InterviewJuniorWhy does query #19 use LEFT JOIN and COUNT(l.invoice_no) rather than COUNT(*)?

So members who've never borrowed still appear, and show 0 rather than 1.

LEFT JOIN keeps those members, with the loan columns set to NULL. COUNT(*) counts rows, so they'd still count as 1. COUNT(l.invoice_no) counts only non-NULL values, so it correctly gives 0.

Read in post: Databases
InterviewJuniorIn query #25 the genre condition is in WHERE but the count threshold is in HAVING. Why?

WHERE filters rows before grouping; HAVING filters groups after.

Filtering the genre in WHERE is both correct and reduces the rows to group. HAVING is the only place you can use an aggregate like COUNT(*) >= 2. Putting the genre condition in HAVING is either a syntax error (the column isn't grouped) or slower.

Read in post: Databases
InterviewMidHow do you guarantee "at most one open loan per book" in the database?

A unique index that only covers open loans: a partial unique index in PostgreSQL, a generated column + unique key in MySQL.

  • PostgreSQL: UNIQUE (book_id) WHERE returned_at IS NULL.
  • MySQL: a generated column equal to book_id while the loan is open and NULL afterwards, with a unique key on it (unique allows many NULLs).

An application-only check isn't enough because of races between concurrent requests.

Read in post: Databases
InterviewMidWe already validate in Java. Do we still need NOT NULL, CHECK and FKs in the database?

Yes. The database is the last gate that every write path goes through.

Migration scripts, batch jobs, another service, someone running SQL by hand: none of them go through your Java code. Check-then-act also isn't safe under concurrency. Database constraints are cheap, always enforced, and living documentation of the business rules. Application validation is still needed for friendly errors; the two layers complement each other.

Read in post: Databases
InterviewSeniorThe loan table reaches 50 million rows and the "overdue loans" screen keeps getting slower. What do you do?

Measure with EXPLAIN, add an index aimed only at open loans, and longer term archive old loans so the hot table shrinks.

  • Check for a full scan. The query filters on returned_at IS NULL AND due_date < ?, so add an index on (returned_at, due_date) in MySQL or a partial index on (due_date) WHERE returned_at IS NULL in PostgreSQL; open loans are a small fraction, so the index stays compact.
  • Long list: keyset pagination instead of OFFSET.
  • Longer term: archive long-closed loans into a separate table.
  • Aggregate reports still heavy: move them to a read replica or a warehouse, not the primary.
Read in post: Databases
InterviewSeniorThe brief is ambiguous ("delete books", "not late"). What do you do?

Don't guess and code: list the possible readings, propose a default with a reason, and confirm it with whoever owns the requirement.

Spell out the consequence of each reading: a hard delete loses loan history and hits the FK; does "not late" include open loans that aren't due yet? Turn the agreed answer into a test case or put it in the spec so nobody has to ask again. For data, the safe default is not losing information: soft delete rather than hard delete.

Read in post: Databases
Edge caseJuniorA 1-1 relationship needs UNIQUE on the foreign key, or it is really 1-nAdding studentid as an FK on the card table without UNIQUE lets a student have many cards, so it's really 1-n. Technically the FK can go on either side, but put it on the dependent table (a card can't exist without a student) and always add UNIQUE.

Adding student_id as an FK on the card table without UNIQUE lets a student have many cards, so it's really 1-n. Technically the FK can go on either side, but put it on the dependent table (a card can't exist without a student) and always add UNIQUE.

Read in post: Databases
Trade-offMidON DELETE CASCADE vs RESTRICT on a foreign keyCASCADE is handy but dangerous: one DELETE can silently remove thousands of rows across three other tables. For important business data (orders, payments) I keep RESTRICT and handle deletion deliberately in code, or use soft delete (post 5 of this series).

CASCADE is handy but dangerous: one DELETE can silently remove thousands of rows across three other tables. For important business data (orders, payments) I keep RESTRICT and handle deletion deliberately in code, or use soft delete (post 5 of this series).

Read in post: Databases
Trade-offJuniorChen or crow's foot notation for an ERDChen suits conceptual analysis: it shows a relationship as a "verb" that can carry attributes, but the diagram balloons because every attribute is an ellipse. Crow's foot is compact, close to the actual tables (columns, PK/FK) and shows mandatory vs optional, so it's the default for schema design. Interviews mostly use

Chen suits conceptual analysis: it shows a relationship as a "verb" that can carry attributes, but the diagram balloons because every attribute is an ellipse. Crow's foot is compact, close to the actual tables (columns, PK/FK) and shows mandatory vs optional, so it's the default for schema design. Interviews mostly use crow's foot; being able to read Chen is enough.

Read in post: Databases
Edge caseMidA right-table condition in WHERE turns a LEFT JOIN into an INNER JOINWith a LEFT JOIN, a condition in ON is not the same as one in WHERE. LEFT JOIN book b ON b.borrowerid = s.id AND b.year 2020 keeps every student. ... WHERE b.year 2020 drops students with no books (because NULL 2020 is UNKNOWN), silently turning the LEFT JOIN into an INNER JOIN.

With a LEFT JOIN, a condition in ON is not the same as one in WHERE. LEFT JOIN book b ON b.borrower_id = s.id AND b.year > 2020 keeps every student. ... WHERE b.year > 2020 drops students with no books (because NULL > 2020 is UNKNOWN), silently turning the LEFT JOIN into an INNER JOIN.

Read in post: Databases
Edge caseMidJoining two one-to-many relations at once multiplies aggregates (fan-out)Join fan-out: a customer with 5 orders and 3 addresses, joined to both, gives 15 rows, so SUM(order.total) is tripled. Fix it by aggregating in a subquery first and joining afterwards.

Join fan-out: a customer with 5 orders and 3 addresses, joined to both, gives 15 rows, so SUM(order.total) is tripled. Fix it by aggregating in a subquery first and joining afterwards.

Read in post: Databases
Edge caseJuniorSELECT * ... GROUP BY age, as pictured on the slide, is rejected by MySQL 8The slide illustrates GROUP BY with select from student and then group by age, as if the result were one full row per age. MySQL 8 (ONLYFULLGROUPBY) fails with error 1055, because id, name... are neither in GROUP BY nor functionally dependent on age. MySQL 5.6 and earlier run it but return values from an arbitrary row

The slide illustrates GROUP BY with select * from student and then group by age, as if the result were one full row per age. MySQL 8 (ONLY_FULL_GROUP_BY) fails with error 1055, because id, name... are neither in GROUP BY nor functionally dependent on age. MySQL 5.6 and earlier run it but return values from an arbitrary row in each group, a classic source of bugs. Write it properly: SELECT age, COUNT(*) FROM student GROUP BY age, or to see the names in each group, SELECT age, GROUP_CONCAT(name ORDER BY name) FROM student GROUP BY age (PostgreSQL: string_agg).

Read in post: Databases
Trade-offMidTeacher–Course: a teacher_id column (1-n) or a course_teacher table (n-n)A course.teacherid NOT NULL column (1-n) is simple, joins in one step, and the database guarantees exactly one teacher per course. If the business needs co-teaching (several teachers, lead/assistant roles, revenue sharing), switch to courseteacher(courseid, teacherid, role, revenueshare, PRIMARY KEY (courseid, teacheri

A course.teacher_id NOT NULL column (1-n) is simple, joins in one step, and the database guarantees exactly one teacher per course. If the business needs co-teaching (several teachers, lead/assistant roles, revenue sharing), switch to course_teacher(course_id, teacher_id, role, revenue_share, PRIMARY KEY (course_id, teacher_id)). The cost: every "teachers of this course" query needs one more join, and "exactly one lead teacher" is no longer a simple constraint (you need a conditional unique index or an application check). Ask first, because moving from 1-n to n-n later is a data migration.

Read in post: Databases
InterviewJuniorWhat's the difference between WHERE and HAVING?

WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY.

WHERE can't use aggregates, while HAVING can use COUNT, SUM and so on. Anything you can filter in WHERE should go there, because it shrinks the data before grouping.

Read in post: Databases
InterviewJuniorINNER JOIN vs LEFT JOIN?

INNER keeps only rows that match on both sides; LEFT keeps every left row and fills the right-hand columns with NULL when there's no match.

"List every customer with their order count, including customers who never bought anything" needs a LEFT JOIN with COUNT(o.id).

Read in post: Databases
InterviewJuniorHow do you implement a many-to-many relationship?

With a junction table holding two FKs to the two tables, and a composite PK (or UNIQUE) on the pair.

The composite PK prevents duplicates; add an index on the second FK for reverse lookups. The junction table often carries attributes of the relationship itself, like an enrolment date or a rating.

Read in post: Databases
InterviewJuniorHow do you read TEACHER ||--o{ COURSE in a crow's foot ERD, and how does it differ from Chen notation?

Each course has exactly one teacher and a teacher teaches zero or more courses; as tables, teacher_id is an FK on course.

In crow's foot you read the symbol at each end of the line: on the TEACHER end || (exactly one), on the COURSE end o{ (zero or many). Chen draws the same thing as two rectangles joined through a "teach" diamond, with 1 and N on the lines and attributes as ellipses. Crow's foot is closer to the real tables, so it's the usual choice for schema design.

Read in post: Databases
InterviewMidWhy do COUNT(*) and COUNT(column) differ after a LEFT JOIN?

COUNT(*) counts every row, including the NULL-filled rows the LEFT JOIN produces; COUNT(col) skips NULLs.

Counting "orders per customer" with COUNT(*) returns 1 for customers with no orders. Count a column from the right-hand table, usually its PK.

Read in post: Databases
InterviewMidWhat's the logical execution order of SELECT, and why can't you use an alias in WHERE?

FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT; aliases are created in the SELECT step, after WHERE.

So WHERE can't see them, while ORDER BY runs later and can. MySQL leniently allows aliases in HAVING; PostgreSQL doesn't.

Read in post: Databases
InterviewMidWhat happens if you LEFT JOIN and then filter the right table in WHERE?

The result is identical to an INNER JOIN: the unmatched rows are dropped.

Unmatched rows have NULLs in the right-hand columns, so a condition like WHERE r.status = 'X' evaluates to UNKNOWN and drops them. To keep the left rows, move the condition into ON.

Read in post: Databases
InterviewMidWhen would you use ON DELETE CASCADE?

When the child rows are an inseparable part of the parent with no business value of their own, e.g. the lines of a temporary shopping cart.

Avoid it for financial, historical or audit data: one delete can spread much further than intended. Prefer RESTRICT and deliberate deletion or archiving.

Read in post: Databases
InterviewSeniorA JOIN fans out and SUM comes out wrong. How do you fix it?

Aggregate each child table by the parent key first (subquery/CTE), then join the aggregated results.

Joining a parent to two 1-n child tables at once makes the row count the product of both sides, so totals get multiplied. After aggregating, each child contributes one row per parent. A correlated subquery in SELECT also works. Verify by comparing COUNT(*) before and after the join.

Read in post: Databases
InterviewSeniorHow does a database execute a JOIN, and why do FK columns need an index?

Mostly as a nested loop join: for each outer row, look up the inner table. With an index each lookup is O(log n); without one it's a full scan, so O(n × m) overall.

MySQL 8.0.18+ adds hash joins for the no-index case; PostgreSQL also has merge joins. An index on the FK also speeds up deleting or updating parent rows, because the database has to check the child table. Postgres doesn't create FK indexes automatically, which is a common performance bug.

Read in post: Databases
Trade-offMidJSON/array column vs a child table"Atomic" is relative to how you query it. An address string is atomic if you only ever print it, but not if you need to filter by province. A JSON column or a PostgreSQL array technically breaks 1NF, but it's reasonable when the data is always read and written as a whole (say, UI settings). Don't use them when you need

"Atomic" is relative to how you query it. An address string is atomic if you only ever print it, but not if you need to filter by province.

A JSON column or a PostgreSQL array technically breaks 1NF, but it's reasonable when the data is always read and written as a whole (say, UI settings). Don't use them when you need constraints, joins, or searches on individual elements.

Read in post: Databases
Edge caseMidThe purchase price in order_item is not a 2NF violationThe price at the time of purchase (unitprice in orderitem) is a different fact: "order 10 bought P1 at price X". It depends on the whole key, and you must keep it because product prices change. Telling "duplicated data" apart from "a historical snapshot" shows you understand the business.

The price at the time of purchase (unit_price in order_item) is a different fact: "order 10 bought P1 at price X". It depends on the whole key, and you must keep it because product prices change. Telling "duplicated data" apart from "a historical snapshot" shows you understand the business.

Read in post: Databases
Trade-offSeniorStop at 3NF or decompose to BCNFIn the table above, "teacher X teaches subject Y" repeats for every student. Decomposing to BCNF: teachersubject(teacher PK, subject) and studentteacher(student, teacher). The price: "one teacher per subject per student" can no longer be enforced with a simple unique constraint. That's why people sometimes stop at 3NF.

In the table above, "teacher X teaches subject Y" repeats for every student. Decomposing to BCNF: teacher_subject(teacher PK, subject) and student_teacher(student, teacher).

The price: "one teacher per subject per student" can no longer be enforced with a simple unique constraint. That's why people sometimes stop at 3NF.

Read in post: Databases
Edge caseMidThe 4NF example only works if the two sets are independent; "each course goes with one hobby" gets it backwardsSplit only when the two sets are truly independent; if a business rule links them, the three-column table is a legitimate fact. The slide leads in with "each course corresponds to one hobby". If the two really were linked (taking Piano means your hobby is Music), (student, course, hobby) must not be split. 4NF is viola

Split only when the two sets are truly independent; if a business rule links them, the three-column table is a legitimate fact.

The slide leads in with "each course corresponds to one hobby". If the two really were linked (taking Piano means your hobby is Music), (student, course, hobby) must not be split. 4NF is violated only when student ↠ course and student ↠ hobby are independent. Before splitting, ask: "is there any business rule connecting these two columns?".

Read in post: Databases
Edge caseSeniorSplitting a three-column table for 5NF without the cyclic rule creates spurious rowsWithout the cyclic rule (A1 sells only specific combinations), the three-column table is already in 5NF and must not be split. Splitting into three tables and joining back produces fake rows (spurious tuples). 5NF depends on business rules; you can't tell by looking at the data.

Without the cyclic rule (A1 sells only specific combinations), the three-column table is already in 5NF and must not be split. Splitting into three tables and joining back produces fake rows (spurious tuples). 5NF depends on business rules; you can't tell by looking at the data.

Read in post: Databases
Trade-offSeniorNormalize or denormalizeReal systems often deliberately denormalize in a few places: My rules of thumb: 1. Design normalized first (3NF/BCNF) and only denormalize with numbers: which query is slow, by how much, at what load. 2. Every copy needs one source of truth and an explicit sync mechanism (trigger, same transaction, events). 3. Write do

Real systems often deliberately denormalize in a few places:

Technique Example The cost
Stored counters/totals post.comment_count Must be kept in sync; concurrent writes go wrong easily (use an atomic UPDATE ... SET c = c + 1)
Copying a column to avoid a join order.customer_name Can drift when the customer renames. Fine if it means "name at the time of ordering"
Materialized views / reporting tables Revenue per day Stale data; needs a refresh job
A separate read model (CQRS), search index Pushing to Elasticsearch Eventual consistency; needs syncing via outbox/CDC
Star schema for OLAP Fact + dimension tables Not for OLTP

My rules of thumb:

  1. Design normalized first (3NF/BCNF) and only denormalize with numbers: which query is slow, by how much, at what load.
  2. Every copy needs one source of truth and an explicit sync mechanism (trigger, same transaction, events).
  3. Write down why, in the migration or an ADR, so the next person doesn't "fix it back to normal form" and kill performance.
Read in post: Databases
InterviewJuniorWhat is normalization and why do we do it?

It's organizing tables so each fact is stored once, based on functional dependencies.

The goal is to reduce redundancy and avoid update/insert/delete anomalies, so the data can't contradict itself when it changes.

Read in post: Databases
InterviewJuniorState 1NF, 2NF and 3NF in one sentence each.

1NF: one atomic value per cell, no repeating groups. 2NF: plus every non-key column depends on the whole key. 3NF: plus no transitive dependencies.

Transitive means a non-key column depends on the key through another non-key column.

Read in post: Databases
InterviewJuniorCan a table with a single-column PK violate 2NF?

No, because a partial dependency needs a key of two or more columns.

A 1NF table with a single-column PK is automatically in 2NF, though it can still violate 3NF.

Read in post: Databases
InterviewJuniorWhat's wrong with storing tags as "a,b,c" in one column?

It breaks 1NF; use an item_tag(item_id, tag) table instead.

You can't put an FK or uniqueness on individual tags. Searching by tag needs LIKE '%b%' (no index, and it also matches "bb"). Adding or removing a tag means parsing strings.

Read in post: Databases
InterviewJuniorA table has columns phone1, phone2, phone3 (or ActivityID1..3). Which normal form does it break? What about data repeated across rows?

Numbered columns are a repeating group, which breaks 1NF. Data repeated across rows isn't a 1NF problem; it's the symptom of a 2NF or 3NF violation.

  • Repeating group: a fourth item needs a schema change, and searching by value needs an OR across columns. Fix it with a child table (owner_id, value).
  • Repeated data (the same person's name and address in several rows): it depends on some other column rather than the key (partially or transitively), so it belongs in its own table.
Read in post: Databases
InterviewMidHow does 3NF differ from BCNF? Give an example.

BCNF requires every determinant (left side of a functional dependency) to be a superkey; 3NF makes an exception when the right side is a prime attribute.

Example: (student, subject, teacher) with teacher → subject is in 3NF because subject belongs to the key (student, subject), but not BCNF because teacher isn't a superkey.

Read in post: Databases
InterviewMidWhat is a multivalued dependency, and when is 4NF violated?

A ↠ B holds when each A maps to a set of B values independent of the other columns. 4NF is violated when one table holds two independent sets for the same key.

Example: employee × skill × language, which forces you to store the Cartesian product. The fix is one table per set.

Read in post: Databases
InterviewMidIs storing unit_price in order_item denormalization?

No, if it means "the price at purchase time".

That's a historical fact that depends on the order line, different from the current price in product. If you don't store it, changing a product's price corrupts every old invoice.

Read in post: Databases
InterviewMidDoes normalization make a system slower?

Usually not: writes get faster, and reads need extra joins, but joins on indexed keys are cheap in OLTP.

Writes are faster because there's one place to update, narrower rows and fewer indexes per table. Real slowness shows up only in big aggregates or very hot read paths; that's when you denormalize selectively, based on measurements rather than guesses.

Read in post: Databases
InterviewSeniorWhen do you deliberately denormalize, and how do you keep the data correct?

When measurements show joins or aggregates are the bottleneck on a hot read path; the copy always has one source of truth and an explicit sync mechanism.

  • Example: counting comments every time a feed loads.
  • Sync in the same transaction with an atomic increment (SET c = c + 1), or asynchronously via outbox/CDC if eventual consistency is acceptable.
  • Add a periodic reconciliation job to fix drift, and document the decision.
Read in post: Databases
InterviewSeniorDoes 5NF matter in practice?

Rarely; it only comes up with cyclic business rules (if A–B, B–C and C–A all hold, then A–B–C holds).

The practical lesson: splitting a three-way table into three two-way tables is only correct if that rule exists; otherwise joining back produces spurious rows. Decide from the business rules, not from sample data.

Read in post: Databases
InterviewSeniorHow does a normalized OLTP schema differ from a reporting/OLAP schema?

OLTP normalizes to 3NF/BCNF for many small writes that must be correct; OLAP uses a denormalized star/snowflake schema for big scans.

  • OLTP: index for point queries.
  • OLAP: fact table plus dimensions, usually in a columnar store in a separate warehouse fed by ETL/CDC.
  • Mixing both workloads on one database lets heavy reports steal locks and I/O from transactions.
Read in post: Databases
InterviewSeniorA 50-million-row production table violates 3NF. How do you split it without downtime?

Use expand–contract (parallel change) over several deploys, with every step reversible.

  1. Create the new table, which nothing reads yet.
  2. Make the code write to both the old column and the new table.
  3. Backfill old data in small batches (a few thousand rows each, with pauses) so you don't hold long locks or make replicas lag.
  4. Reconcile the two sources.
  5. Switch reads to the new table behind a feature flag so you can switch back.
  6. Stop writing the old column, and only then DROP it.

For big ALTER TABLEs on MySQL, use online DDL (ALGORITHM=INPLACE/INSTANT) or gh-ost/pt-online-schema-change.

Read in post: Databases
Edge caseSeniorA UUID v4 primary key slows InnoDB downThe PK should be short (every secondary index stores a copy) and increasing (inserts go to the end of the tree, with no page splits, i.e. splitting a full page in two). A random UUID v4 breaks both. PostgreSQL is different: a table is an unordered heap, and every index (including the PK) points to a physical location (
  • The PK should be short (every secondary index stores a copy) and increasing (inserts go to the end of the tree, with no page splits, i.e. splitting a full page in two). A random UUID v4 breaks both.
  • PostgreSQL is different: a table is an unordered heap, and every index (including the PK) points to a physical location (TID). There's no permanent clustered index; CLUSTER reorders the table once.
Read in post: Databases
Edge caseMidThe optimizer often ignores an index on a low-cardinality columnEven with an index on (status), fetching 25% of the table through a secondary index (12,500 random lookups) is usually slower than a sequential scan, so the optimizer picks the full scan. It's only worth indexing when: the value you're looking for is rare (e.g. status = 'FAILED' at 0.1%), or it's the leading column of

Even with an index on (status), fetching 25% of the table through a secondary index (12,500 random lookups) is usually slower than a sequential scan, so the optimizer picks the full scan. It's only worth indexing when:

  • the value you're looking for is rare (e.g. status = 'FAILED' at 0.1%), or
  • it's the leading column of a composite index that also serves the sort, or
  • (Postgres) you use a partial index: CREATE INDEX ... ON orders (created_at) WHERE status = 'FAILED'.
Read in post: Databases
Edge caseMidWrapping a column in a function or an implicit cast stops the index from being usedA predicate is sargable (Search ARGument ABLE) when the database can use an index to seek on it. Things that break sargability: a function on the column: DATE(col), LOWER(col), col + 1 = 5; LIKE '%abc' (leading wildcard); implicit type conversion: comparing a VARCHAR column to a number (WHERE phone = 0901...) makes MyS

A predicate is sargable (Search ARGument ABLE) when the database can use an index to seek on it. Things that break sargability:

  • a function on the column: DATE(col), LOWER(col), col + 1 = 5;
  • LIKE '%abc' (leading wildcard);
  • implicit type conversion: comparing a VARCHAR column to a number (WHERE phone = 0901...) makes MySQL convert every row to a number;
  • OR across two different columns (sometimes rescued by an index merge, but don't count on it).

If you really need to filter on an expression, use a functional index (MySQL 8.0.13+): CREATE INDEX idx ON t ((LOWER(email))). Postgres has equivalent expression indexes.

Read in post: Databases
TILSeniorMySQL 8 invisible indexes let you remove an index safelyALTER TABLE orders ALTER INDEX idxx INVISIBLE: the optimizer ignores the index but it's still maintained. If a query regresses, flip it back instantly with no rebuild. Find indexes nobody uses with sys.schemaunusedindexes (MySQL) or pgstatuserindexes (Postgres).

ALTER TABLE orders ALTER INDEX idx_x INVISIBLE: the optimizer ignores the index but it's still maintained. If a query regresses, flip it back instantly with no rebuild. Find indexes nobody uses with sys.schema_unused_indexes (MySQL) or pg_stat_user_indexes (Postgres).

Read in post: Databases
Edge caseMidPostgreSQL does not index foreign keys automatically (MySQL InnoDB does)FOREIGN KEY (customerid) REFERENCES customers(id) only creates a constraint. InnoDB requires an index on the FK column and creates one if it's missing; PostgreSQL does not: only the referenced side (the PK of customers) has an index. The result in PostgreSQL: "orders of one customer" is a full table scan, and every tim

FOREIGN KEY (customer_id) REFERENCES customers(id) only creates a constraint. InnoDB requires an index on the FK column and creates one if it's missing; PostgreSQL does not: only the referenced side (the PK of customers) has an index.

The result in PostgreSQL: "orders of one customer" is a full table scan, and every time you delete a customers row or change its key, the database scans orders to check the constraint (holding locks). When moving a schema from MySQL, add a CREATE INDEX yourself for every FK column you join or delete by.

Read in post: Databases
TILSeniorMySQL doesn't use a range scan for the row value comparison (a, b) < (?, ?)PostgreSQL lets you write WHERE (createdat, id) < (:c, :i) (a row value comparison) and uses the index well. MySQL 8.4 with the same syntax gives type: index, possiblekeys: NULL: it walks the index and filters row by row, so the deeper the cursor, the slower (the first page is still fast thanks to LIMIT). The expanded

PostgreSQL lets you write WHERE (created_at, id) < (:c, :i) (a row value comparison) and uses the index well. MySQL 8.4 with the same syntax gives type: index, possible_keys: NULL: it walks the index and filters row by row, so the deeper the cursor, the slower (the first page is still fast thanks to LIMIT). The expanded form created_at < :c OR (created_at = :c AND id < :i) gives type: range; on MySQL, write it that way.

Read in post: Databases
Trade-offSeniorOFFSET vs keyset pagination
OFFSET Keyset
Deep-page performance Degrades, O(offset) Constant
Jump to an arbitrary page Yes No (next/previous only)
Stable while data changes Can duplicate/skip Stable
Requirements A deterministic ORDER BY A unique sort key (add id as tie-breaker) and a matching index
Best for Small admin tables that need page numbers Feeds, infinite scroll, public APIs, large exports
Read in post: Databases
Edge caseMidSoft delete breaks unique constraints when a user signs up again with the same emailA user deletes the account a@x.com, signs up again, and hits a duplicate email. In MySQL, fix it with a generated column (tested): Postgres: CREATE UNIQUE INDEX ON accountuser (email) WHERE deletedat IS NULL.

A user deletes the account a@x.com, signs up again, and hits a duplicate email. In MySQL, fix it with a generated column (tested):

CREATE TABLE account_user (
  id           BIGINT AUTO_INCREMENT PRIMARY KEY,
  email        VARCHAR(255) NOT NULL,
  deleted_at   DATETIME NULL,
  active_email VARCHAR(255) AS (CASE WHEN deleted_at IS NULL THEN email END) STORED,
  UNIQUE KEY uq_user_active_email (active_email)
);

Postgres: CREATE UNIQUE INDEX ON account_user (email) WHERE deleted_at IS NULL.

Read in post: Databases
Trade-offSeniorSoft delete vs archive table, audit log or business statesThe alternatives: Archive table: move deleted rows elsewhere; the main table stays lean and uniqueness stays correct. Audit log/event for every change, then hard delete. Meaningful business states (status = 'CANCELLED', 'DEACTIVATED') instead of a generic "deleted" flag. My rule: soft delete data users may want to rest

The alternatives:

  • Archive table: move deleted rows elsewhere; the main table stays lean and uniqueness stays correct.
  • Audit log/event for every change, then hard delete.
  • Meaningful business states (status = 'CANCELLED', 'DEACTIVATED') instead of a generic "deleted" flag.

My rule: soft delete data users may want to restore in the short term, with a job that hard deletes or archives after N days.

Read in post: Databases
InterviewJuniorWhat is an index and why does it make queries faster?

An auxiliary data structure (usually a B+tree) kept sorted by some columns, so lookups take O(log n) instead of a full O(n) scan.

The trade-off is slower writes and extra storage.

Read in post: Databases
InterviewJuniorWhat's the N+1 problem?

One query loads N parent records, then each record triggers another query for related data: 1 + N queries in total.

It usually comes from ORM lazy loading. Fix it with JOIN FETCH, an entity graph, batch fetching or a DTO projection.

Read in post: Databases
InterviewJuniorWhen should you not add an index?

When it barely helps reads but still slows down every write.

  • The table is tiny (a full scan is cheap anyway).
  • The column has low selectivity and doesn't serve a sort.
  • The table is write-heavy and queries on that column are rare.
  • The new index is a prefix of an existing one ((a) is redundant next to (a, b)).

Every index slows down INSERT/UPDATE and takes space in the buffer pool.

Read in post: Databases
InterviewMidWhich queries can a composite index (a, b, c) serve?

Those using a leftmost prefix: a, a,b, a,b,c.

Plus ordering by the next column when the previous ones are equality matches. It doesn't help b or c on their own. After a range condition on b, c can no longer be used for seeking.

Read in post: Databases
InterviewMidWhat's a covering index, and how do you spot one in EXPLAIN?

An index that contains every column the query needs, so the database never visits the table.

MySQL shows Using index in Extra; Postgres shows Index Only Scan. In InnoDB the PK is always in secondary indexes, so it counts as covered.

Read in post: Databases
InterviewMidWhy is a large OFFSET slow, and what do you use instead?

The database reads and discards offset rows before returning anything, so the cost grows linearly with page depth. Use keyset pagination instead.

Keyset: WHERE (sort_key, id) < (last_sort_key, last_id) ORDER BY sort_key DESC, id DESC LIMIT n with a matching index. On MySQL, expand it into the OR form to get a range scan.

Read in post: Databases
InterviewMidAn API suddenly got slow. How do you investigate the SQL?

Get the real SQL and parameters, run EXPLAIN ANALYZE, fix based on evidence, then measure again on production-sized data.

  • Get the real query from the slow query log or APM.
  • EXPLAIN ANALYZE: the most expensive step, and estimated vs actual rows; if they're far apart, refresh statistics first.
  • Check type (any ALL?), key/key_len (how many index columns are used), Extra (Using filesort, Using temporary), sargability and the composite index column order.
Read in post: Databases
InterviewSeniorWhy is a UUID v4 primary key bad for InnoDB, and what would you use instead?

InnoDB orders rows physically by the PK; a random UUID v4 scatters inserts across the tree and is copied into every secondary index. Use an increasing PK.

  • Random inserts cause page splits, half-empty pages, and a much larger set of "hot" pages the buffer pool must hold.
  • The 16-byte key (36 bytes if stored as text) is copied into every secondary index.
  • Options: a BIGINT AUTO_INCREMENT internal PK plus a unique UUID column for external use, or a time-ordered id such as UUIDv7/ULID stored as BINARY(16).
  • MySQL's UUID_TO_BIN(uuid, 1) swaps the time parts of a UUID v1 so it becomes increasing.
Read in post: Databases
InterviewSeniorAre you in favour of soft delete?

It depends on the data: yes for data that may need restoring or must keep historical references, provided you deal with its costs.

  • Automatic filtering (@SQLRestriction/@SoftDelete).
  • Uniqueness among active rows (partial index or generated column).
  • Indexes that account for deleted_at.
  • An archive/hard-delete job after N days, and compliance with requests to erase personal data.

Often a meaningful business state (CANCELLED) or an archive table plus an audit log beats a generic deleted flag.

Read in post: Databases
Trade-offJuniorRecursion vs iterationPros: short, readable code when the problem is naturally recursive (trees, divide and conquer, backtracking). Cons: it can be slow (call overhead, repeated work), harder to follow, prone to infinite recursion if the base case is wrong, and it uses stack: depth d costs O(d) memory. Rule of thumb in Java: recursion is fi
  • Pros: short, readable code when the problem is naturally recursive (trees, divide and conquer, backtracking).
  • Cons: it can be slow (call overhead, repeated work), harder to follow, prone to infinite recursion if the base case is wrong, and it uses stack: depth d costs O(d) memory.
  • Rule of thumb in Java: recursion is fine when the depth is O(log n) or small and bounded; when depth grows linearly with the input, use a loop.
Read in post: Recursion, binary search and a few classic algorithms
Edge caseSeniorDeep recursion overflows the JVM stack, and Java has no tail-call optimizationEach thread gets a fixed-size stack, set with -Xss (e.g. -Xss1m), about 1 MB by default on 64-bit Linux. Recurse too deep and you get a StackOverflowError. It's an Error, not an Exception, and you shouldn't catch it as a workaround. The maximum depth depends on frame size (parameters, locals, whether the code is JIT-co
  • Each thread gets a fixed-size stack, set with -Xss (e.g. -Xss1m), about 1 MB by default on 64-bit Linux. Recurse too deep and you get a StackOverflowError. It's an Error, not an Exception, and you shouldn't catch it as a workaround.
  • The maximum depth depends on frame size (parameters, locals, whether the code is JIT-compiled). An empty recursive method on default settings blew up at around 20,000 levels when I tried it. So recursion of depth n = 10⁵ (walking a long linked list, DFS on a path-shaped graph) is not safe.
  • Java has no tail-call optimization (it never reuses the frame for a call in the last position). return f(n - 1, acc) still costs one frame per level. To be safe, switch to a loop or an explicit stack (ArrayDeque) on the heap.
  • Running the work in a dedicated Thread with a bigger stack (new Thread(null, task, "deep", 512L * 1024 * 1024)) is a patch, not a design.
  • O(log n) depth (binary search, merge sort, a properly written quicksort) is safe: even n = 10⁹ is only about 30 levels.
Read in post: Recursion, binary search and a few classic algorithms
Trade-offMidMemoization: extra memory for less timeWhen recursion calls the same subproblem many times, memoization stores each subproblem's result in a table (a map or an array) and returns it immediately next time. Complexity often drops from exponential to polynomial, at the cost of memory for the table. This is top-down dynamic programming; a loop from small subpro

When recursion calls the same subproblem many times, memoization stores each subproblem's result in a table (a map or an array) and returns it immediately next time. Complexity often drops from exponential to polynomial, at the cost of memory for the table.

This is top-down dynamic programming; a loop from small subproblems up to the big one is bottom-up. Example, Fibonacci (section 3.2): naive is O(2ⁿ), memoized is O(n) time and O(n) memory, and bottom-up keeping the last two values needs O(1) memory.

Read in post: Recursion, binary search and a few classic algorithms
Edge caseMidHashMap.computeIfAbsent throws ConcurrentModificationException in recursive memoizationSince Java 9, if the function passed to computeIfAbsent modifies the same map (which a recursive call does), HashMap throws ConcurrentModificationException. Use get then put as in fibMemo in section 3.2, or use an array.

Since Java 9, if the function passed to computeIfAbsent modifies the same map (which a recursive call does), HashMap throws ConcurrentModificationException. Use get then put as in fibMemo in section 3.2, or use an array.

Read in post: Recursion, binary search and a few classic algorithms
Trade-offMidLinear vs binary searchLinear search: O(n), no sorting needed, works on anything you can iterate sequentially (linked lists included). Binary search: O(log n) but needs sorted data with O(1) random access. Small arrays (a few dozen elements): linear search is often faster, because sequential access is cache-friendly and its branches are easy
  • Linear search: O(n), no sorting needed, works on anything you can iterate sequentially (linked lists included).
  • Binary search: O(log n) but needs sorted data with O(1) random access.
  • Small arrays (a few dozen elements): linear search is often faster, because sequential access is cache-friendly and its branches are easy to predict.
Read in post: Recursion, binary search and a few classic algorithms
Edge caseMidmid = (low + high) / 2 overflows in binary search on huge arraysBoth copies of the slides write mid = (low + high) / 2. Once low + high exceeds Integer.MAXVALUE (arrays above roughly a billion elements), the sum overflows to a negative number and you get an ArrayIndexOutOfBoundsException. The JDK's own Arrays.binarySearch shipped with this bug for years until it was found and fixed

Both copies of the slides write mid = (low + high) / 2. Once low + high exceeds Integer.MAX_VALUE (arrays above roughly a billion elements), the sum overflows to a negative number and you get an ArrayIndexOutOfBoundsException. The JDK's own Arrays.binarySearch shipped with this bug for years until it was found and fixed in 2006. Two correct forms:

  • low + (high - low) / 2
  • (low + high) >>> 1 (an unsigned right shift treats the overflowed sum as an unsigned 32-bit value)
Read in post: Recursion, binary search and a few classic algorithms
TILMidBinary search works on any monotonic predicate, not just arraysBinary search works on any monotonic predicate (one that only goes one way, false then true), like "the smallest capacity that finishes within T seconds", or git bisect hunting for the commit that broke the build. Database B-tree indexes rely on the same idea of narrowing a range.

Binary search works on any monotonic predicate (one that only goes one way, false then true), like "the smallest capacity that finishes within T seconds", or git bisect hunting for the commit that broke the build. Database B-tree indexes rely on the same idea of narrowing a range.

Read in post: Recursion, binary search and a few classic algorithms
Edge caseJuniorArray-based iterative Fibonacci crashes for n = 0The slides use an array f[0..n]: for n = 0 it creates new int[1] and then assigns f[1] = 1, which throws ArrayIndexOutOfBoundsException. You only need the last two values anyway, so memory is O(1):

The slides use an array f[0..n]: for n = 0 it creates new int[1] and then assigns f[1] = 1, which throws ArrayIndexOutOfBoundsException. You only need the last two values anyway, so memory is O(1):

static long fib(int n) {
    if (n < 0) throw new IllegalArgumentException("n must be >= 0");
    if (n == 0) return 0;
    long prev = 0, cur = 1;
    for (int i = 2; i <= n; i++) {
        long next = prev + cur;
        prev = cur;
        cur = next;
    }
    return cur;
}
Read in post: Recursion, binary search and a few classic algorithms
Edge caseJuniorJava integer overflow wraps silently: Fibonacci overflows int at F(47)An int holds up to F(46) = 1,836,311,903; F(47) overflows. A long holds up to F(92). Beyond that, use BigInteger, or the problem will ask for the answer modulo something (usually 10⁹ + 7). Java doesn't complain about integer overflow, it silently wraps around; use Math.addExact if you want an exception.

An int holds up to F(46) = 1,836,311,903; F(47) overflows. A long holds up to F(92). Beyond that, use BigInteger, or the problem will ask for the answer modulo something (usually 10⁹ + 7). Java doesn't complain about integer overflow, it silently wraps around; use Math.addExact if you want an exception.

Read in post: Recursion, binary search and a few classic algorithms
Edge caseJuniorRecursive palindrome check with substring and a len == 1 base case crashes and is O(n²)The slides' recursive version compares the first and last characters, then recurses on substring(1, len - 1). Two bugs: 1. The only base case is len == 1. An even-length string like "abba" shrinks to "bb" and then "", where charAt(0) throws StringIndexOutOfBoundsException; an empty string passed in fails the same way.

The slides' recursive version compares the first and last characters, then recurses on substring(1, len - 1). Two bugs:

  1. The only base case is len == 1. An even-length string like "abba" shrinks to "bb" and then "", where charAt(0) throws StringIndexOutOfBoundsException; an empty string passed in fails the same way. The right base case is len <= 1.
  2. Every level's substring copies O(n) characters (since Java 7u6 substring copies instead of sharing the backing array), adding up to O(n²) time and memory.

Fix: pass two indices i, j instead of slicing, and stop when i >= j.

Read in post: Recursion, binary search and a few classic algorithms
InterviewJuniorWhat's a base case, and what happens without one?

It's the smallest case that returns an answer directly without recursing. Without it the JVM throws StackOverflowError.

Without a base case, or if calls don't move toward it, the recursion never ends until the stack fills up.

Read in post: Recursion, binary search and a few classic algorithms
InterviewJuniorWhat do you need before you can use binary search?

Sorted data (more generally, a monotonic condition) and O(1) random access.

On a linked list binary search loses its advantage, because just reaching the middle costs O(n).

Read in post: Recursion, binary search and a few classic algorithms
InterviewMidWhat's the complexity of naive recursive Fibonacci, and how do you improve it?

About O(φⁿ) with φ ≈ 1.618 (commonly called O(2ⁿ)) because subproblems are recomputed; memoization brings it to O(n).

Bottom-up DP is also O(n) time; keeping just two variables makes memory O(1). Matrix exponentiation or fast doubling gives O(log n).

Read in post: Recursion, binary search and a few classic algorithms
InterviewMidWhat's wrong with mid = (low + high) / 2?

Integer overflow when low + high > Integer.MAX_VALUE, which produces a negative index.

Fix it with low + (high - low) / 2 or (low + high) >>> 1. The JDK had exactly this bug in Arrays.binarySearch.

Read in post: Recursion, binary search and a few classic algorithms
InterviewMidHow do you count the space complexity of a recursive function?

Add the call stack depth: depth d costs O(d), on top of any memory you explicitly allocate.

Recursive factorial(n) is O(n) space even though it creates no arrays; recursive binary search is O(log n); the iterative versions are O(1).

Read in post: Recursion, binary search and a few classic algorithms
InterviewMidWhat does Arrays.binarySearch return when the key isn't found?

-(insertionPoint) - 1, where insertionPoint is where the key would go to keep the array sorted.

It's always negative when not found, even when insertionPoint is 0, so check >= 0 to know whether it was found. With duplicates, there's no guarantee which match you get.

Read in post: Recursion, binary search and a few classic algorithms
InterviewSeniorDoes Java optimize tail calls? What does that mean for recursive code?

No. Tail recursion still costs O(n) stack, so linearly deep recursion has to be rewritten as a loop.

The JVM keeps full stack frames (partly for stack traces and the security model). Recursion whose depth grows linearly with the input (long lists, degenerate trees, DFS on large graphs) can throw StackOverflowError in production; rewrite it as a loop or use an ArrayDeque as an explicit stack on the heap. Bumping -Xss is only a patch.

Read in post: Recursion, binary search and a few classic algorithms
InterviewSeniorIs it OK to catch StackOverflowError and carry on?

Generally no: it's an Error, signaling a state the application shouldn't try to recover from.

By the time you catch it the stack is nearly exhausted, so anything in the catch block (logging, allocation) can fail again, and invariants (locks, half-finished state) may already be broken. The right fix is to bound the input depth or rewrite it without recursion.

Read in post: Recursion, binary search and a few classic algorithms
InterviewSeniorAn API has to check whether lots of numbers are prime. How would you design it?

It depends on the range: a precomputed Sieve of Eratosthenes for small numbers, deterministic Miller-Rabin for numbers up to 64 bits.

  • Small numbers (≤ 10⁷) queried often: build the sieve once at startup (a ~1.25 MB bitset), then each query is O(1).
  • Up to 64 bits: deterministic Miller-Rabin with a fixed set of bases, or BigInteger.isProbablePrime.
  • Trial division up to √n only makes sense for a few small numbers.
  • Spell out the trade-off between memory, startup time and per-request latency.
Read in post: Recursion, binary search and a few classic algorithms
Edge caseJuniornextLine() right after nextInt() returns an empty stringThe user types 25⏎. nextInt() reads 25 but leaves the ⏎ in the buffer (a temporary memory area holding data not yet read). The next nextLine() hits that ⏎ immediately and returns an empty string, so it looks as if the input was "skipped". Two fixes:

The user types 25⏎. nextInt() reads 25 but leaves the ⏎ in the buffer (a temporary memory area holding data not yet read). The next nextLine() hits that ⏎ immediately and returns an empty string, so it looks as if the input was "skipped". Two fixes:

// Fix 1: consume the rest of the line
int age = in.nextInt();
in.nextLine();                          // swallow the leftover line break
String name = in.nextLine();

// Fix 2 (my preference): always read whole lines and parse them yourself
int age2 = Integer.parseInt(in.nextLine().trim());
Read in post: Java basics
Trade-offMidScanner vs BufferedReader for reading inputAlways reading whole lines and parsing them yourself is more consistent than mixing nextInt() with nextLine(), and lets you catch NumberFormatException right where you parse. For very large inputs (competitive programming, files of several hundred MB), Scanner is slow because it uses regular expressions; use a Buffered

Always reading whole lines and parsing them yourself is more consistent than mixing nextInt() with nextLine(), and lets you catch NumberFormatException right where you parse. For very large inputs (competitive programming, files of several hundred MB), Scanner is slow because it uses regular expressions; use a BufferedReader and split the lines yourself.

Read in post: Java basics
Edge caseMidPrintWriter never throws on a failed writeThree production details the slides skip: 1. Always close resources. Without close(), buffered data can be lost and file descriptors leak. Always use try-with-resources. 2. PrintWriter swallows errors: it never throws IOException on a failed write; it only sets a flag you have to check with checkError(). For important

Three production details the slides skip:

  1. Always close resources. Without close(), buffered data can be lost and file descriptors leak. Always use try-with-resources.
  2. PrintWriter swallows errors: it never throws IOException on a failed write; it only sets a flag you have to check with checkError(). For important data, use Files.newBufferedWriter, which does throw.
  3. Encoding: specify StandardCharsets.UTF_8. Since Java 18 UTF-8 is the default (JEP 400), but code running on older JDKs still depends on the OS settings.
Read in post: Java basics
Trade-offMidFiles.readAllLines vs Files.linesreadAllLines is concise and closes itself, but loads everything into memory; Files.lines is lazy so RAM stays constant, but it must be closed.

readAllLines is concise and closes itself, but loads everything into memory; Files.lines is lazy so RAM stays constant, but it must be closed.

Path path = Path.of("data.txt");
List<String> lines = Files.readAllLines(path);           // small file: load it all into memory
try (Stream<String> stream = Files.lines(path)) {        // large file: read lazily, line by line
    long errors = stream.filter(l -> l.contains("ERROR")).count();
}
Files.writeString(Path.of("out.txt"), "hello\n");        // write a string in one call
Read in post: Java basics
InterviewJuniorWhy does nextLine() return an empty string right after nextInt()?

Because nextInt() reads only the number and leaves the line break in the buffer.

nextLine() immediately reads up to that line break and returns an empty string. Either add an extra nextLine() to consume it, or always read whole lines and parse them yourself.

Read in post: Java basics
InterviewJuniorDoes FileWriter overwrite or append? How do you append?

It overwrites by default; to append use new FileWriter(path, true) or pass StandardOpenOption.APPEND.

FileWriter, PrintWriter and Files.write/writeString all create a new file or overwrite the existing one. With Files: Files.writeString(path, text, StandardOpenOption.CREATE, StandardOpenOption.APPEND). For real logging, use a logging library, which also handles appending, file rotation and concurrent writes from many threads.

Read in post: Java basics
InterviewMidWhy use try-with-resources for files?

So close() always runs, even on an exception: buffers get flushed and file descriptors get released.

If both the body and close() throw, the close() exception is attached to the primary one as a suppressed exception, so the original error isn't lost. Any AutoCloseable works with it.

Read in post: Java basics
InterviewMidFiles.readAllLines, Files.lines or BufferedReader: which do you pick?

Small file: readAllLines/readString; large file: Files.lines; per-line control: BufferedReader.

  • readAllLines/readString load the whole file into memory, are concise and close the file themselves: fine for small files (config, a few MB).
  • Files.lines returns a lazy Stream<String> with constant memory however big the file is, but it must be closed with try-with-resources.
  • BufferedReader.readLine in a loop is lazy too, and suits counting lines, per-line error handling or stopping early.
  • Specify the charset in all three.
Read in post: Java basics
InterviewMidWhy should you specify a charset when reading or writing text? What changed in Java 18?

Because a file only holds bytes: decode them with the wrong charset and you get wrong text with no exception. Java 18 (JEP 400) made UTF-8 the default on every platform.

Vietnamese turning into Viá»t is the classic example. Before Java 18, FileReader, FileWriter, Scanner(File) and String.getBytes() used the OS default encoding, so the same code worked on macOS and broke on Windows. Still, write StandardCharsets.UTF_8 explicitly so the code is correct on older JDKs and the intent is obvious.

Read in post: Java basics
InterviewSeniorHow would you process a 20 GB log file?

Stream it lazily line by line with Files.lines or a BufferedReader so memory stays constant; never readAllLines, which blows the heap.

Specify the charset. If speed matters, split the file into byte ranges and process them in parallel, use memory-mapped I/O (FileChannel.map), or move to a stream- or batch-processing tool. Measure before you optimize.

Read in post: Java basics
InterviewSeniorHow do you write a file so other processes never read a half-written version?

Write to a temp file in the same directory, close it, then Files.move(tmp, target, ATOMIC_MOVE, REPLACE_EXISTING).

The rename is atomic at the OS level, so readers see either the old file or the complete new one. If you must be sure the data reached the disk before the rename (to survive a power cut), call FileChannel.force(true) on the temp file. A temp file in another directory (such as /tmp) may be on a different filesystem, and then the move is no longer atomic.

Read in post: Java basics
TILMidEnumSet has two implementations, picked automatically by sizeEnumSet is an abstract class; its factory methods (of, noneOf, allOf) pick an implementation by the number of constants. Up to 64 constants get a RegularEnumSet, which stores the whole set in one long. Larger enums get a JumboEnumSet backed by a long[]. So an EnumSet of permissions or weekdays is just a 64-bit number,

EnumSet is an abstract class; its factory methods (of, noneOf, allOf) pick an implementation by the number of constants. Up to 64 constants get a RegularEnumSet, which stores the whole set in one long. Larger enums get a JumboEnumSet backed by a long[]. So an EnumSet of permissions or weekdays is just a 64-bit number, and union or intersection is a single OR/AND.

Read in post: Enums in production
Edge caseMidEnumType.ORDINAL stores the declaration position, so reordering the enum corrupts existing dataThe column holds 0, 1, 2.... Insert PAID between PENDING and SHIPPED, and every old SHIPPED row (stored as 1) now reads back as PAID. No exception, the data is silently wrong, usually found when customers complain. Removing a constant is worse: everything after it shifts. Without a backup, it can't be undone. Always us

The column holds 0, 1, 2.... Insert PAID between PENDING and SHIPPED, and every old SHIPPED row (stored as 1) now reads back as PAID. No exception, the data is silently wrong, usually found when customers complain. Removing a constant is worse: everything after it shifts. Without a backup, it can't be undone. Always use @Enumerated(EnumType.STRING) or an AttributeConverter with dedicated codes, and consider a CHECK constraint in the database to reject unknown values.

Read in post: Enums in production
Trade-offSeniorEnumType.STRING or an AttributeConverter with stable codesSTRING: no extra code, readable straight from SQL. The cost: Java constant names become a contract with the database; a rename is a migration, and the column is wider than a short code. Converter + dedicated codes: names in code change freely, database codes stay short and stable, and can match a legacy system's codes.
  • STRING: no extra code, readable straight from SQL. The cost: Java constant names become a contract with the database; a rename is a migration, and the column is wider than a short code.
  • Converter + dedicated codes: names in code change freely, database codes stay short and stable, and can match a legacy system's codes. The cost: more code, codes must be unique (toUnmodifiableMap fails at startup on duplicates); JPQL comparing against constants still works, but anyone reading raw SQL needs the code table.
  • ORDINAL is almost never right; saving a few bytes isn't worth the risk of corrupted data.
Read in post: Enums in production
Edge caseSeniorAdding an enum value to an API response can break old clientsA Java client using default Jackson settings throws InvalidFormatException on an unknown enum string, so the whole response fails to parse. Clients with an exhaustive switch (Kotlin when, a TypeScript union, Java generated from OpenAPI) may break logic or throw. What to do: Server: state in the API docs that the enum m

A Java client using default Jackson settings throws InvalidFormatException on an unknown enum string, so the whole response fails to parse. Clients with an exhaustive switch (Kotlin when, a TypeScript union, Java generated from OpenAPI) may break logic or throw. What to do:

  • Server: state in the API docs that the enum may gain values; never rename or remove, only deprecate; when needed, start emitting a new value only after clients have upgraded.
  • Client (tolerant reader — a reader that accepts unexpected data instead of crashing): add an UNKNOWN constant marked @JsonEnumDefaultValue, enable DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, and handle UNKNOWN safely.
  • Incoming requests are the opposite: reject unknown values with a 400 instead of quietly mapping them to UNKNOWN.
Read in post: Enums in production
TILMidEnum deserialization uses only the name; fields don't travelJava serialization writes an enum constant as its name and reads it back with Enum.valueOf, so you always get the very instance already in the JVM (deserialized == Singleton.INSTANCE is true). Fields aren't written: serialize while a field is 42, change it to 7, deserialize, and you see 7. That's why enum singletons su

Java serialization writes an enum constant as its name and reads it back with Enum.valueOf, so you always get the very instance already in the JVM (deserialized == Singleton.INSTANCE is true). Fields aren't written: serialize while a field is 42, change it to 7, deserialize, and you see 7. That's why enum singletons survive serialization, and why a serialVersionUID or readResolve in an enum does nothing.

Read in post: Enums in production
InterviewMidWhy are EnumMap and EnumSet faster than HashMap/HashSet for enum keys?

Because they're built on ordinal: EnumSet is a bit vector and EnumMap is an array, so there's no hashing and no collisions.

For enums with up to 64 constants an EnumSet is a single long with one bit per constant, so add, contains, union and intersection are bit operations. EnumMap indexes an array by ordinal and creates no Entry per element. Both iterate in declaration order. In exchange, they don't accept null and aren't thread-safe.

Read in post: Enums in production
InterviewMidYou store an EnumSet in the database as a bitmask. What do you watch out for?

Every constant needs an explicit, fixed bit position, never ordinal(), and you accept that bitmasks are hard to query.

With ordinal(), inserting or reordering constants changes the meaning of every stored mask. Reject duplicate bits when the enum loads; when reading an unknown bit, fail or log clearly (newer code may have written it). A long holds only 64 permissions. Bitmasks are hard to query (perms & 8 <> 0 can't use an index) and hard to read while debugging; to filter by permission, a join table or a string-array column is usually better.

Read in post: Enums in production
InterviewMidHow does Jackson serialize enums? How do you make the JSON use your own codes instead of constant names?

By default Jackson writes name() and reads back by exact name; for custom codes, use @JsonValue to write and @JsonCreator to read.

On an unknown value Jackson throws InvalidFormatException. You can enable WRITE_ENUMS_USING_TO_STRING/READ_ENUMS_USING_TO_STRING to use toString(). For stable custom codes, put @JsonValue on a method returning the code and add a static factory annotated with @JsonCreator. For clients that must tolerate new values, add an UNKNOWN constant with @JsonEnumDefaultValue and enable READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE.

Read in post: Enums in production
InterviewSeniorHow do you store an enum in a database, and how do you evolve it once there's existing data?

Store it as STRING or through a converter with stable codes, never ORDINAL; evolve it migration-first, and rename with expand/contract.

  • ORDINAL: inserting or removing a constant shifts the numbers, and old data reads back wrong without any error.
  • STRING survives reordering but ties Java constant names to the data; to decouple completely, give the enum a stable code and use an AttributeConverter.
  • New constant: run the migration (update the CHECK constraint or the database ENUM type) before deploying code that writes it, and make sure the old version still running during a rolling deploy doesn't crash on the new value.
  • Rename: add the new value, migrate the data, then drop the old one. Never remove a constant while data still uses it.
Read in post: Enums in production
InterviewSeniorWhy is an enum considered the best way to write a singleton? What are the downsides?

Because the JVM guarantees exactly one instance against concurrency, reflection and serialization; the downside is global state that's hard to replace in tests.

Enum constants are created exactly once during class initialization, so it's thread-safe without locks. Reflection can't create extra instances. Deserialization always returns the existing instance because enums are serialized by name only. Downsides: it can't extend another class, it's initialized when the enum loads, and it's global state that's hard to replace in tests. In Spring, a singleton should usually be a container-managed bean so it can be injected and mocked; the enum singleton suits dependency-free utilities.

Read in post: Enums in production
InterviewSeniorYou add a new value to an enum returned by a REST API. Is that a breaking change? How do you design for it?

It can be: clients that don't know the new value may crash while parsing, so the contract must say the enum is extensible and clients must read tolerantly.

  • A client on default Jackson settings throws InvalidFormatException; clients with exhaustive switches or code generated from OpenAPI may break.
  • The API contract states that the enum is extensible; clients act as tolerant readers (an UNKNOWN constant with @JsonEnumDefaultValue plus READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE).
  • The server only adds, never renames or removes, and can start emitting a new value after major clients have upgraded or behind an API version.
  • Incoming requests are still validated strictly, with a 400 for unknown values.
Read in post: Enums in production
Trade-offJuniorEnum or String/int constantsEnum: the compiler rejects unknown values, switch checks exhaustiveness, you can attach fields and methods, and you get EnumSet/EnumMap. The cost: the set is fixed at compile time, so adding a value means rebuilding and redeploying. String/int constants: flexible, but the compiler can't tell a valid string from any oth
  • Enum: the compiler rejects unknown values, switch checks exhaustiveness, you can attach fields and methods, and you get EnumSet/EnumMap. The cost: the set is fixed at compile time, so adding a value means rebuilding and redeploying.
  • String/int constants: flexible, but the compiler can't tell a valid string from any other; all validation moves to runtime.
  • Use an enum when the set is decided by code and rarely changes (order status, payment type, system permissions). When it's decided by data (product categories, regions an admin can add), keep it in a database table.
Read in post: Enums in Java
Edge caseMidAn enum constructor can't use the enum's own static fieldsEnum constants are created before the enum's other static fields are initialized: Using a static field directly in the constructor: compile error illegal reference to static field from initializer. Going through a static method: compiles, but fails at runtime with ExceptionInInitializerError (caused by a NullPointerExc

Enum constants are created before the enum's other static fields are initialized:

  • Using a static field directly in the constructor: compile error illegal reference to static field from initializer.
  • Going through a static method: compiles, but fails at runtime with ExceptionInInitializerError (caused by a NullPointerException, because the map is still null).
  • Referencing a constant declared later in a constructor argument (PENDING(EnumSet.of(SHIPPED))): illegal forward reference.

The fix: build lookup or transition tables in a static { ... } block placed after the constants, or use a method with a switch on this.

Read in post: Enums in Java
Trade-offSeniorStrategy as an enum or as an interface with beansEnum strategy: a closed set known at compile time, stateless, no dependencies (fee formulas, operators, rounding rules). Cheap, no configuration, and switch checks exhaustiveness. Interface with multiple Spring beans: when a strategy needs dependencies (repositories, HTTP clients, config), needs mocking in tests, or th
  • Enum strategy: a closed set known at compile time, stateless, no dependencies (fee formulas, operators, rounding rules). Cheap, no configuration, and switch checks exhaustiveness.
  • Interface with multiple Spring beans: when a strategy needs dependencies (repositories, HTTP clients, config), needs mocking in tests, or the set is open (plugins, a new payment provider without touching an enum). Look them up through a Map<Type, Strategy> injected by the container.
  • Signs you picked wrong: the enum calls a static ApplicationContext.getBean(...) or holds a mutable field so something can be "injected". Switch to beans and keep the enum only as the key for choosing one.
Read in post: Enums in Java
Edge caseMidvalueOf throws, is case-sensitive, and your own toUpperCase depends on the localeEnum.valueOf throws IllegalArgumentException for an unknown name and NullPointerException for null; it never returns null. try/catch on the normal path is slow and hard to read; look up through a prebuilt Map. It matches name() exactly: "shipped" and " SHIPPED " both fail. Always use toUpperCase(Locale.ROOT). Under a T
  • Enum.valueOf throws IllegalArgumentException for an unknown name and NullPointerException for null; it never returns null. try/catch on the normal path is slow and hard to read; look up through a prebuilt Map.
  • It matches name() exactly: "shipped" and " SHIPPED " both fail.
  • Always use toUpperCase(Locale.ROOT). Under a Turkish locale, "title".toUpperCase() gives "TİTLE" (dotted capital I), and valueOf fails only on servers configured with that locale.
  • Spring converts query parameters to enums via valueOf; unknown values become MethodArgumentTypeMismatchException, which you should map to a 400 in your exception handler.
Read in post: Enums in Java
Edge caseMidvalues() allocates a new array on every callJava arrays are always mutable, so values() has to return a copy ($VALUES.clone()) so nobody can modify the list of constants: Color.values() == Color.values() is false. Calling values() in a hot loop or on every request parse is wasted allocation. Compute it once, e.g. private static final List<Color ALL = List.of(val

Java arrays are always mutable, so values() has to return a copy ($VALUES.clone()) so nobody can modify the list of constants: Color.values() == Color.values() is false. Calling values() in a hot loop or on every request parse is wasted allocation. Compute it once, e.g. private static final List<Color> ALL = List.of(values());, or build a lookup Map instead of scanning values() to find a constant by field.

Read in post: Enums in Java
Trade-offMidShould a switch on an enum have a defaultNo default (switch expression): the compiler points to every place to update when a constant is added. The default choice for enums your own service owns. With default: turns that check off; new constants silently fall into default, usually wrong business behavior nobody notices. The reasonable exception: an external e
  • No default (switch expression): the compiler points to every place to update when a constant is added. The default choice for enums your own service owns.
  • With default: turns that check off; new constants silently fall into default, usually wrong business behavior nobody notices.
  • The reasonable exception: an external enum that may gain values you don't control (a library enum, an UNKNOWN value from deserialization). Then write a default, but make it loud: log a warning with the value, bump a metric, or throw a clear exception, instead of returning a "sensible" value.
Read in post: Enums in Java
Trade-offSeniorEnum or sealed interface with recordsEnum: each value is a singleton with the same fields and no per-use state. You get values(), EnumSet/EnumMap, and simple persistence and JSON (a single string). Sealed interface + records: each case is its own type with its own data and many instances. Switches stay exhaustive, but there's no values(), and persistence
  • Enum: each value is a singleton with the same fields and no per-use state. You get values(), EnumSet/EnumMap, and simple persistence and JSON (a single string).
  • Sealed interface + records: each case is its own type with its own data and many instances. Switches stay exhaustive, but there's no values(), and persistence or JSON needs design work (a discriminator column, @JsonTypeInfo).
  • Rule of thumb: "which value from a fixed list is this" calls for an enum; "which case is this, and what data does it carry" calls for sealed + records. They combine well: a sealed hierarchy can have enum-typed fields.
Read in post: Enums in Java
InterviewJuniorWhy use an enum instead of static final String constants?

Because an enum is a distinct type: the compiler only accepts the declared values, while with String any string compiles.

With String, mistakes only show up at runtime. Enums can also be compared with ==, used in switches with exhaustiveness checks, carry fields and methods per value, and come with the fast EnumSet/EnumMap.

Read in post: Enums in Java
InterviewJuniorCan an enum have a constructor? Why can't you call new on it?

Yes, but the constructor is always implicitly private: the only instances are the constants the JVM creates once when the enum is loaded.

Enums have fields, constructors and methods like classes. You can't new one and can't create one via reflection (Cannot reflectively create enum objects). An enum can't extend another class because it already implicitly extends Enum, though it can implement interfaces.

Read in post: Enums in Java
InterviewJuniorDo you compare enum values with == or equals?

==: each constant is a single instance, so == is semantically correct, fast and null-safe.

status == Status.ACTIVE doesn't throw when status is null. == is also type-checked at compile time: comparing two different enum types with == is a compile error, whereas equals silently returns false.

Read in post: Enums in Java
InterviewMidWhat does Status.valueOf("active") return when the constant is named ACTIVE? How do you parse enums from user input?

It throws IllegalArgumentException, because valueOf matches name() exactly and is case-sensitive; null throws NullPointerException.

For external input, prebuild a Map<String, Status> (or one keyed by a dedicated code), normalize with strip() and toUpperCase(Locale.ROOT), and return an Optional. In the web layer, map invalid values to a 400 rather than letting them become a 500.

Read in post: Enums in Java
InterviewMidA switch expression on an enum has no default. What happens when you add a new constant?

If the calling code is recompiled: a compile error, which is good. If it isn't rebuilt: a MatchException at runtime.

  • Recompiled: "the switch expression does not cover all possible input values"; the compiler points to every place that needs handling.
  • The enum lives in a library that gets upgraded without rebuilding the caller: hitting the new constant makes the switch expression throw MatchException (Java 21; previously IncompatibleClassChangeError).
  • Adding a default turns the check off, so only do it for enums owned by someone else, and make the default branch fail loudly.
Read in post: Enums in Java
InterviewSeniorWhen do you choose a sealed interface with records over an enum?

When the cases carry different data; for a plain fixed list of same-shaped values, stick with an enum.

For example a card payment needs the last four digits, a bank transfer an account number, a wallet a provider. An enum forces every constant to have the same fields and be a singleton, which ends in a pile of nullable fields. A sealed interface with records gives each case its own type and data, allows many instances, and pattern-matching switches are still checked for exhaustiveness. You give up values() and EnumSet/EnumMap, and persistence or JSON needs a discriminator.

Read in post: Enums in Java
Trade-offJuniorChecked vs unchecked exceptionsThe group you pick decides what the caller has to do:

The group you pick decides what the caller has to do:

Checked Unchecked
Which classes Exception except the RuntimeException branch RuntimeException, Error and subclasses
Checked by the compiler? Yes: you must catch it or declare it with throws No
Typical meaning External, recoverable failures: I/O, network, files Bugs and contract violations: nulls, bad indexes, bad arguments
Examples IOException, SQLException, InterruptedException NullPointerException, IllegalStateException
Read in post: Java exceptions
Edge caseJuniorA checked exception does not have to be inside a try-catchThe compiler's rule is "catch or declare": catch it, or declare it with throws and make it the caller's problem. And "unchecked = logic error" only holds for RuntimeException; Error is unchecked too, but it isn't a bug in your logic.

The compiler's rule is "catch or declare": catch it, or declare it with throws and make it the caller's problem. And "unchecked = logic error" only holds for RuntimeException; Error is unchecked too, but it isn't a bug in your logic.

Read in post: Java exceptions
TILMidChecked vs unchecked exists only in the compilerAt the bytecode level the JVM doesn't distinguish checked from unchecked; it is purely a Java compiler rule. That's why Kotlin, Scala and Lombok's @SneakyThrows can throw checked exceptions without declaring them.

At the bytecode level the JVM doesn't distinguish checked from unchecked; it is purely a Java compiler rule. That's why Kotlin, Scala and Lombok's @SneakyThrows can throw checked exceptions without declaring them.

Read in post: Java exceptions
Edge caseMidA return in finally swallows the exception from tryA return (or throw) in finally overrides whatever the try produced; the original exception vanishes without a trace. Never return from finally.
static int trap() {
    try {
        throw new IllegalStateException("boom");
    } finally {
        return 42;   // swallows the exception; the method returns 42
    }
}

A return (or throw) in finally overrides whatever the try produced; the original exception vanishes without a trace. Never return from finally.

Read in post: Java exceptions
Trade-offMidtry-with-resources vs closing resources by hand in finallyAnything that implements AutoCloseable should be opened with try-with-resources instead of being closed by hand in finally: Resources are closed in reverse order of opening. If both the body and close() throw, the body's exception is primary and the close() failure is attached via getSuppressed() (suppressed = carried

Anything that implements AutoCloseable should be opened with try-with-resources instead of being closed by hand in finally:

try (var conn = dataSource.getConnection();
     var ps = conn.prepareStatement("SELECT name FROM users WHERE id = ?")) {
    ps.setLong(1, id);
    try (var rs = ps.executeQuery()) {
        return rs.next() ? rs.getString(1) : null;
    }
}
  • Resources are closed in reverse order of opening.
  • If both the body and close() throw, the body's exception is primary and the close() failure is attached via getSuppressed() (suppressed = carried along, not overwriting). With a hand-written finally, the close() exception typically overwrites the original.
Read in post: Java exceptions
TILJuniorHelpful NullPointerExceptions (Java 14+)Java 14+ has helpful NullPointerExceptions (on by default since 15): the message tells you exactly what was null, e.g. Cannot invoke "String.length()" because "user.name" is null.

Java 14+ has helpful NullPointerExceptions (on by default since 15): the message tells you exactly what was null, e.g. Cannot invoke "String.length()" because "user.name" is null.

Read in post: Java exceptions
Edge caseSeniorOmitStackTraceInFastThrow strips the stack trace from production NPEsHotSpot enables -XX:+OmitStackTraceInFastThrow by default: when the same NullPointerException/ArithmeticException is thrown repeatedly from the same JIT-compiled spot, the JVM reuses a preallocated instance with no stack trace. If production logs show a bare java.lang.NullPointerException with no lines under it, this i

HotSpot enables -XX:+OmitStackTraceInFastThrow by default: when the same NullPointerException/ArithmeticException is thrown repeatedly from the same JIT-compiled spot, the JVM reuses a preallocated instance with no stack trace. If production logs show a bare java.lang.NullPointerException with no lines under it, this is why. Find the first occurrence in the logs or turn the flag off while debugging.

Read in post: Java exceptions
InterviewJuniorWhat's the difference between checked and unchecked exceptions?

Checked exceptions are subject to the compiler's "catch or declare" rule; unchecked ones aren't.

Checked means subclasses of Exception outside RuntimeException; unchecked means RuntimeException and Error. Checked is meant for recoverable external failures (I/O); unchecked for programming errors and contract violations.

Read in post: Java exceptions
InterviewJuniorHow is throw different from throws?

throw is a statement that throws an instance; throws is part of a method signature that declares the checked exceptions it may throw.

throws tells callers what they need to handle.

Read in post: Java exceptions
InterviewJuniorDoes finally always run?

Almost always, even when the try returns or throws.

The exceptions: System.exit(), a JVM crash or kill, a thread stuck forever, or a daemon thread at JVM shutdown.

Read in post: Java exceptions
InterviewJuniorWhy must a subclass catch come before its superclass?

Because catch blocks are checked top to bottom and only the first match runs.

If the superclass came first, the subclass handler could never be reached, and the compiler reports it as unreachable.

Read in post: Java exceptions
InterviewMidWhat problem does try-with-resources solve, and what is a suppressed exception?

It closes AutoCloseable resources automatically in reverse order, and it doesn't let a close() failure overwrite the original exception.

If both the body and close() throw, the body's exception is primary and the close() failure is attached via getSuppressed(). With a hand-written finally, the original often gets overwritten.

Read in post: Java exceptions
InterviewSeniorAre exceptions expensive? How would you optimize?

Yes: the main cost is capturing the stack trace at construction (fillInStackTrace), proportional to stack depth.

  • Don't use exceptions for frequent control flow.
  • For high-volume business exceptions, disable the stack trace with the writableStackTrace=false constructor.
  • Be aware that OmitStackTraceInFastThrow makes repeated NPEs lose their stack traces in logs.
Read in post: Java exceptions
InterviewSeniorWhere does an exception thrown in an @Async method or an executor thread go?

Not to the caller or to @ControllerAdvice; you have to handle it deliberately or it's lost.

  • Future/CompletableFuture: it's wrapped and surfaces on get()/join() (as ExecutionException/CompletionException).
  • A void @Async method: it goes to the AsyncUncaughtExceptionHandler (which just logs by default).
  • A plain thread: the UncaughtExceptionHandler.
Read in post: Java exceptions
Edge caseSeniorThreadPoolExecutor only grows beyond core once the queue is fullA pool doesn't "scale from core up to max when busy": it only goes beyond corePoolSize when queue.offer() fails. With an unbounded queue (new LinkedBlockingQueue() has a capacity of Integer.MAXVALUE), the queue is never full, so maximumPoolSize never kicks in and the rejection policy never runs. That's exactly how Exec

A pool doesn't "scale from core up to max when busy": it only goes beyond corePoolSize when queue.offer() fails. With an unbounded queue (new LinkedBlockingQueue() has a capacity of Integer.MAX_VALUE), the queue is never full, so maximumPoolSize never kicks in and the rejection policy never runs.

That's exactly how Executors.newFixedThreadPool(n) and newSingleThreadExecutor() are built. Submitting 200,000 tasks holding 1 KB each to newFixedThreadPool(2) pushed the heap to ~226 MB: no error, no back-pressure, ever-growing latency, and eventually an OutOfMemoryError.

newCachedThreadPool() fails the other way: its SynchronousQueue holds nothing and max = Integer.MAX_VALUE, so a traffic spike creates thousands of threads. In production, build your own ThreadPoolExecutor with a bounded queue, a deliberate rejection policy and named threads.

Read in post: ExecutorService, thread pools and virtual threads in Java
Trade-offSeniorBounded queues and choosing a rejection policyAn unbounded queue only moves the failure elsewhere: latency grows without limit, then OOM, and when the pod dies every queued task (held only in RAM) is lost. A bounded queue forces you to answer "what do we do when overloaded?": Abort: fail fast; the caller decides (return 503, push to a durable message queue for lat

An unbounded queue only moves the failure elsewhere: latency grows without limit, then OOM, and when the pod dies every queued task (held only in RAM) is lost. A bounded queue forces you to answer "what do we do when overloaded?":

  • Abort: fail fast; the caller decides (return 503, push to a durable message queue for later). The clearest option, easy to monitor.
  • CallerRuns: free back-pressure, but the submitting thread may be an HTTP thread or an event loop (Netty, a Kafka consumer); making it run a heavy task can stall something more important.
  • Discard/DiscardOldest: only when losing data is acceptable, and with a metric counting dropped tasks.

Size the queue from tolerable latency: 1,000 tasks, 50 ms each, 10 threads means the last task waits ~5 s. With a 1 s SLA, that queue is too long.

Read in post: ExecutorService, thread pools and virtual threads in Java
Edge caseMidExceptions in tasks passed to submit() are swallowed until someone calls get()With execute(runnable), an exception kills the worker thread (the pool replaces it) and reaches the UncaughtExceptionHandler, which by default prints the stack trace to stderr. With submit(...), the exception is stored in the Future: no log, no handler. If nobody calls future.get(), the error vanishes. What to do: for

With execute(runnable), an exception kills the worker thread (the pool replaces it) and reaches the UncaughtExceptionHandler, which by default prints the stack trace to stderr. With submit(...), the exception is stored in the Future: no log, no handler. If nobody calls future.get(), the error vanishes.

What to do: for fire-and-forget work use execute, or try/catch and log inside the task; with submit/CompletableFuture, something must call get()/join() or attach exceptionally/whenComplete. A Spring @Async method returning void sends its errors to the AsyncUncaughtExceptionHandler.

Read in post: ExecutorService, thread pools and virtual threads in Java
TILMidExecutorService works with try-with-resources since Java 19Since Java 19, ExecutorService extends AutoCloseable. The default close() calls shutdown(), waits for all tasks (no timeout), and calls shutdownNow() if the waiting thread is interrupted. For short-lived work inside one method: try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) { ... } When the bloc

Since Java 19, ExecutorService extends AutoCloseable. The default close() calls shutdown(), waits for all tasks (no timeout), and calls shutdownNow() if the waiting thread is interrupted. For short-lived work inside one method:

try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) { ... }

When the block exits, every task is done. Pools that live as long as the app still need shutdown + awaitTermination + shutdownNow with a timeout.

Read in post: ExecutorService, thread pools and virtual threads in Java
Trade-offSeniorPlatform thread pools vs virtual threadsPlatform thread pool: tens to hundreds of threads; the pool both reuses threads and acts as a natural concurrency limit. Fits CPU-bound work (sized to the core count), code doing I/O inside synchronized on Java 21–23, and native/JNI code. Virtual threads: one thread per task, millions are fine. Fits I/O-bound work with
  • Platform thread pool: tens to hundreds of threads; the pool both reuses threads and acts as a natural concurrency limit. Fits CPU-bound work (sized to the core count), code doing I/O inside synchronized on Java 21–23, and native/JNI code.
  • Virtual threads: one thread per task, millions are fine. Fits I/O-bound work with high concurrency (calling databases/HTTP, fan-out to many services), keeping readable blocking code instead of reactive pipelines.

What to unlearn with virtual threads:

  • Don't pool them. They're cheap; a fixed-size pool throws away the whole benefit.
  • Limit concurrency with a Semaphore, not pool size. With nothing holding them back, 10,000 virtual threads will all hit a database with 20 connections, or blow through an external API's rate limit. Why the HikariCP connection count still follows Little's Law and connectionTimeout becomes the back-pressure point with virtual threads: see Connection pooling and HikariCP.
  • Go easy on heavy ThreadLocals: a million threads means a million caches. ScopedValue (final in Java 25) is the alternative for passing context.
Read in post: ExecutorService, thread pools and virtual threads in Java
TILSeniorJava 24 removes pinning for synchronized (JEP 491)On Java 21–23, many libraries (JDBC drivers, HTTP clients, connection pools) block inside synchronized, so an app with virtual threads could stall once the few carriers were pinned. Since Java 24 (JEP 491), a virtual thread can release its carrier when it blocks or calls wait() inside synchronized; "replace every synch

On Java 21–23, many libraries (JDBC drivers, HTTP clients, connection pools) block inside synchronized, so an app with virtual threads could stall once the few carriers were pinned. Since Java 24 (JEP 491), a virtual thread can release its carrier when it blocks or calls wait() inside synchronized; "replace every synchronized with ReentrantLock" is no longer needed.

Pinning still happens through native/JNI code (and rare cases such as class initializers). If you're serious about virtual threads in production, run on the Java 25 LTS rather than 21. The jdk.tracePinnedThreads flag was removed in 24; use the JFR event jdk.VirtualThreadPinned.

Read in post: ExecutorService, thread pools and virtual threads in Java
Edge caseSeniorA ThreadLocal without remove() in a thread pool leaks data between requestsA value that was set but never removed "survives" into the next task. Two kinds of damage: Wrong data / security: the next request reads the previous request's user, tenant or trace id (an anonymous request audited under someone else's name). Memory leaks: ThreadLocalMap holds keys as weak references but values as stro

A value that was set but never removed "survives" into the next task. Two kinds of damage:

  • Wrong data / security: the next request reads the previous request's user, tenant or trace id (an anonymous request audited under someone else's name).
  • Memory leaks: ThreadLocalMap holds keys as weak references but values as strong references; pool threads live as long as the app, so the value (sometimes a whole cache) is never collected. In old app servers the value pinned the webapp's classloader, and a few redeploys exhausted Metaspace.

Rule: wherever you set, remove() in a finally right there. When handing MDC/SecurityContext to another executor, use Spring's TaskDecorator to copy the context in and clean up after the task. A new thread does not inherit the ThreadLocals of the thread that created it.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewJuniorWhy use a thread pool instead of new Thread() per task?

Because OS threads are expensive and unbounded; a pool reuses a fixed set of threads and gives you one place to manage them.

Creating and destroying OS threads costs about 1 MB of stack and system calls; a traffic spike creates threads until memory runs out. A pool has a queue and explicit limits, and is the one place to name threads, catch errors and shut down cleanly. Virtual threads (Java 21) are the exception: they're cheap, so you don't pool them and you cap concurrency with a Semaphore instead.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewMidHow do execute() and submit() behave when the task throws?

execute lets the exception kill the thread and reach the UncaughtExceptionHandler; submit stores it in the Future, where it only surfaces on get().

execute(Runnable) returns nothing; the default handler prints to stderr and the pool creates a replacement thread. submit(...) returns a Future; the exception surfaces as an ExecutionException when you call get(). If nobody calls get(), the error is lost.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewMidHow do you choose the size of a thread pool?

CPU-bound ≈ cores; I/O-bound ≈ cores × (1 + wait/compute); then cap it by downstream resources and measure.

Little's law also works (concurrency = throughput × latency). Downstream resources include the database connection pool and API rate limits; measure under real load. Split pools by kind of work (bulkheads) so one slow dependency doesn't take the whole app down.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewMidWhat's the difference between shutdown() and shutdownNow()?

shutdown() stops accepting new tasks but lets running and queued ones finish; shutdownNow() interrupts running threads and returns the tasks that never started.

Tasks only really stop if they respect interruption. Neither one waits; for that you call awaitTermination(timeout). The standard pattern: shutdown(), wait with a deadline, and if that expires, shutdownNow() and wait a little longer.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewSeniorWhy shouldn't you use Executors.newFixedThreadPool or newCachedThreadPool in production?

Fixed uses an unbounded queue, so overload becomes a silent OOM; Cached has no thread limit, so a spike spawns thousands of threads.

newFixedThreadPool and newSingleThreadExecutor use an unbounded LinkedBlockingQueue: no back-pressure, and maximumPoolSize and the rejection policy never take effect (the pool only grows past core when the queue is full). newCachedThreadPool has a max of Integer.MAX_VALUE. Build your own ThreadPoolExecutor with a bounded queue, a deliberate rejection policy (Abort to fail fast, CallerRuns for back-pressure), a naming ThreadFactory, and metrics for queue size and rejected tasks.

Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewSeniorWhat do virtual threads help with, what don't they help with, and what are the traps?

They raise throughput for high-concurrency I/O-bound work while keeping sequential blocking code; they don't help CPU-bound work or reduce per-request latency.

The JVM unmounts a virtual thread from its carrier when it blocks. Traps:

  • Pinning when blocking inside synchronized (Java 21–23, fixed in 24 by JEP 491) or native code.
  • Never pool them; limit concurrency with a Semaphore so you don't overwhelm the database or downstream APIs.
  • Heavy ThreadLocals multiply with the thread count; consider ScopedValue.
Read in post: ExecutorService, thread pools and virtual threads in Java
InterviewSeniorHow does ThreadLocal cause leaks in a thread pool?

Pool threads are reused, so a value that was set and never removed carries over to the next task: wrong data and memory leaks.

The next request sees the previous request's user or tenant; the value is a strong reference in the ThreadLocalMap of a thread that lives forever (in app servers it can also pin a classloader). Always remove() in finally; when passing context (MDC, SecurityContext) to another executor, use a TaskDecorator to copy it in and clean up afterwards.

Read in post: ExecutorService, thread pools and virtual threads in Java
Trade-offMidType parameter on the class or on the methodOn the class (class Cache<K, V): the type is part of the object's state, and several methods share it and must agree. Each instance is tied to one set of type arguments. On the method (static <T T firstOrNull(List<T)): the type only matters for one call, especially for static methods (a static method can't see the clas
  • On the class (class Cache<K, V>): the type is part of the object's state, and several methods share it and must agree. Each instance is tied to one set of type arguments.
  • On the method (static <T> T firstOrNull(List<T>)): the type only matters for one call, especially for static methods (a static method can't see the class's type parameters).
  • Smell that it's in the wrong place: the class has <T> but only one method uses it, or you must create a Util<String> just to call a helper. Move T down to the method.
Read in post: Java generics
Edge caseJunior<T> void printArray(T[] arr) won't accept an int[]T can only be a reference type, so printArray(new int[] {1, 2, 3}) fails to compile (method printArray cannot be applied to given types): an int[] isn't a T[] for any T. Autoboxing doesn't apply to whole arrays. To support primitive arrays, write a separate overload (printArray(int[] arr)), which is why Arrays.toString

T can only be a reference type, so printArray(new int[] {1, 2, 3}) fails to compile (method printArray cannot be applied to given types): an int[] isn't a T[] for any T. Autoboxing doesn't apply to whole arrays.

To support primitive arrays, write a separate overload (printArray(int[] arr)), which is why Arrays.toString has 9 overloads. Or take an Object and use java.lang.reflect.Array.

Read in post: Java generics
Edge caseSenior<T extends Comparable<T>> rejects a List<LocalDate>LocalDate doesn't implement Comparable<LocalDate; it implements Comparable<ChronoLocalDate (it compares with dates from other calendar systems). With static <T extends Comparable<T T max(List<T items), calling max(dates) on a List<LocalDate fails to compile: the compiler needs T = LocalDate (from the list) and T = Chro

LocalDate doesn't implement Comparable<LocalDate>; it implements Comparable<ChronoLocalDate> (it compares with dates from other calendar systems). With static <T extends Comparable<T>> T max(List<T> items), calling max(dates) on a List<LocalDate> fails to compile: the compiler needs T = LocalDate (from the list) and T = ChronoLocalDate (from the bound) at once.

The fix is <T extends Comparable<? super T>>: T only has to be comparable to some supertype of itself. The same happens with any subclass that inherits compareTo from its parent, e.g. java.sql.Timestamp extending java.util.Date.

Read in post: Java generics
Edge caseMidCovariant arrays only reveal type errors at runtime (ArrayStoreException)Object[] arr = new String[2]; compiles, but arr[0] = 1; throws ArrayStoreException at runtime, since the JVM knows the real array is a String[]. Generics do the opposite: List<Object l = new ArrayList<String(); is rejected at compile time. That's the main reason to prefer List<T over T[] in APIs.

Object[] arr = new String[2]; compiles, but arr[0] = 1; throws ArrayStoreException at runtime, since the JVM knows the real array is a String[]. Generics do the opposite: List<Object> l = new ArrayList<String>(); is rejected at compile time. That's the main reason to prefer List<T> over T[] in APIs.

Read in post: Java generics
Trade-offMidArrays or List<T> in an APIArrays: hold primitives without boxing (int[] is far more compact and faster than List<Integer) and know their element type at runtime. But they're covariant, mix poorly with generics (no new T[], no new List<String[]), and are always mutable. List<T: type-safe at compile time, has immutable versions (List.of), richer
  • Arrays: hold primitives without boxing (int[] is far more compact and faster than List<Integer>) and know their element type at runtime. But they're covariant, mix poorly with generics (no new T[], no new List<String>[]), and are always mutable.
  • List<T>: type-safe at compile time, has immutable versions (List.of), richer API. The cost is boxing for numbers and no element type at runtime.
  • Pick arrays for large numeric data, performance-critical hot paths or varargs; pick List<T> for most business APIs.
Read in post: Java generics
InterviewJuniorWhat problem do generics solve?

They move type errors from runtime to compile time.

You can't put the wrong type into a collection, you don't need manual casts when reading (the compiler inserts them and guarantees they're correct), and you can write reusable classes and methods for many types while staying type-safe.

Read in post: Java generics
InterviewJuniorWhat's the difference between a generic class and a generic method?

A generic class ties the type to each object; a generic method ties it to each call.

A generic class declares type parameters after the class name (class Box<T>), and all instance methods share that T. A generic method declares them before the return type (static <T> T first(List<T>)), and T is usually inferred from the arguments. Static methods can't use the class's type parameters, so they have to be generic methods.

Read in post: Java generics
InterviewJuniorWhat is the diamond operator, and what's the trap when you combine it with var?

new ArrayList<>() lets the compiler infer the type argument; with var there's nothing to infer from, so you get ArrayList<Object>.

The diamond (Java 7) infers from the left-hand side or the context, so you don't repeat <String>. With var list = new ArrayList<>();, anything you add compiles. With var, put the type argument on the right: var list = new ArrayList<String>();.

Read in post: Java generics
InterviewMidWhy isn't List<Integer> a List<Number> when Integer[] is a Number[]?

Generics are invariant so the compiler can stop you from add(3.14) into a List<Integer>; arrays have been covariant since Java 1.0 and compensate with runtime checks.

Arrays know their element type, so the JVM checks every store and throws ArrayStoreException. Generics are erased, so they can't be checked at runtime and must be locked down at compile time.

Read in post: Java generics
InterviewMidWhen does a type parameter belong on the class, and when on the method?

On the class when the type is part of the object's state; on the method when it only matters for one call.

On the class when several methods must agree on it (Cache<K, V>, Repository<T, ID>); each instance is tied to one set of type arguments. On the method especially for static methods, which can't see the class's type parameters. Signs it's in the wrong place: a class declares <T> but only one method uses it, or you have to create a Util<String> just to call a helper.

Read in post: Java generics
InterviewMidWhy won't <T> void printArray(T[] arr) accept an int[]? Should an API take arrays or List<T>?

T must be a reference type, so an int[] isn't a T[] for any T. Business APIs should prefer List<T>.

Autoboxing doesn't apply to whole arrays, so primitive arrays need their own overload. List<T> is type-safe at compile time, available in immutable form, and free of the covariant ArrayStoreException problem. Arrays fit large numeric data, performance-critical code (an int[] is far more compact than a List<Integer>), and varargs.

Read in post: Java generics
InterviewSeniorWhy does Collections.max have the signature <T extends Object & Comparable<? super T>> T max(Collection<? extends T>)?

Comparable<? super T> accepts types that inherit compareTo from a parent, ? extends T because the collection is a producer, and Object & is a binary-compatibility trick.

For example, LocalDate implements Comparable<ChronoLocalDate>. Erasure uses the first bound, so the erased return type is Object, just like the pre-Java 5 max, instead of Comparable, which keeps code compiled against the old API working.

Read in post: Java generics
Edge caseMidTwo overloads that differ only in type arguments don't compileAfter erasure both become save(List), and a class can't have two methods with the same signature. Overloading works on the number and erased types of parameters, not on type arguments. Fix it with meaningful names (saveNames, saveIds), which usually read better anyway.
void save(List<String> names) { }
void save(List<Integer> ids) { }   // error: name clash ... have the same erasure

After erasure both become save(List), and a class can't have two methods with the same signature. Overloading works on the number and erased types of parameters, not on type arguments. Fix it with meaningful names (saveNames, saveIds), which usually read better anyway.

Read in post: Java generics
Edge caseSeniorReturning a generic varargs array causes a ClassCastException in the callerstatic <T T[] toArray(T... a) { return a; } looks harmless. But call it from another generic method (<T T[] pickTwo(T a, T b, T c) { return toArray(a, b); }) and the array created is an Object[], so String[] r = pickTwo("a", "b", "c") throws ClassCastException in the caller. Rule: never return a generic varargs array a

static <T> T[] toArray(T... a) { return a; } looks harmless. But call it from another generic method (<T> T[] pickTwo(T a, T b, T c) { return toArray(a, b); }) and the array created is an Object[], so String[] r = pickTwo("a", "b", "c") throws ClassCastException in the caller.

Rule: never return a generic varargs array and never write into it. Only when you follow both rules should you add @SafeVarargs; adding it wrongly just silences the warning without making the code safe.

Read in post: Java generics
TILSeniorErasure removes type arguments from objects, but declared signatures stay in the .class fileThe declared types of fields, parameters, return types and supertypes (class UserRepo extends BaseRepo<User) are readable via Field.getGenericType(), Method.getGenericReturnType() and Class.getGenericSuperclass(). Spring (ResolvableType), Jackson and Hibernate rely on this to know a List<Address field should be deseria

The declared types of fields, parameters, return types and supertypes (class UserRepo extends BaseRepo<User>) are readable via Field.getGenericType(), Method.getGenericReturnType() and Class.getGenericSuperclass(). Spring (ResolvableType), Jackson and Hibernate rely on this to know a List<Address> field should be deserialized into Address objects. "Generics are completely erased at runtime" is wrong.

Read in post: Java generics
Edge caseMidRaw types make the ClassCastException blow up where you read, not where you wroteraw.add(42) only produces an unchecked warning, not an error. The Integer sits quietly in the list until someone does String s = strings.get(0). Only then does the compiler-inserted cast throw ClassCastException, possibly in another module, hours later. To find the culprit, temporarily wrap the list with Collections.ch

raw.add(42) only produces an unchecked warning, not an error. The Integer sits quietly in the list until someone does String s = strings.get(0). Only then does the compiler-inserted cast throw ClassCastException, possibly in another module, hours later.

To find the culprit, temporarily wrap the list with Collections.checkedList(list, String.class): the error is then thrown at the bad add.

Read in post: Java generics
Edge caseMidobjectMapper.readValue(json, List.class) returns a list of LinkedHashMap, not UserList.class carries no type argument, so Jackson has no idea the elements are Users and turns every JSON object into a LinkedHashMap. The code still compiles (usually with an unchecked cast). ClassCastException: LinkedHashMap cannot be cast to User only fires when you take an element out and use it. Fix it in one of thr

List.class carries no type argument, so Jackson has no idea the elements are Users and turns every JSON object into a LinkedHashMap. The code still compiles (usually with an unchecked cast). ClassCastException: LinkedHashMap cannot be cast to User only fires when you take an element out and use it.

Fix it in one of three ways:

  • new TypeReference<List<User>>() {}.
  • objectMapper.getTypeFactory().constructCollectionType(List.class, User.class).
  • Deserialize into a User[] and convert.

Same story with restTemplate.getForObject(url, List.class) → use ParameterizedTypeReference.

Read in post: Java generics
Trade-offSeniorClass<T>, Supplier<T> or a super type tokenClass<T: simple, gives you cast/isInstance, can create arrays via Array.newInstance. Can't represent parameterized types (List<User). Good for type-keyed lookups, EnumMap, typed registries. Supplier<T / IntFunction<T[]: no reflection, compile-time safe, can wrap constructors with arguments. Only good for creating objec
  • Class<T>: simple, gives you cast/isInstance, can create arrays via Array.newInstance. Can't represent parameterized types (List<User>). Good for type-keyed lookups, EnumMap, typed registries.
  • Supplier<T> / IntFunction<T[]>: no reflection, compile-time safe, can wrap constructors with arguments. Only good for creating objects, not for asking "what is T?".
  • Super type token (TypeReference, ParameterizedTypeReference): keeps full nested types, which serialization and HTTP clients need. The cost is an anonymous class per use, a java.lang.reflect.Type you have to interpret yourself, and no safe cast like Class<T>.cast.
Read in post: Java generics
Trade-offSeniorA sealed Result<T> or exceptions for business errorsExceptions: propagate on their own, can be handled centrally (@RestControllerAdvice), familiar to every Java developer, and integrate with @Transactional rollback. But the method signature doesn't tell you how it can fail (unchecked), and building stack traces costs something if used for frequent outcomes. Sealed Resul
  • Exceptions: propagate on their own, can be handled centrally (@RestControllerAdvice), familiar to every Java developer, and integrate with @Transactional rollback. But the method signature doesn't tell you how it can fail (unchecked), and building stack traces costs something if used for frequent outcomes.
  • Sealed Result<T>: the failure is part of the return type, an exhaustive switch forces callers to handle every case, and it's cheap. The cost is threading it manually through every layer (map/flatMap), no automatic rollback, and unfamiliarity for teams used to exceptions.
  • In practice: exceptions for unexpected failures and anything that should abort the request; Result for outcomes where "failure is normal", such as bulk validation, calls to partners, or parsing data line by line. See also Java exceptions.
Read in post: Java generics
InterviewJuniorWhy can't you write List<int>?

Because of type erasure: type parameters are replaced by Object (or their bound), and int isn't an Object.

You use the wrapper List<Integer> (paying for boxing, with each element a separate heap object). When performance matters, use int[], IntStream or a primitive collections library.

Read in post: Java generics
InterviewMidWhat is type erasure and what limitations does it bring?

The compiler type-checks with full information, then removes the type arguments: it replaces T with its bound (or Object), inserts casts and generates bridge methods.

Consequences:

  • No List<int>, no new T(), no new T[].
  • No instanceof List<String> on an Object, no static T field, no generic exceptions.
  • No overloads that differ only by type argument.
  • ArrayList<String>.class == ArrayList<Integer>.class.

Erasure was chosen for backward compatibility with pre-Java 5 code without changing the JVM.

Read in post: Java generics
InterviewMidWhat is a bridge method and when does the compiler generate one?

A synthetic method the compiler adds to keep polymorphism working after erasure.

For example, class Name implements Comparable<Name> has compareTo(Name), but the erased interface declares compareTo(Object). The compiler generates a compareTo(Object) that casts to Name and calls the real one. Bridges are also generated for covariant return type overrides.

Calling through a raw type with the wrong argument throws ClassCastException from the bridge. Reflection-based frameworks filter with Method.isBridge().

Read in post: Java generics
InterviewMidHow do you create an instance or an array of T when new T() isn't allowed?

Pass the type in as a value.

  • Objects: a Supplier<T> (e.g. create(StringBuilder::new)), or a Class<T> with type.getDeclaredConstructor().newInstance() if you need reflection.
  • Arrays: Array.newInstance(type, n) or an IntFunction<T[]> (toArray(String[]::new)).

A supplier is preferred because it avoids reflection and is checked at compile time.

Read in post: Java generics
InterviewMidWhy are raw types dangerous, and when are you forced to use them?

A raw type (List with no <...>) switches off all generic checks for that variable, so type errors fire late and far from their cause.

Assign a List<String> to a List variable and add(42) only produces an unchecked warning. The ClassCastException shows up later at a read, sometimes in another module.

Use them only where you can't avoid it: class literals (List.class) and pre-Java 5 libraries. When you must deal with non-type-safe code: enable -Xlint:unchecked, keep @SuppressWarnings to the smallest scope, and wrap collections with Collections.checkedList so the bad add fails on the spot.

Read in post: Java generics
InterviewSeniorHow does Jackson know to deserialize into a List<User> when generics are erased?

Super type token: new TypeReference<List<User>>() {} creates an anonymous subclass, and its generic supertype is still in the .class file.

The supertype TypeReference<List<User>> is stored in the class's Signature attribute and can be read with getClass().getGenericSuperclass() as a full ParameterizedType. Erasure removes type arguments from objects, not from declarations.

Spring uses the same technique with ParameterizedTypeReference and ResolvableType. Pass List.class instead and Jackson can only build a list of LinkedHashMap.

Read in post: Java generics
InterviewSeniorWhat is heap pollution? When do you use @SafeVarargs?

Heap pollution is a variable of a parameterized type pointing to an object that isn't of that type; use @SafeVarargs only when the method neither writes to the varargs array nor leaks it.

Heap pollution comes from raw types or unchecked casts; the failure shows up late, at a compiler-inserted cast. Generic varargs are a common source because the varargs array is created from the erasure (Object[]): returning it causes a ClassCastException in the caller.

@SafeVarargs can only go on static, final and private methods and constructors. Adding it wrongly just hides the warning.

Read in post: Java generics
Trade-offSeniorWildcard or type parameter in a method signaturestatic void printAll(List<? list) and static <T void printAll(List<T list) accept the same arguments. How to choose: The type parameter appears only once in the signature → use a wildcard; the signature is shorter and the intent ("I don't care about the type") is clearer. You need to link several positions (input and o

static void printAll(List<?> list) and static <T> void printAll(List<T> list) accept the same arguments. How to choose:

  • The type parameter appears only once in the signature → use a wildcard; the signature is shorter and the intent ("I don't care about the type") is clearer.
  • You need to link several positions (input and output of the same type, two parameters of the same type), or write elements of that type → use T.
  • Don't return wildcard types (List<? extends Number> find()): callers would have to drag the wildcard around everywhere. Wildcards belong on parameters, not return types.
  • You can combine them: a wildcard in the public signature, with a private <T> helper in the implementation (wildcard capture).
Read in post: Java generics
Edge caseMidCollections.copy doesn't grow the destination listCollections.copy(dest, src) overwrites with set(i, ...); it never calls add. If dest.size() < src.size() it throws IndexOutOfBoundsException: Source does not fit in dest, even when dest is new ArrayList<(100) (capacity 100, but size is still 0). To copy into a new list, use new ArrayList<(src) or dest.addAll(src). Coll

Collections.copy(dest, src) overwrites with set(i, ...); it never calls add. If dest.size() < src.size() it throws IndexOutOfBoundsException: Source does not fit in dest, even when dest is new ArrayList<>(100) (capacity 100, but size is still 0).

To copy into a new list, use new ArrayList<>(src) or dest.addAll(src). Collections.copy only fits when you want to overwrite the front of a list that already has enough elements.

Read in post: Java generics
TILMidA List.of(...) call can match List<Number> even though a List<Integer> variable can'tGiven static double total(List<Number l), the call total(List.of(1, 2)) compiles. The reason is Java 8+ target typing (the compiler infers a type from where the value is used): List.of must return a List<Number to fit the parameter. But List<Integer x = List.of(1, 2); total(x); fails, because x already has a fixed type

Given static double total(List<Number> l), the call total(List.of(1, 2)) compiles. The reason is Java 8+ target typing (the compiler infers a type from where the value is used): List.of must return a List<Number> to fit the parameter.

But List<Integer> x = List.of(1, 2); total(x); fails, because x already has a fixed type and generics are invariant. Don't let the first case fool you into thinking a List<Number> parameter is flexible enough; real APIs should still say List<? extends Number>.

Read in post: Java generics
Edge caseMidList<Box<T>> won't accept a mixed list of Box<Integer> and Box<String>The signature static <T double total(List<InventoryItem<T items) forces every element to share the same T. A List<InventoryItem<? holding both numeric-ID and SKU items can't be passed in (method cannot be applied to given types). If the method doesn't need to know T, use Collection<? extends InventoryItem<?: it accepts

The signature static <T> double total(List<InventoryItem<T>> items) forces every element to share the same T. A List<InventoryItem<?>> holding both numeric-ID and SKU items can't be passed in (method cannot be applied to given types).

If the method doesn't need to know T, use Collection<? extends InventoryItem<?>>: it accepts both the mixed list and a uniform List<InventoryItem<Integer>>.

Read in post: Java generics
InterviewJuniorHow do List<?>, List<Object> and List differ?

List<Object> holds anything but won't accept a List<String>; List<?> accepts any list and stays type-safe; a raw List turns type checking off.

  • List<Object>: rejects a List<String> argument because of invariance.
  • List<?>: a list of some unknown type; reads elements as Object, can't be added to (except null).
  • Raw List: lets you add anything and can corrupt the list; it exists only for legacy compatibility.
Read in post: Java generics
InterviewJuniorWhy can't you add an Integer to a List<? extends Number>?

Because that list might really be a List<Double>, and adding an Integer would corrupt it.

The compiler only knows "a list of some subtype of Number": it could be a List<Double>, a List<Integer> or a List<Number>. No value (other than null) is valid for every possible subtype. So ? extends is for reading (as Number); to write, use ? super Integer.

Read in post: Java generics
InterviewMidWhat is PECS? Give JDK examples.

Producer Extends, Consumer Super: a parameter the method reads T from takes ? extends T, a parameter the method writes T into takes ? super T. One that does both takes plain T.

Examples: Collections.copy(List<? super T> dest, List<? extends T> src), Collection.addAll(Collection<? extends E>), List.sort(Comparator<? super E>), Stream.map(Function<? super T, ? extends R>).

Read in post: Java generics
InterviewMidWrite the signature of a method that totals the prices of a list holding both InventoryItem<Integer> and InventoryItem<String>.

static BigDecimal total(Collection<? extends InventoryItem<?>> items).

The signature <T> total(List<InventoryItem<T>>) is wrong because T has to be one type for the whole list, so a mixed list can't be passed in. InventoryItem<?> means "an item with any ID type", and ? extends also lets you pass a List<InventoryItem<Integer>>. The method only reads prices, so it's a producer.

Read in post: Java generics
InterviewMidWhat is wildcard capture, and when do you need a helper method?

Capture is the compiler giving a temporary name to the unknown type of a List<?>. You need a helper when you have to write back into that list.

The temporary name shows up in errors as CAP#1. You can't write that name, so you can't set an element you just read back into the list. The fix is a private generic method <T> void helper(List<T> list): the compiler infers T as the captured type, and inside the helper reads and writes work normally. The public signature stays a clean List<?>, just like Collections.swap and Collections.reverse.

Read in post: Java generics
InterviewMidWhy does List.sort take a Comparator<? super E> rather than a Comparator<E>?

Because a comparator consumes elements (it takes them in to compare), so by PECS it's ? super E.

That way a Comparator<Number> or Comparator<Object> can sort a List<Integer>, and a comparator written for a superclass (Comparator<Employee>) works for a list of a subclass (List<Manager>). With Comparator<E> you'd have to rewrite the comparator for every subtype.

Read in post: Java generics
InterviewSeniorWhen do you use a wildcard and when a type parameter in a method signature?

If the type parameter appears only once → wildcard. If you need to link several positions or write elements → type parameter.

  • A wildcard is shorter and states the intent when you don't care about the type.
  • "Linking" means input and output of the same type, or two parameters of the same type.
  • Apply PECS to each parameter.
  • Don't return wildcard types, since that forces callers to carry them around.
  • When the public signature uses List<?> but the implementation needs to write, use a private <T> helper (wildcard capture).
Read in post: Java generics
Trade-offJuniorCentralized vs distributed version control
Centralized Distributed
Examples Subversion (SVN), CVS, Perforce Git, Mercurial
Where history lives Only on the server Every clone has the full history
Working offline Barely Commit, branch, log and diff all work offline
Branches Expensive, used sparingly Cheap (just a pointer), used all the time
Read in post: Git
Edge caseJuniorgit add . makes it easy to stage junkgit add . makes it easy to stage logs, .env or build output. Add a .gitignore in the very first commit and read git status before every commit.

git add . makes it easy to stage logs, .env or build output. Add a .gitignore in the very first commit and read git status before every commit.

Read in post: Git
Edge caseJuniorFormatting changes are style, not refactorA correction to the slides: in the spec, pure formatting changes are style; refactor means restructuring without a behaviour change. There are also perf, test, build and ci. A ! or a BREAKING CHANGE: footer flags an incompatible change, and semantic-release uses it to bump the major version.

A correction to the slides: in the spec, pure formatting changes are style; refactor means restructuring without a behaviour change. There are also perf, test, build and ci. A ! or a BREAKING CHANGE: footer flags an incompatible change, and semantic-release uses it to bump the major version.

Read in post: Git
InterviewJuniorWhat does git commit --amend do, and when shouldn't you use it?

It replaces the last commit with a new one; don't use it on a commit already pushed to a branch others use.

The new commit contains whatever is staged plus the (optionally edited) message. Since a commit's hash depends on its content, amending always changes the hash. Amend a pushed commit and your history and the remote's diverge, you have to force push, and everyone else ends up out of sync. Once it's pushed, add a fix-up commit instead.

Read in post: Git
InterviewJuniorWhat's the difference between Git and GitHub?

Git is a version control tool that runs on your machine; GitHub is a hosted service for Git repos.

GitHub adds pull requests, issues, CI (Actions) and access control. You can use Git without GitHub (GitLab, Bitbucket, or a self-hosted server).

Read in post: Git
InterviewJuniorWhat is the staging area for?

It's the draft of your next commit: it lets you pick exactly which changes go in.

You can pick down to individual hunks with git add -p, so one messy editing session can still become several focused commits.

Read in post: Git
InterviewMidDoes a commit store a snapshot or a diff? Then why doesn't the repo blow up in size?

A snapshot; the repo stays small because an unchanged file has the same hash and reuses the existing blob.

Each commit points to a root tree describing the whole directory; only changed files produce new blobs. Later, git gc packs objects into packfiles with delta compression between similar versions. Diffs aren't stored at all; they're computed when you run git diff or git log -p.

Read in post: Git
InterviewMidWhat do Conventional Commits give you beyond a readable history?

They're machine-readable: tools work out the next version and generate the changelog.

With semantic-release or release-please, fix bumps the patch, feat the minor, ! or BREAKING CHANGE the major. Filtering history by type or scope is trivial. You can enforce the convention with commitlint in a hook or in CI. Combined with "one commit, one idea", reverts and bisects get more precise too.

Read in post: Git
InterviewSeniorExplain Git's object model. What is a branch, really?

Git is a content-addressable store of blobs, trees, commits and annotated tags; a branch is just a ref, a file holding the hash of the tip commit.

A blob is file contents, a tree is a directory mapping names to blobs and trees, and a commit points to a root tree, parent commits and metadata. Each object is identified by the hash of its content. A commit is a snapshot of the whole tree, and unchanged files reuse existing blobs. HEAD points to the current branch. Because a commit's hash includes its parent's, rewriting history always produces new commits.

Read in post: Git
InterviewSeniorAn API key was pushed to main. What do you do?

Assume it's leaked and rotate or revoke it immediately: that's the most important step, because clones, forks and CI caches may already have it.

  • Remove it from the code and move it to a secret manager or environment variable.
  • If it must leave history too, use git filter-repo or BFG, coordinate a force push with the whole team, and ask the host (GitHub) to purge cached views.
  • Prevent it next time with secret scanning, a pre-commit hook (gitleaks) and .gitignore entries for .env files.
Read in post: Git
TILJuniorGit 2.23 split git checkout into git switch and git restoregit checkout does too many things: switch branches, restore files, and detach HEAD (point HEAD straight at a commit instead of a branch). Git 2.23 split it into git switch (branches) and git restore (files). The slides' checkout still works, but get comfortable with both.

git checkout does too many things: switch branches, restore files, and detach HEAD (point HEAD straight at a commit instead of a branch). Git 2.23 split it into git switch (branches) and git restore (files). The slides' checkout still works, but get comfortable with both.

Read in post: Git
Trade-offMidFast-forward vs merge commit (--no-ff)When you git merge feature/x into main: main has no new commits since you branched off: Git moves the main pointer to the tip of feature/x. That's a fast-forward, with no new commit. Both sides have new commits: Git finds the merge base (the nearest common ancestor), performs a three-way merge (compares each side with

When you git merge feature/x into main:

  • main has no new commits since you branched off: Git moves the main pointer to the tip of feature/x. That's a fast-forward, with no new commit.
  • Both sides have new commits: Git finds the merge base (the nearest common ancestor), performs a three-way merge (compares each side with the merge base to see who changed what) and creates a merge commit with two parents.

git merge --no-ff always creates a merge commit, which keeps a visible "this was a feature" marker.

Read in post: Git
Edge caseJuniorA cleanly resolved conflict can still be logically wrongBuild and run the tests after resolving a merge conflict. A conflict can be syntactically clean and still logically wrong, for example calling a method whose signature the other branch changed.

Build and run the tests after resolving a merge conflict. A conflict can be syntactically clean and still logically wrong, for example calling a method whose signature the other branch changed.

Read in post: Git
Edge caseMidDuring a rebase, "ours" and "theirs" are swappedgit checkout --ours file / --theirs file takes one side wholesale. Watch out: during a rebase the two are swapped: ours is the branch you're rebasing onto, theirs is your commit being replayed.

git checkout --ours file / --theirs file takes one side wholesale. Watch out: during a rebase the two are swapped: ours is the branch you're rebasing onto, theirs is your commit being replayed.

Read in post: Git
TILMidmerge.conflictstyle zdiff3 shows the original text in conflictsSet git config --global merge.conflictstyle zdiff3 so conflict markers also show the original text from the merge base (the common ancestor) next to both sides. That tells you what each side changed.

Set git config --global merge.conflictstyle zdiff3 so conflict markers also show the original text from the merge base (the common ancestor) next to both sides. That tells you what each side changed.

Read in post: Git
Trade-offMidMerge vs rebaseRebasing a feature branch (X, Y) onto main (A - B - C) gives a linear history: A - B - C - X' - Y'. The primes mean X' and Y' are new commits with new hashes, because their parents changed.

Rebasing a feature branch (X, Y) onto main (A - B - C) gives a linear history: A - B - C - X' - Y'. The primes mean X' and Y' are new commits with new hashes, because their parents changed.

Merge Rebase
History Preserved exactly as it happened, with merge commits Linear, as if work happened in sequence
Rewrites commits No Yes (new hashes)
Safe on shared branches Yes No: others are building on the old commits
Conflict resolution Once for the whole branch Possibly once per replayed commit
git bisect, git log Noisier with many merges Clean
"When did this feature land?" Obvious from the merge commit Lost, unless you --no-ff the final merge
Read in post: Git
Edge caseMidRebasing shared commits breaks other people's branchesThe golden rule: never rebase commits that you've pushed to a branch other people use. Rebasing your own feature branch is fine. If you've already pushed it, re-push with git push --force-with-lease, not --force: it refuses to overwrite the remote if it contains commits you haven't seen.

The golden rule: never rebase commits that you've pushed to a branch other people use. Rebasing your own feature branch is fine. If you've already pushed it, re-push with git push --force-with-lease, not --force: it refuses to overwrite the remote if it contains commits you haven't seen.

Read in post: Git
Trade-offMidreset vs revert for undoing commitsreset moves the branch pointer, so it rewrites history. git revert <hash instead adds a new commit that undoes the change, without rewriting history. On shared branches, use revert.
git reset --soft HEAD~1    # drop the last commit, keep changes staged
git reset --mixed HEAD~1   # (default) drop the commit, changes back in the working directory
git reset --hard HEAD~1    # drop the commit AND discard the changes: be careful

reset moves the branch pointer, so it rewrites history. git revert <hash> instead adds a new commit that undoes the change, without rewriting history. On shared branches, use revert.

Read in post: Git
Trade-offSeniorGit Flow vs GitHub Flow vs trunk-based development
Git Flow GitHub Flow Trunk-based development
Long-lived branches main, develop main main (the trunk)
Short-lived branches feature/*, release/*, hotfix/* feature/* Very short (under 1–2 days), or commit directly
Releasing Cut release/x.y from develop, stabilise, merge into main and tag Merging to main means deploying main is always deployable; release from trunk or a release branch cut from it
Unfinished work Lives on long-running feature branches Lives on feature branches Hidden behind feature flags (runtime switches that turn a feature on or off)
Good fit Versioned products (mobile apps, libraries, on-prem software), several supported versions at once Small to mid-sized web apps that deploy often Teams with strong CI/CD and solid automated tests, deploying many times a day
Risk Long branches, merge hell, late integration Needs decent CI Needs discipline: tests, flags, fast reviews
Read in post: Git
Edge caseMidThe reflog can't recover changes that were never committedThe reflog cannot bring back changes that were never committed or staged: edits that only existed in the working directory are gone after reset --hard. Staged changes leave a dangling blob you can find with git fsck --lost-found. The lesson: commit early and often on your own branch, and tidy up later with rebase.

The reflog cannot bring back changes that were never committed or staged: edits that only existed in the working directory are gone after reset --hard. Staged changes leave a dangling blob you can find with git fsck --lost-found. The lesson: commit early and often on your own branch, and tidy up later with rebase.

Read in post: Git
Edge caseJuniorBranch a/b can't coexist with branch a/b/cIf you name the lesson branch feature/03-operators-conditions and the exercise branch feature/03-operators-conditions/01, Git refuses: The reason: branches are stored as files under .git/refs/heads/. feature/03-operators-conditions is already a file, so it can't also be a directory containing 01. The fix is to put the

If you name the lesson branch feature/03-operators-conditions and the exercise branch feature/03-operators-conditions/01, Git refuses:

fatal: cannot lock ref 'refs/heads/feature/03-operators-conditions/01':
'refs/heads/feature/03-operators-conditions' exists; cannot create 'refs/heads/feature/03-operators-conditions/01'

The reason: branches are stored as files under .git/refs/heads/. feature/03-operators-conditions is already a file, so it can't also be a directory containing 01. The fix is to put the lesson branch on a different leaf, e.g. lesson/03-operators-conditions with exercises under exercise/03-operators-conditions/01, or to use a dash: feature/03-operators-conditions-ex01. (The task also spells the repo name two slightly different ways; I picked one.)

Read in post: Git
InterviewJuniorWhen does a merge conflict happen and how do you resolve it?

When Git can't decide which side is right: both branches changed the same lines, or one side edited a file the other deleted or renamed.

Open the file, keep one side or combine them, remove the <<<<<<< ======= >>>>>>> markers, git add, then commit (or rebase --continue). Then build and run the tests, because a resolution can be syntactically fine but logically wrong.

Read in post: Git
InterviewJuniorWhat is a fast-forward merge? When does Git create a merge commit?

A fast-forward is when Git just moves the target branch's pointer forward with no new commit; a merge commit appears when both branches have new commits.

If the target branch has no new commits since the feature branch was created, Git moves its pointer to the feature branch's last commit. If both moved on, Git does a three-way merge using the merge base and creates a merge commit with two parents. git merge --no-ff forces a merge commit even when a fast-forward is possible, to keep a visible trace of the feature.

Read in post: Git
InterviewMidMerge vs rebase: what's the difference and when do you use each?

Merge preserves history with a merge commit; rebase replays your commits on top of the target branch, giving new hashes and a linear history.

I rebase personal, unshared branches (to catch up with main or tidy commits before a PR) and merge, or squash-merge through a PR, into shared branches. Never rebase commits other people have built on.

Read in post: Git
InterviewMidrevert vs reset?

reset rewrites history and is only safe on your own branch; revert adds an inverse commit and is safe on shared branches.

reset moves the branch pointer back to an older commit. revert adds a new commit that undoes an earlier one without touching existing history, so it's fine on main.

Read in post: Git
InterviewMidHow is --force-with-lease different from --force?

--force overwrites the remote no matter what's there; --force-with-lease refuses if the remote has commits you haven't seen.

--force-with-lease only overwrites if the remote is still at the commit you last saw, according to your remote-tracking branch (your local copy of the remote branch). If a teammate pushed in the meantime, it refuses, so you don't wipe out their work.

Read in post: Git
InterviewMidWhat are the pros and cons of squash merging?

Pros: one commit per PR, a clean history, and a whole feature reverts in one go. Cons: you lose the small commits inside, and you get repeated conflicts if the feature branch keeps being used.

Losing the fine-grained commits makes it harder to bisect within the PR. If the feature branch keeps being used after the squash, Git doesn't recognise its commits as merged, which leads to repeated conflicts.

Read in post: Git
InterviewMidWhen would you cherry-pick, and what are the risks?

When you need one specific commit on another branch without merging the whole branch, classically backporting a hotfix from main to an older release branch.

Risks: you get duplicate-content commits with different hashes on two branches, which can conflict when those branches later merge. The picked commit may also depend on other commits the target branch doesn't have. Use -x to record where it came from.

Read in post: Git
InterviewSeniorYou ran reset --hard and lost three commits, or deleted an unmerged branch. How do you recover?

Use git reflog to find the hash from before the reset (or the deleted branch's last commit), then create a branch there or reset to it.

Commands: git branch rescue <hash> or git reset --hard HEAD@{n}. The commits stay in the object database until gc (garbage collection), roughly 30 to 90 days by default. Changes that were never staged or committed can't be recovered through the reflog.

Read in post: Git
InterviewSeniorGit Flow or trunk-based? How would you choose for a team?

It depends on how you release: several versions in parallel points to Git Flow, continuous deployment with strong CI points to trunk-based.

  • Git Flow suits versioned products (mobile apps, libraries, on-prem), at the cost of late integration and big conflicts.
  • Trunk-based suits continuously deployed web services: short-lived branches, an always-deployable main, unfinished work behind feature flags. It requires fast CI, trustworthy automated tests and quick reviews.
  • I look at deploy frequency, how many versions we maintain, and test maturity, and I usually lean towards trunk-based plus a release branch when we need to hotfix older versions.
Read in post: Git
InterviewSeniorHow do you find which of the last 500 commits introduced a regression?

Use git bisect: a binary search between one good and one bad commit, about log2(500) ≈ 9 steps.

At each step you, or a script via git bisect run, say whether the commit is good or bad, and Git halves the remaining range. It only works well if every commit builds and can be tested, which is exactly why commit hygiene matters.

Read in post: Git
Edge caseJuniorThe default branch may be main, not masterThe slides use git push origin master. Since around 2020, GitHub and many organisations default to main, so check which name your repo uses.

The slides use git push origin master. Since around 2020, GitHub and many organisations default to main, so check which name your repo uses.

Read in post: Git
Trade-offMidFull clone vs shallow clone (--depth 1) in CIgit clone --depth 1 <url fetches only the latest commit without the history: much faster and lighter on a long-lived repo. It suits CI jobs that only build and test the current code (GitHub Actions' actions/checkout defaults to fetch-depth: 1). The cost: git log, git blame and git bisect are incomplete; git describe fi

git clone --depth 1 <url> fetches only the latest commit without the history: much faster and lighter on a long-lived repo. It suits CI jobs that only build and test the current code (GitHub Actions' actions/checkout defaults to fetch-depth: 1).

The cost: git log, git blame and git bisect are incomplete; git describe finds no tags ("No names found"); tools that derive things from commits (semantic-release, diff-based coverage, SonarQube) can get it wrong. Jobs that need history use fetch-depth: 0 or git fetch --unshallow. A middle ground for huge repos: git clone --filter=blob:none — full commit history, file contents downloaded only when needed.

Read in post: Git
Edge caseJuniorAdding a file to .gitignore doesn't stop Git tracking it once committed.gitignore only applies to untracked files. If application-local.yml was ever committed, adding it to .gitignore changes nothing: Git keeps tracking it and reporting changes. Remove it from the index with git rm --cached application-local.yml (the file stays on disk) and commit. If the file holds a password, it's still

.gitignore only applies to untracked files. If application-local.yml was ever committed, adding it to .gitignore changes nothing: Git keeps tracking it and reporting changes. Remove it from the index with git rm --cached application-local.yml (the file stays on disk) and commit. If the file holds a password, it's still in the history: treat it as leaked and rotate it.

Read in post: Git
TILMidgit bundle packs a whole repository, history included, into one filegit bundle create repo.bundle --all packs every branch, tag and the complete history into a single file. That file works like a remote (git clone repo.bundle, git fetch repo.bundle). Handy for backups to an external drive, moving a repo across a network that can't reach GitHub, or archiving a finished project.

git bundle create repo.bundle --all packs every branch, tag and the complete history into a single file. That file works like a remote (git clone repo.bundle, git fetch repo.bundle). Handy for backups to an external drive, moving a repo across a network that can't reach GitHub, or archiving a finished project.

Read in post: Git
Trade-offMidAnnotated tags vs lightweight tagsLightweight (git tag v1.2.0): just a ref pointing straight at a commit, like a branch that never moves. No tagger, date or message. Annotated (git tag -a v1.2.0 -m "..."): a separate tag object with a tagger, a timestamp, a message, and optionally a signature (-s) proving who cut the release. Use annotated tags for rel
  • Lightweight (git tag v1.2.0): just a ref pointing straight at a commit, like a branch that never moves. No tagger, date or message.
  • Annotated (git tag -a v1.2.0 -m "..."): a separate tag object with a tagger, a timestamp, a message, and optionally a signature (-s) proving who cut the release.

Use annotated tags for releases: git describe and git push --follow-tags only look at annotated tags by default. Lightweight tags are fine as private, temporary bookmarks.

Read in post: Git
Edge caseJuniorgit push doesn't push tags to the remoteYou create a tag, run git push, and the tag still isn't on GitHub: by default push only sends branches. Push tags explicitly with git push origin v1.2.0, or git push --follow-tags (annotated only; lightweight ones are skipped). git push --tags pushes every local tag, scratch tags included. Once a tag is public, don't d

You create a tag, run git push, and the tag still isn't on GitHub: by default push only sends branches. Push tags explicitly with git push origin v1.2.0, or git push --follow-tags (annotated only; lightweight ones are skipped). git push --tags pushes every local tag, scratch tags included.

Once a tag is public, don't delete it and recreate it on another commit: machines that fetched the old one won't update, so the same "v1.2.0" means two commits. If a release is broken, ship v1.2.1.

Read in post: Git
InterviewJuniorgit fetch vs git pull?

fetch only downloads; pull downloads and then integrates into the current branch.

fetch updates the remote-tracking branches (origin/main) without touching your branches or files. pull is fetch plus a merge (or a rebase with --rebase).

Read in post: Git
InterviewJunior.gitignore already lists .env, yet Git still reports changes to .env. Why, and how do you fix it?

.gitignore only applies to untracked files; .env was committed at some point, so Git keeps tracking it.

Remove it from the index with git rm --cached .env and commit; the file stays on disk. If .env holds secrets, they're already in the history, so rotate them right away.

Read in post: Git
InterviewJuniorHow is git clone different from git pull?

clone is a one-off for a machine without the repo; pull is for a repo you already have, to get new commits.

clone creates the folder, adds the origin remote, downloads the whole history and checks out the default branch. pull fetches the remote's new commits and integrates them into your current branch.

Read in post: Git
InterviewJuniorHow do you read version 2.3.1 under Semantic Versioning?

MAJOR.MINOR.PATCH: 2 is the major (breaking changes), 3 the minor (new backward-compatible features), 1 the patch (bug fixes only).

Moving to 2.4.0 gives you new features and is safe to upgrade; moving to 3.0.0 means reading the changelog, because something breaks. A 0.x version is considered unstable.

Read in post: Git
InterviewMidIs pushing to GitHub every day enough of a backup?

Only for what's committed and pushed.

  • Uncommitted changes, unpushed commits, local branches without an upstream, stashes and ignored files all stay on your machine. git status -sb and git log --branches --not --remotes show what hasn't gone out.
  • For an organisation's code the remote can be lost too (a deleted repo, a force push over history): you want branch protection, scheduled mirrors or git bundle copies elsewhere, and an occasional real restore test.
Read in post: Git
InterviewMidWhat's the difference between annotated and lightweight tags, and which should a release use?

Releases use annotated tags: their own object with a tagger, date, message and optional GPG signature; a lightweight tag is just a ref pointing at a commit.

Annotated tags give you traceability, and git describe and git push --follow-tags only use them by default. Remember: a plain git push doesn't send tags, and never move a published tag to another commit; cut a new patch release instead.

Read in post: Git
InterviewSeniorHow would you automate releasing versions from commit history, and what tends to go wrong?

Enforce Conventional Commits in CI, then let semantic-release or release-please compute the version, generate the changelog and create an annotated tag on the main branch.

The tool reads the commits since the last tag, works out the next SemVer version, generates the changelog, creates an annotated tag and builds the artifact from exactly that commit. commitlint in CI enforces the convention. What goes wrong:

  • The CI job uses a shallow clone and can't see previous tags (it needs fetch-depth: 0).
  • Squash merges lose each commit's type if PR titles don't follow the convention.
  • Someone deletes and recreates a tag, so one version points at two commits (turn on protected tags, treat tags as immutable).
  • A breaking change isn't marked with !, so it only bumps the minor.
Read in post: Git
Edge caseJuniorjava Greeting.class can't find the classThe java command takes a class name (or, since Java 11, a .java file name), not a path to a .class file. Typing java Greeting.class fails with Could not find or load main class Greeting.class, because the JVM looks for a class called class in a package called Greeting. If the class lives in package com.vinhnq.demo, run

The java command takes a class name (or, since Java 11, a .java file name), not a path to a .class file. Typing java Greeting.class fails with Could not find or load main class Greeting.class, because the JVM looks for a class called class in a package called Greeting.

If the class lives in package com.vinhnq.demo, run it from the directory that contains com/ as java com.vinhnq.demo.Greeting, or point at the classpath with java -cp out com.vinhnq.demo.Greeting.

Read in post: Java basics
TILJuniorJava 25 compact source filesSince Java 25, a small program can be written as void main() { IO.println("Hi"); } (compact source files). Production code still uses full classes with public static void main(String[] args).

Since Java 25, a small program can be written as void main() { IO.println("Hi"); } (compact source files). Production code still uses full classes with public static void main(String[] args).

Read in post: Java basics
Edge caseJunior1 / 0 throws but 1.0 / 0 returns InfinityInteger 1 / 0 throws, but 1.0 / 0 gives Infinity and 0.0 / 0 gives NaN. Floating-point arithmetic follows IEEE 754 (the common standard for floating-point numbers) and never throws.

Integer 1 / 0 throws, but 1.0 / 0 gives Infinity and 0.0 / 0 gives NaN. Floating-point arithmetic follows IEEE 754 (the common standard for floating-point numbers) and never throws.

Read in post: Java basics
Edge caseJunior1/3 is 0 in Java, so 4 * (1 - 1/3 + 1/5 - …) prints 4Type the Leibniz series with integer literals, 4 (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13), and it prints 4. Dividing two ints is integer division, so 1/3, 1/5 and the rest are all 0, and the compiler doesn't warn you. Make one side floating-point (1.0 / 3 or 1 / 3.0) to get real division. The same bug appears in perce

Type the Leibniz series with integer literals, 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13), and it prints 4. Dividing two ints is integer division, so 1/3, 1/5 and the rest are all 0, and the compiler doesn't warn you. Make one side floating-point (1.0 / 3 or 1 / 3.0) to get real division.

The same bug appears in percentages: done / total * 100 with two ints is almost always 0; write done * 100.0 / total.

Read in post: Java basics
InterviewJuniorWhy does main have to be public static void main(String[] args)?

The JVM calls main before any object exists, so it must be static, and it must be public so the JVM can call it from outside the class.

It returns void because a program reports its exit code through System.exit(code), not a return value. args holds the command-line arguments. Since Java 25, small programs may write void main() (no static, no parameters) and the JVM creates an instance and calls it, but production code still uses the full form.

Read in post: Java basics
InterviewJuniorWhat is the difference between compile errors, runtime errors and logic errors? Which is the most dangerous?

They differ in when they surface: at compile time, at run time, or never. Logic errors are the most dangerous because nothing reports them.

Compile errors are caught by javac (a missing ;, a type mismatch), so the program can't run yet. Runtime errors happen while the program runs, as exceptions (ArithmeticException on integer division by zero, NullPointerException). Logic errors let the program run and produce wrong results. The defence is unit tests that cover edge cases, plus code review.

Read in post: Java basics
InterviewJuniorWhy is 7 / 2 equal to 3 in Java? How do you get 3.5?

Both operands are int, so it's integer division; make one side floating-point: 7.0 / 2 or (double) a / b.

The fraction is truncated toward zero, so -7 / 2 == -3. 7 / 2.0 works too. Writing (double) (a / b) is wrong, because the integer division has already happened before the cast.

Read in post: Java basics
InterviewJuniorWhat's the difference between javac and java? Why does java Greeting.class fail?

javac compiles .java into .class bytecode; java starts the JVM and runs a class by name, so it doesn't accept a .class path.

java is the launcher: it runs the class that has main. It takes a class name (or, since Java 11, a single .java file), so java Greeting.class is read as a class named class in a package named Greeting, which doesn't exist.

Read in post: Java basics
InterviewMidWhy does 1_000_000 * (1_000_000 + 1) / 2 come out negative? How do you fix it?

The multiplication runs in 32-bit int, overflows and wraps to a negative number; make one operand a long (1_000_000L).

The result (about 10¹²) exceeds Integer.MAX_VALUE and wraps around without any exception. With one long operand the whole expression is computed in long. If you'd rather fail loudly than be silently wrong, use Math.multiplyExact, which throws ArithmeticException on overflow.

Read in post: Java basics
InterviewMidWhy shouldn't you compare two doubles with ==?

Binary floating point can't represent most decimal fractions exactly, so compare within a tolerance: Math.abs(a - b) < 1e-9.

0.1 + 0.2 == 0.3 is false and 4.5 * 7.9 prints 35.550000000000004. The same formula can differ in the last digit depending on evaluation order. Use a relative tolerance for large values. For money, use BigDecimal or integers in the smallest currency unit, never double.

Read in post: Java basics
InterviewSeniorWhen would you run java Hello.java directly, and why not for a production service?

For small scripts and quick experiments; production needs a build step, dependency management and a versioned artifact.

Source-file mode (Java 11+) compiles in memory and runs immediately, which is great for small scripts, quickly trying an API, or a file with a #!/usr/bin/java --source 21 shebang. Not for production: it recompiles on every start, skips the build step where tests and checks run, has no dependency management (Maven/Gradle), and produces no versioned JAR or image. A real service needs reproducible builds, a fixed artifact and startup optimizations (CDS, jlink).

Read in post: Java basics
Edge caseJunior@ComponentScan only scans the main class package and its subpackages@SpringBootApplication includes @ComponentScan, which scans only the main class's package and its subpackages, not the whole classpath. That's why the main class sits in the root package (com.example.shop). Classes outside that tree never become beans, giving you the classic "No qualifying bean" error.

@SpringBootApplication includes @ComponentScan, which scans only the main class's package and its subpackages, not the whole classpath. That's why the main class sits in the root package (com.example.shop). Classes outside that tree never become beans, giving you the classic "No qualifying bean" error.

Read in post: IoC and Dependency Injection
Trade-offSenior@Configuration full mode vs lite mode (proxyBeanMethods)A default @Configuration class (proxyBeanMethods = true, full mode) is wrapped in a CGLIB subclass (a subclass generated at runtime). So when one @Bean method calls another directly, say new MomoGateway(paymentHttpClient(), ...), you still get the same singleton. With @Bean in a plain @Component, or @Configuration(prox

A default @Configuration class (proxyBeanMethods = true, full mode) is wrapped in a CGLIB subclass (a subclass generated at runtime). So when one @Bean method calls another directly, say new MomoGateway(paymentHttpClient(), ...), you still get the same singleton.

With @Bean in a plain @Component, or @Configuration(proxyBeanMethods = false) (lite mode), that call is an ordinary Java method call and creates a new object each time. Spring Boot uses lite mode for auto-configuration to start faster; in that mode, take dependencies as method parameters instead of calling methods.

Read in post: IoC and Dependency Injection
TILJuniorA class with a single constructor doesn't need @AutowiredSince Spring 4.3, a class with a single constructor doesn't need @Autowired. With Lombok, @RequiredArgsConstructor plus final fields generates that constructor for you.

Since Spring 4.3, a class with a single constructor doesn't need @Autowired. With Lombok, @RequiredArgsConstructor plus final fields generates that constructor for you.

Read in post: IoC and Dependency Injection
Edge caseMid@RequiredArgsConstructor only injects final fields; a non-final field stays nullLombok only puts final fields (and uninitialised @NonNull fields) into the constructor. Forget final (private PricingService pricingService;) and Spring never injects it, the context still starts fine, and the NullPointerException only fires on the first request that takes the branch using that field. Always declare de

Lombok only puts final fields (and uninitialised @NonNull fields) into the constructor. Forget final (private PricingService pricingService;) and Spring never injects it, the context still starts fine, and the NullPointerException only fires on the first request that takes the branch using that field.

Always declare dependencies as private final, and keep at least one test that starts the context and calls the main endpoints.

Read in post: IoC and Dependency Injection
Trade-offMidField, constructor or setter injection
Field Constructor Setter
final, immutable fields No Yes No
Required dependencies guaranteed No (can be null if created outside Spring) Yes: no dependency, no object No
Testable without Spring Hard (needs reflection) Easy: new ReportService(mockRepo) Yes
Exposes "too many dependencies" Hidden A long constructor signals the class does too much Hidden
Detects dependency cycles Late/hidden Right at startup Late/hidden
Use for Test code, demos The default Optional dependencies or ones that change after creation
Read in post: IoC and Dependency Injection
Trade-offMidSeveral beans of one type: @Primary, @Qualifier or inject a collectionMomoGateway and VnPayGateway are both PaymentGateways, so injecting PaymentGateway fails with NoUniqueBeanDefinitionException. Three ways out: Option 3 is a natural fit for the strategy pattern: adding a new payment provider means adding a bean, not editing the router.

MomoGateway and VnPayGateway are both PaymentGateways, so injecting PaymentGateway fails with NoUniqueBeanDefinitionException. Three ways out:

@Bean @Primary                          // 1. the default when nothing more specific is asked for
PaymentGateway momoGateway(...) { ... }

public RefundService(@Qualifier("vnPayGateway") PaymentGateway gateway) { ... }  // 2. ask by name

public PaymentRouter(Map<String, PaymentGateway> gateways) { ... }  // 3. take them all: key = bean name
public PaymentRouter(List<PaymentGateway> gateways) { ... }         //    or a List, ordered by @Order

Option 3 is a natural fit for the strategy pattern: adding a new payment provider means adding a bean, not editing the router.

Read in post: IoC and Dependency Injection
Edge caseMidField/setter-injected dependencies aren't set inside the constructorInside the constructor, field/setter-injected dependencies aren't there yet. Put init logic that needs them in @PostConstruct, or use constructor injection.

Inside the constructor, field/setter-injected dependencies aren't there yet. Put init logic that needs them in @PostConstruct, or use constructor injection.

Read in post: IoC and Dependency Injection
Edge caseSeniorCalling @Transactional from the same bean's @PostConstruct runs without a transactionThe proxy is created at the very end (postProcessAfterInitialization). Inside @PostConstruct you're working with the raw object, so a @Transactional call from there gets no transaction. Startup work that needs a transaction belongs in an ApplicationReadyEvent listener.

The proxy is created at the very end (postProcessAfterInitialization). Inside @PostConstruct you're working with the raw object, so a @Transactional call from there gets no transaction. Startup work that needs a transaction belongs in an ApplicationReadyEvent listener.

Read in post: IoC and Dependency Injection
Edge caseMidA singleton bean holding per-request state in fields is a race conditionA singleton bean is shared by every request across many threads. Don't keep per-request state in fields: Keep beans stateless: the only fields are final dependencies or immutable configuration. Per-request state travels through method parameters.

A singleton bean is shared by every request across many threads. Don't keep per-request state in fields:

@Service
public class PriceService {
    private Order currentOrder;          // BUG: two requests overwrite each other

    public Money price(Order order) {
        this.currentOrder = order;        // race condition
        ...
    }
}

Keep beans stateless: the only fields are final dependencies or immutable configuration. Per-request state travels through method parameters.

Read in post: IoC and Dependency Injection
Edge caseMidA prototype injected into a singleton is fetched only onceA singleton is created once, so a prototype injected through its constructor is also fetched only once, which defeats "a new one every time". The right way: Alternatives: a @Lookup method, or @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGETCLASS). For request/session beans injected into a singleton, Sprin

A singleton is created once, so a prototype injected through its constructor is also fetched only once, which defeats "a new one every time". The right way:

@Service
public class ImportService {
    private final ObjectProvider<CsvParser> parserProvider;   // CsvParser is @Scope("prototype")

    public ImportService(ObjectProvider<CsvParser> parserProvider) {
        this.parserProvider = parserProvider;
    }

    public void importFile(Path file) {
        CsvParser parser = parserProvider.getObject();         // a new instance on every call
        parser.parse(file);
    }
}

Alternatives: a @Lookup method, or @Scope(value = "prototype", proxyMode = ScopedProxyMode.TARGET_CLASS). For request/session beans injected into a singleton, Spring requires a scoped proxy: on every method call, the proxy finds the right instance for the current request.

Read in post: IoC and Dependency Injection
Edge caseMid@Transactional and @Async are ignored on self-invocationSelf-invocation (calling this.otherMethod() inside the same class) skips the proxy, so @Transactional/@Async on otherMethod is silently ignored. Fixes: move the method to another bean (cleanest), or inject yourself via @Lazy/ObjectProvider (ugly).

Self-invocation (calling this.otherMethod() inside the same class) skips the proxy, so @Transactional/@Async on otherMethod is silently ignored. Fixes: move the method to another bean (cleanest), or inject yourself via @Lazy/ObjectProvider (ugly).

Read in post: IoC and Dependency Injection
Edge caseMidAnnotations on private or final methods do nothing with CGLIB proxiesProxy-based annotations (@Transactional, @Async, @Cacheable...) on private or final methods do nothing with CGLIB, because the subclass can't override those methods.

Proxy-based annotations (@Transactional, @Async, @Cacheable...) on private or final methods do nothing with CGLIB, because the subclass can't override those methods.

Read in post: IoC and Dependency Injection
TILSeniorThe three-level singleton cache lets Spring resolve field-injection cyclesWith field/setter injection, Spring used to resolve cycles thanks to a three-level cache for singletons: 1. singletonObjects: fully initialised beans. 2. earlySingletonObjects: beans whose object exists but isn't fully injected yet (early references). 3. singletonFactories: factories that produce early references (poss

With field/setter injection, Spring used to resolve cycles thanks to a three-level cache for singletons:

  1. singletonObjects: fully initialised beans.
  2. earlySingletonObjects: beans whose object exists but isn't fully injected yet (early references).
  3. singletonFactories: factories that produce early references (possibly a proxy if the bean needs AOP).

Spring creates OrderService with a no-arg constructor and puts an early reference in the cache. When InventoryService needs OrderService, it gets that "unfinished" instance injected. It works, but a bean can be used before it's fully initialised.

Read in post: IoC and Dependency Injection
Trade-offSeniorFixing circular dependencies: redesign, events, @Lazy or allow-circular-referencesSince Spring Boot 2.6, circular references are banned by default (spring.main.allow-circular-references=false), even with field injection. In order of preference: 1. Redesign: extract the shared part into a third bean, or merge the two classes if they're really one. 2. Use events (ApplicationEventPublisher) to flip one

Since Spring Boot 2.6, circular references are banned by default (spring.main.allow-circular-references=false), even with field injection. In order of preference:

  1. Redesign: extract the shared part into a third bean, or merge the two classes if they're really one.
  2. Use events (ApplicationEventPublisher) to flip one direction of the dependency.
  3. @Lazy on one constructor parameter: Spring injects a lazy proxy that resolves on first use. It puts out the fire but hides the design problem.
  4. Re-enable allow-circular-references=true: only as a temporary measure during an upgrade.
Read in post: IoC and Dependency Injection
Edge caseJunior@Service plus @Bean on the same class creates two beansDon't put @Service on a class and also declare it as a @Bean: you end up with two beans of the same type and a NoUniqueBeanDefinitionException wherever it's injected.

Don't put @Service on a class and also declare it as a @Bean: you end up with two beans of the same type and a NoUniqueBeanDefinitionException wherever it's injected.

Read in post: IoC and Dependency Injection
InterviewJuniorWhat's the difference between IoC and DI?

IoC is the principle (the framework owns creating and wiring objects); DI is one way to implement it.

With DI, dependencies are handed to an object through its constructor, setters or fields instead of the object creating them. Other ways to implement IoC: template methods, callbacks, the service locator.

Read in post: IoC and Dependency Injection
InterviewJuniorWhat is a bean? What is the ApplicationContext?

A bean is an object whose creation and lifecycle the Spring IoC container manages; the ApplicationContext is that container.

It extends BeanFactory with events, i18n, environment/profiles and eager singleton creation at startup.

Read in post: IoC and Dependency Injection
InterviewJuniorHow do @Component, @Service and @Repository differ?

All three mark a class as a bean for component scanning; only @Repository adds behavior.

@Service differs only in meaning. @Repository translates persistence-layer exceptions into DataAccessException.

Read in post: IoC and Dependency Injection
InterviewJuniorWhy prefer constructor injection?

Because required dependencies are guaranteed the moment the object exists, and the class is testable without Spring.

On top of that: fields can be final, a long constructor warns that the class does too much, and dependency cycles show up at startup.

Read in post: IoC and Dependency Injection
InterviewMidWhen would you use @Bean instead of @Component?

When you can't edit the class's source (a third-party library).

Or when creating the bean needs non-trivial logic or configuration parameters, or when you want several beans of one type with different configurations.

Read in post: IoC and Dependency Injection
InterviewMidTwo beans implement the same interface. How do you inject one?

@Primary for the default bean, @Qualifier("name") to ask for a specific one.

Or inject a List<T>/Map<String, T> to get all of them, which suits the strategy pattern.

Read in post: IoC and Dependency Injection
InterviewMidAre singleton beans thread-safe?

No, Spring doesn't make them thread-safe; the bean has to be stateless.

One instance is shared across threads. Per-request state goes through parameters, or into request scope / a ThreadLocal that gets cleaned up.

Read in post: IoC and Dependency Injection
InterviewMidWalk through the main steps of a bean's lifecycle.

Read the definition, create, inject, initialise, wrap in a proxy, use, destroy.

In detail: read the definition, run BeanFactoryPostProcessors, call the constructor, inject dependencies, Aware callbacks, BeanPostProcessor.before (including @PostConstruct), afterPropertiesSet/init-method, BeanPostProcessor.after (creates the AOP proxy), use, then @PreDestroy/destroy when the context closes. Prototypes get no destroy callback.

Read in post: IoC and Dependency Injection
InterviewSeniorWhy doesn't @Transactional work when you call a method in the same class?

Because transactions are applied by a proxy around the bean, and this.method() calls the real object directly.

Fixes: move the method to another bean, or use TransactionTemplate. The same goes for @Async, @Cacheable, and for private/final methods under CGLIB.

Read in post: IoC and Dependency Injection
InterviewSeniorHow does Spring deal with circular dependencies?

With constructor injection it can't (BeanCurrentlyInCreationException); the real fix is redesign.

With field/setter injection, the three-level singleton cache allows injecting an early reference, but since Boot 2.6 that's banned by default. Fix it by extracting a third bean or using events; @Lazy is only a stopgap.

Read in post: IoC and Dependency Injection
InterviewSeniorWhat happens if you inject a prototype bean into a singleton?

The prototype is fetched once when the singleton is created, so it's always the same instance.

Use ObjectProvider<T>.getObject(), @Lookup or a scoped proxy to get a new instance each time.

Read in post: IoC and Dependency Injection
InterviewSeniorHow is @Configuration different from a @Component with @Bean methods?

@Configuration (full mode) gets a CGLIB proxy, so calling one @Bean method from another still returns the same singleton.

In a @Component or with proxyBeanMethods = false (lite mode), that call creates a new object. Lite mode starts faster, but you must take dependencies as method parameters.

Read in post: IoC and Dependency Injection
InterviewSeniorHow does DI help with testing and long-term architecture?

Testing: swap dependencies for mocks or fakes without a container or real infrastructure. Architecture: code depends on abstractions, so implementations change through configuration.

You can swap the database, payment provider or cache without touching business logic; combine it with automated architecture checks (ArchUnit) to keep layer boundaries intact.

Read in post: IoC and Dependency Injection
TILJuniorThe "learning pyramid" (5% from lectures, 90% from teaching) has no scientific basisThe course's opening session shows the "learning pyramid": you retain 5% of a lecture, 10% of what you read, …, and 90% of what you teach. Those numbers can't be traced to any study (they're usually attributed to the NTL Institute), and education researchers treat the pyramid as a myth. Two techniques with solid eviden

The course's opening session shows the "learning pyramid": you retain 5% of a lecture, 10% of what you read, …, and 90% of what you teach. Those numbers can't be traced to any study (they're usually attributed to the NTL Institute), and education researchers treat the pyramid as a myth.

Two techniques with solid evidence are retrieval practice (cover the answer and recall it) and spaced repetition (review at growing intervals). That's why the interview questions here are collapsed: answer out loud first, then open the answer.

Read in post: Java basics
Trade-offMidWhich Java version to pick for a new projectThe latest LTS (25): patched the longest, unpinned virtual threads, smaller object headers. The catch: some libraries, build plugins or monitoring (APM) agents may lag behind, so check them first. The previous LTS (21): a mature ecosystem. The safe choice if your company isn't ready for 25. Non-LTS releases (26, 27): t
  • The latest LTS (25): patched the longest, unpinned virtual threads, smaller object headers. The catch: some libraries, build plugins or monitoring (APM) agents may lag behind, so check them first.
  • The previous LTS (21): a mature ecosystem. The safe choice if your company isn't ready for 25.
  • Non-LTS releases (26, 27): the newest features, but you must upgrade every six months to keep getting patches. Only for teams with solid CI.
  • Java 8/11: the only reason left is a legacy system that hasn't been migrated. Spring Boot 3 doesn't run on them.
Read in post: Java basics
Edge caseJunior"Java is secure thanks to its sandbox" is outdatedThe "security sandbox" was the applet and Security Manager model: the Security Manager was deprecated in Java 17 and permanently disabled in Java 24. Java ME for embedded devices is effectively legacy too. Java's safety today comes from a memory-safe language (no raw pointers, bounds-checked arrays), the bytecode verif

The "security sandbox" was the applet and Security Manager model: the Security Manager was deprecated in Java 17 and permanently disabled in Java 24. Java ME for embedded devices is effectively legacy too.

Java's safety today comes from a memory-safe language (no raw pointers, bounds-checked arrays), the bytecode verifier, and isolation at the OS or container level. Another claim that's often wrong: "everything in Java is an object". The 8 primitive types are not objects.

Read in post: Java basics
Trade-offMidPin your tool versions or always use the latestPin the JDK and build tool versions so every machine (yours, your teammates', CI, the Docker image) runs the same environment and bugs don't depend on "who installed what": Maven: <maven.compiler.release21</maven.compiler.release. Gradle: java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }, and Gradle d

Pin the JDK and build tool versions so every machine (yours, your teammates', CI, the Docker image) runs the same environment and bugs don't depend on "who installed what":

  • Maven: <maven.compiler.release>21</maven.compiler.release>. Gradle: java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }, and Gradle downloads the right JDK if it's missing. A Spring Boot project only needs <java.version>21</java.version>; the parent sets maven.compiler.release (the Maven and project layout post).
  • A .sdkmanrc or .tool-versions file in the repo so SDKMAN! or asdf switches the JDK when you enter the directory.
  • Docker: use an explicit tag such as eclipse-temurin:21-jre, never latest.

The cost: you upgrade deliberately and on a schedule (each new LTS, plus the quarterly security patches) instead of "getting updates for free". Knowing one version well and upgrading on purpose beats chasing the newest release without knowing what changed.

Read in post: Java basics
InterviewJuniorWhat is the difference between the JDK, the JRE and the JVM?

The JVM runs bytecode; the JRE is the JVM plus the standard library, enough to run apps; the JDK is the JRE plus development tools.

The JDK tools include javac, jar, jshell, jcmd... Developers install the JDK; production servers only need a runtime, which you can build with jlink.

Read in post: Java basics
InterviewJuniorWhy is Java called "write once, run anywhere"?

Because javac produces platform-independent bytecode, and every OS/CPU combination has its own JVM that runs it.

You package your app once (as a JAR) and it runs on any machine with a compatible JVM.

Read in post: Java basics
InterviewJuniorBesides backends, where is Java used, and what makes it popular with enterprises?

Banking and payments, big data, Android, build tools and embedded devices; enterprises pick it for stability, memory safety, a huge ecosystem and backward compatibility.

Concretely: big data tools (Hadoop, Spark, Kafka), build tools (Maven, Gradle), chip cards (Java Card). The JVM runs everywhere, the GC manages memory and arrays are always bounds-checked (so buffer-overflow-style bugs are rare), ten-year-old code still runs, and hiring is easy.

Read in post: Java basics
InterviewMidWhat is an LTS release? Which Java version would you pick for a new project?

An LTS release gets security patches for years (a regular one for six months). For a new project I pick the latest LTS our key dependencies support: usually 25, or 21.

The LTS releases are 8, 11, 17, 21 and 25; since 17 there's a new one every two years. "Key dependencies" means Spring Boot, monitoring agents and build plugins. I also pin the version in Maven/Gradle and in the Docker image.

Read in post: Java basics
InterviewMidName a few changes between Java 8 and 21 that you use every day.

Records, switch expressions, text blocks, var, pattern matching and virtual threads, each backed by a real example.

var (10); HttpClient, String.isBlank/strip/lines and Files.readString (11); switch expressions and helpful NPE messages (14); text blocks (15); records and pattern matching for instanceof (16); sealed classes (17); virtual threads, pattern matching for switch, record patterns and sequenced collections (21). Examples: records instead of hand-written DTOs, a switch over a sealed interface so the compiler catches missing cases, virtual threads for services that mostly wait on I/O.

Read in post: Java basics
InterviewMidHow do OpenJDK, Oracle JDK, Temurin and Corretto differ?

They're all builds of the same OpenJDK code and behave practically the same; they differ in licence, patch support period and bundled tooling.

Others include Azul Zulu and the Microsoft Build of OpenJDK. They all pass the compatibility test kit (TCK). Companies usually pick Temurin or Corretto to avoid licensing questions, often matching their platform (Corretto on AWS, for example).

Read in post: Java basics
InterviewSeniorWhat is the JIT, and how does it affect benchmarks and service startup?

The JIT compiles hot methods to native code at runtime, so a service is noticeably slower for its first few seconds; benchmarks need warm-up, deployments need readiness probes or warm-up traffic.

The JVM interprets first, counts how often each method runs, then compiles hot methods (C1 for quick compilation, C2 for deeper optimization, with inlining and escape analysis). Use JMH for benchmarks. For faster startup, look at CDS/AppCDS, GraalVM native images or CRaC.

Read in post: Java basics
InterviewSeniorWhat do you watch out for when upgrading a service from Java 8 or 11 to 21?

Three risk groups: removed APIs, encapsulated JDK internals and changed runtime behaviour; upgrade in steps and re-measure in a production-like environment.

  • Removed APIs: JAXB, JAX-WS and CORBA left the JDK in 11, so they need explicit dependencies. Moving to Spring Boot 3 also means renaming javax.* to jakarta.*.
  • Strong encapsulation (16, 17): libraries that reflect into JDK internals break; upgrade Lombok, Mockito, ByteBuddy and APM agents, or use --add-opens as a stopgap.
  • Tooling: jdeps --jdk-internals finds uses of internal APIs, and jdeprscan finds APIs slated for removal.
  • Runtime changes: G1 is the default GC, the JVM respects container CPU and memory limits, and UTF-8 is the default charset since 18. Re-measure memory and latency.
  • Approach: build on the new JDK first, adopt new features later, run the full test suite, canary the deployment, and watch GC logs and p99 latency.
Read in post: Java basics
Trade-offJuniorIndexed for vs for-eachUse for when you know the number of iterations or need the index; use for-each when you just read each element in turn. With a List, for-each runs on an Iterator: removing elements inside the loop throws ConcurrentModificationException. Use list.removeIf(...) instead.

Use for when you know the number of iterations or need the index; use for-each when you just read each element in turn. With a List, for-each runs on an Iterator: removing elements inside the loop throws ConcurrentModificationException. Use list.removeIf(...) instead.

Read in post: Java basics
Edge caseJuniorcontinue in a while loop can skip the increment and loop foreverAfter continue, a while/do-while loop jumps straight to the condition, whereas a for loop runs its update (i++) first and then checks. So continue in a while loop whose increment sits at the end of the body loops forever:

After continue, a while/do-while loop jumps straight to the condition, whereas a for loop runs its update (i++) first and then checks. So continue in a while loop whose increment sits at the end of the body loops forever:

int i = 0;
while (i < 10) {
    if (i % 2 == 0) continue;   // BUG: i never increments again
    i++;
}
Read in post: Java basics
Edge caseJuniorJava is always pass-by-value, even for objectsThe slides present this in a way that's easy to misread, so here's the precise version: Java only passes by value. For primitives, the copied value is the number itself. For reference types (arrays, objects), the copied value is the reference. Therefore:

The slides present this in a way that's easy to misread, so here's the precise version: Java only passes by value. For primitives, the copied value is the number itself. For reference types (arrays, objects), the copied value is the reference. Therefore:

static void swap(int a, int b) { int t = a; a = b; b = t; }       // swaps only the copies
static void swapFirstTwo(int[] arr) { int t = arr[0]; arr[0] = arr[1]; arr[1] = t; } // mutates the shared object
static void reassign(int[] arr) { arr = new int[]{0, 0}; }         // changes only the copied reference

int x = 1, y = 2;
swap(x, y);              // x = 1, y = 2: unchanged

int[] data = {10, 20};
swapFirstTwo(data);      // data = [20, 10]: changed, both variables point to the same array
reassign(data);          // data is still [20, 10]
Read in post: Java basics
Trade-offMidMutating an argument vs returning a new valueWith real pass-by-reference, a method that reassigns its parameter (arr = new int[]{0, 0}) would make the caller's data point to the new array. It doesn't, which proves Java passes by value. In API design, a method that quietly mutates an array or list passed in by the caller has a side effect (it changes state outside

With real pass-by-reference, a method that reassigns its parameter (arr = new int[]{0, 0}) would make the caller's data point to the new array. It doesn't, which proves Java passes by value. In API design, a method that quietly mutates an array or list passed in by the caller has a side effect (it changes state outside itself) that breeds bugs. Prefer returning a new object, or make it explicit in the name (sortInPlace).

Read in post: Java basics
Edge caseMida * b / gcd(a, b) can overflow: divide before multiplyingThe LCM of two 9-digit numbers can reach about 10¹⁸. That still fits in a long, but the intermediate product a b can overflow. You must divide before multiplying:

The LCM of two 9-digit numbers can reach about 10¹⁸. That still fits in a long, but the intermediate product a * b can overflow. You must divide before multiplying:

static long lcm(long a, long b) { return a / gcd(a, b) * b; }   // not a * b / gcd
Read in post: Java basics
InterviewJuniorHow do while, do-while and for differ?

while checks first, so it may run zero times; do-while runs first, so it always runs at least once; for packs initialization, condition and update into one line.

for suits a known number of iterations. For-each walks arrays or Iterables when you don't need the index.

Read in post: Java basics
InterviewJuniorWhat is the difference between break and continue? What happens after continue in a for loop?

break leaves the nearest loop (or a labeled one); continue only skips the rest of the current iteration.

In a for loop, the update (i++) runs next and then the condition is checked. In while/do-while, control jumps straight to the condition.

Read in post: Java basics
InterviewJuniorHow do return, break and System.exit differ?

break leaves a loop, return leaves a method, System.exit stops the whole JVM.

  • break only leaves the innermost loop (or switch); code after the loop still runs.
  • return ends the current method and hands control back to the caller. return in main ends the main thread; the program stops if no non-daemon threads remain.
  • System.exit(code) halts the JVM with an exit code for the OS, skipping any pending finally blocks. Server applications and libraries should almost never call it.
Read in post: Java basics
InterviewJuniorWhat is the difference between a parameter and an argument?

A parameter is the variable declared in the method header; an argument is the concrete value passed at the call.

num1 and num2 in int max(int num1, int num2) are parameters (formal parameters); x and y in max(x, y) are arguments (actual parameters). On the call, each argument's value is copied into its parameter, which then lives as a local variable in the method's stack frame.

Read in post: Java basics
InterviewMidIs Java pass-by-value or pass-by-reference?

Always pass-by-value; for objects, the value being copied is the reference.

So a method can change the contents of the object the caller points to, but reassigning the parameter to another object has no effect on the caller's variable.

Read in post: Java basics
InterviewMidHow do the stack and the heap differ? When do you get StackOverflowError versus OutOfMemoryError?

Each thread has its own stack of call frames; the heap is shared, holds objects, and is cleaned up by the GC.

  • A stack frame holds locals and parameters and is freed as soon as its method returns.
  • StackOverflowError: recursion that is too deep or has no base case.
  • OutOfMemoryError: Java heap space: reachable objects exceed -Xmx, typically because of a leak (an unbounded cache, listeners that are never removed).
Read in post: Java basics
InterviewMidWhat does effectively final mean, and why can lambdas only use effectively final locals?

An effectively final local isn't declared final but is assigned exactly once. Lambdas only copy a local's value, so the compiler forbids reassignment to keep the copy and the original from drifting apart.

The local lives in a stack frame that may be gone by the time the lambda runs (on another thread, say), so lambdas and anonymous classes must copy the value in. If reassignment were allowed, the copy and the original would diverge and cause confusing bugs. Fields aren't restricted this way, because the lambda captures this rather than copying the field.

Read in post: Java basics
InterviewSeniorRecursion versus loops: when should you rewrite recursion as iteration in Java?

When the recursion depth grows with the input size, because Java has no tail-call optimization and every call costs a frame.

Walking a long linked list or a degenerate tree can overflow the stack. Rewrite it as a loop with an explicit stack or queue (ArrayDeque). Recursion is fine when the depth is O(log n), as with balanced trees or divide and conquer.

Read in post: Java basics
Trade-offMidjava.util.Stack vs ArrayDeque as a stackjava.util.Stack is a Java 1.0 leftover: It extends Vector, so every method is synchronized: you pay for locking even on a single thread. Being a Vector, it exposes get(i), add(i, e), remove(i) and friends, which break the LIFO abstraction. The JDK's own Javadoc recommends Deque instead. ArrayDeque is a resizable circul

java.util.Stack is a Java 1.0 leftover:

  • It extends Vector, so every method is synchronized: you pay for locking even on a single thread.
  • Being a Vector, it exposes get(i), add(i, e), remove(i) and friends, which break the LIFO abstraction.
  • The JDK's own Javadoc recommends Deque instead.

ArrayDeque is a resizable circular array (two indices, head and tail, wrap around the array). Adding and removing at either end is O(1) amortized, with no node objects and good cache behavior. Caveats: it rejects null (because null is how poll/peek signal "empty"), and it isn't thread-safe.

Read in post: Inside Java Collections
Trade-offSeniorBounded vs unbounded queues for producer/consumerArrayBlockingQueue: bounded, one lock. LinkedBlockingQueue: separate put/take locks. ConcurrentLinkedQueue/ConcurrentLinkedDeque: lock-free. In production, prefer a bounded queue so you get backpressure instead of an OutOfMemoryError when consumers fall behind producers.
  • ArrayBlockingQueue: bounded, one lock.
  • LinkedBlockingQueue: separate put/take locks.
  • ConcurrentLinkedQueue/ConcurrentLinkedDeque: lock-free.

In production, prefer a bounded queue so you get backpressure instead of an OutOfMemoryError when consumers fall behind producers.

Read in post: Inside Java Collections
TILMidJava 21 Sequenced Collections: getFirst(), getLast(), reversed()Java 21 (JEP 431) added the SequencedCollection interface with getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed(). List, Deque and LinkedHashSet all get them. The course's build-your-own ArrayList/LinkedList homework asks you to write exactly these methods yourself.

Java 21 (JEP 431) added the SequencedCollection interface with getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed(). List, Deque and LinkedHashSet all get them. The course's build-your-own ArrayList/LinkedList homework asks you to write exactly these methods yourself.

Read in post: Inside Java Collections
Edge caseJuniorList.of is immutable and Arrays.asList is fixed-sizeList.of(...) returns an immutable list: add throws UnsupportedOperationException, and null isn't allowed. Arrays.asList(...) returns a fixed-size list backed by the original array: set works, add/remove don't, and writing to the list writes to the array.
  • List.of(...) returns an immutable list: add throws UnsupportedOperationException, and null isn't allowed.
  • Arrays.asList(...) returns a fixed-size list backed by the original array: set works, add/remove don't, and writing to the list writes to the array.
Read in post: Inside Java Collections
Edge caseJuniorA hand-written ArrayList must compare size with array.length, not a separate capacity fieldIn the slides' sample code, the capacity field is declared but never assigned, so it's always 0. On the first add, isFull() returns true (0 == 0) and the array is replaced with a one-element array. From then on isFull() is always false (size ≠ 0), so the second add throws ArrayIndexOutOfBoundsException. The fix: compar

In the slides' sample code, the capacity field is declared but never assigned, so it's always 0. On the first add, isFull() returns true (0 == 0) and the array is replaced with a one-element array. From then on isFull() is always false (size ≠ 0), so the second add throws ArrayIndexOutOfBoundsException.

The fix: compare size with array.length and drop the capacity field. Also use a generic <E> instead of Object, and throw an exception instead of printing "Index is invalid" and silently carrying on.

Read in post: Inside Java Collections
Trade-offMidGrowth factor: the slides' size*2+1 vs the JDK's 1.5xThe slides grow the array to size 2 + 1 in ensureCapacity; the JDK uses old + (old 1) (≈ 1.5×), and the solution below follows the JDK. Both grow geometrically, so appending stays O(1) amortized; only the constant differs. Larger factor (2×): fewer copies, but the array can be almost half empty. The +1 keeps a capacity

The slides grow the array to size * 2 + 1 in ensureCapacity; the JDK uses old + (old >> 1) (≈ 1.5×), and the solution below follows the JDK. Both grow geometrically, so appending stays O(1) amortized; only the constant differs.

  • Larger factor (2×): fewer copies, but the array can be almost half empty. The +1 keeps a capacity of 0 from staying stuck at 0.
  • Smaller factor (1.5×): at most about a third wasted, in exchange for copying more often. With a factor below 2, previously freed blocks can eventually add up to fit the new array, so the allocator can reuse them.
  • The real mistake is growing by a constant (say +10 each time): then n appends cost O(n²) copying.
Read in post: Inside Java Collections
Edge caseJuniorCommon bugs in a hand-written singly linked listThe slides' singly linked list (with head, tail, size) has a few instructive bugs: addLast calls get(size - 1) to find the last node (O(n)) even though tail is right there (O(1)). removeLast on a one-element list calls get(-1) → returns null → NullPointerException. remove(i) finds Node(i-1) and then walks from the head

The slides' singly linked list (with head, tail, size) has a few instructive bugs:

  • addLast calls get(size - 1) to find the last node (O(n)) even though tail is right there (O(1)).
  • removeLast on a one-element list calls get(-1) → returns null → NullPointerException.
  • remove(i) finds Node(i-1) and then walks from the head again to find Node(i+1), which is simply node(i-1).next.next. Removing the last node through the "middle" branch doesn't update tail.
  • show() calls get(i) in a loop, which makes it O(n²). Always traverse a linked list by following next.
  • The Node class has no Node(e) constructor, yet the code calls new Node(e).
Read in post: Inside Java Collections
InterviewMidHow does ArrayList grow, and why is add O(1) amortized?

When full, it allocates an array ~1.5× bigger and copies over; because growth is geometric, the total copying across n adds is only O(n).

The default constructor starts with an empty array; the first add allocates 10 slots. Total copying is bounded by a constant times n, so each add averages O(1), even though a single add can be O(n).

Read in post: Inside Java Collections
InterviewMidWhen is LinkedList actually better than ArrayList?

Rarely: mainly when you insert or remove a lot in the middle through a ListIterator that's already positioned there.

Or when you need cheap head operations and don't want ArrayDeque. In most benchmarks ArrayList wins thanks to cache locality and fewer objects; LinkedList carries ~24 bytes of overhead per node and makes the GC work harder.

Read in post: Inside Java Collections
InterviewMidWhy use ArrayDeque instead of Stack?

Stack extends Vector, so it locks for nothing and breaks LIFO; ArrayDeque is a circular array with O(1) amortized push/pop and no locking.

Every Stack method is synchronized, and it exposes index-based methods. ArrayDeque allocates no nodes. The Javadoc itself recommends Deque.

Read in post: Inside Java Collections
InterviewSeniorWalk me through how HashMap works in Java 8+.

A power-of-two array of buckets: the hash picks a bucket, collisions chain in a list, long lists become red-black trees, and past the load factor the table doubles.

16 buckets by default. The hash is spread with h ^ (h >>> 16) and the index is hash & (n-1). Once a bucket hits 8 nodes and the table has at least 64 slots it treeifies (O(log n) worst case), and it turns back into a list at 6. When size exceeds capacity * 0.75 the table doubles and entries are split. Not thread-safe; allows one null key.

Read in post: Inside Java Collections
InterviewSeniorWhat goes wrong if you use a mutable object as a HashMap key?

If a field that feeds hashCode changes after the put, get computes a different bucket, so the entry is never found again.

The entry stays in its old bucket as unreachable garbage that still takes memory, i.e. a leak. Use immutable keys (String, records, Long).

Read in post: Inside Java Collections
InterviewSeniorWhich queue would you use for producer/consumer in production, and why bounded?

ArrayBlockingQueue or LinkedBlockingQueue with a capacity, because an unbounded queue hides slow consumers until the heap fills up.

An unbounded queue ends in OutOfMemoryError. A bounded queue creates backpressure: producers block or get false from offer, so you can reject requests, shed load or scale consumers. Note that Executors.newFixedThreadPool uses an unbounded LinkedBlockingQueue, which is a common trap.

Read in post: Inside Java Collections
InterviewSeniorHow would you build an LRU cache with Java Collections?

Use new LinkedHashMap<>(capacity, 0.75f, true) and override removeEldestEntry to return size() > capacity; get and put are O(1).

Access order (true) makes every get move the entry to the end. From scratch, combine a HashMap (key → node) with a doubly linked list. For concurrent access you need locking, or a library like Caffeine.

Read in post: Inside Java Collections
Edge caseMidremoveAll/retainAll with a large List argument can be O(n·m)a.removeAll(b) calls b.contains(x) for every element of a. If b is an ArrayList, each contains is O(m), so the total is O(n·m): two lists of 100,000 elements means about 10¹⁰ comparisons and a request that hangs for tens of seconds. Fix: wrap the argument in new HashSet<(b) (O(m) to build, O(1) per contains), giving O(

a.removeAll(b) calls b.contains(x) for every element of a. If b is an ArrayList, each contains is O(m), so the total is O(n·m): two lists of 100,000 elements means about 10¹⁰ comparisons and a request that hangs for tens of seconds. Fix: wrap the argument in new HashSet<>(b) (O(m) to build, O(1) per contains), giving O(n + m), provided the elements have correct equals/hashCode. The same applies to retainAll and containsAll.

Read in post: Java Collections
Edge caseJuniorRemoving inside an enhanced for loop throws ConcurrentModificationExceptionCalling names.remove(...) inside an enhanced for loop (e.g. on an ArrayList) throws ConcurrentModificationException. Use iterator.remove() or names.removeIf(n - n.startsWith("B")).

Calling names.remove(...) inside an enhanced for loop (e.g. on an ArrayList) throws ConcurrentModificationException. Use iterator.remove() or names.removeIf(n -> n.startsWith("B")).

Read in post: Java Collections
Edge caseJuniorlist.remove(1) on a List<Integer> removes by index, not by valueOn a List<Integer, list.remove(1) removes the element at index 1; you need list.remove(Integer.valueOf(1)) to remove the value 1.

On a List<Integer>, list.remove(1) removes the element at index 1; you need list.remove(Integer.valueOf(1)) to remove the value 1.

Read in post: Java Collections
Edge caseJuniorCollections.copy needs a destination with enough size; capacity doesn't countCollections.copy(dest, src) overwrites positions with dest.set(i, ...), so you need dest.size() ≥ src.size(). new ArrayList<(10) has a capacity of 10 but a size of 0, so Collections.copy(new ArrayList<(10), src) throws IndexOutOfBoundsException: Source does not fit in dest. For a fresh copy write new ArrayList<(src) or

Collections.copy(dest, src) overwrites positions with dest.set(i, ...), so you need dest.size() ≥ src.size(). new ArrayList<>(10) has a capacity of 10 but a size of 0, so Collections.copy(new ArrayList<>(10), src) throws IndexOutOfBoundsException: Source does not fit in dest. For a fresh copy write new ArrayList<>(src) or List.copyOf(src) (immutable); use copy only when you really mean to overwrite a list that already has elements.

Read in post: Java Collections
TILJuniorStack.search returns a 1-based distance from the top, not an indexsearch(o) returns where o sits counting from the top, starting at 1, or -1 if it's absent; it compares with equals. After push(1), push(2), push(3), search(3) == 1 and search(1) == 3, while indexOf(3) == 2 (inherited from Vector, counting from the bottom, starting at 0). empty() is the legacy name, isEmpty() comes from

search(o) returns where o sits counting from the top, starting at 1, or -1 if it's absent; it compares with equals. After push(1), push(2), push(3), search(3) == 1 and search(1) == 3, while indexOf(3) == 2 (inherited from Vector, counting from the bottom, starting at 0). empty() is the legacy name, isEmpty() comes from Vector/Collection, same answer. ArrayDeque has no search; use contains or walk it yourself.

Read in post: Java Collections
Edge caseJuniorOverriding equals without hashCode lets a HashSet hold duplicatesFor HashSet to treat two objects as "the same" the way you intend, the class must override both equals() and hashCode(). Override only equals and two equal objects can land in different buckets and both stay in the set.

For HashSet to treat two objects as "the same" the way you intend, the class must override both equals() and hashCode(). Override only equals and two equal objects can land in different buckets and both stay in the set.

Read in post: Java Collections
InterviewJuniorWhy must you override hashCode when you override equals?

Because the contract says equal objects must have equal hash codes, and HashMap/HashSet use hashCode to pick a bucket before they ever compare with equals.

Override only equals and two "equal" objects can sit in different buckets, so a set holds duplicates and a map can't find your key.

Read in post: Java Collections
InterviewJuniorHow do HashSet, LinkedHashSet and TreeSet differ, and which do you pick?

Default to HashSet; use LinkedHashSet for insertion order; use TreeSet for sorting or range queries.

  • HashSet: a hash table, O(1) average add/contains/remove, no ordering guarantee, duplicates decided by hashCode + equals, one null allowed.
  • LinkedHashSet: the same plus a linked list, so it iterates in insertion order.
  • TreeSet: a red-black tree, O(log n), always iterates in ascending order, decides duplicates with compareTo/the comparator, rejects null under natural ordering, and offers floor/ceiling/headSet.
Read in post: Java Collections
InterviewJuniorGiven List<Integer> list, what does list.remove(1) remove?

The element at index 1, not the value 1.

The remove(int index) overload matches an int argument exactly, so it wins over remove(Object), which would need boxing. To remove the value 1, write list.remove(Integer.valueOf(1)). It's a classic trap in code that reads numbers from input and then deletes by value.

Read in post: Java Collections
InterviewMidWhen does ConcurrentModificationException happen, and how do you avoid it?

When a collection gets elements added or removed while an iterator is walking it, even on a single thread; fix it with iterator.remove() or removeIf.

For example list.remove(x) inside an enhanced for loop. The iterator compares modCount against what it expects and throws (fail-fast). Other options: iterate over a copy, or use a concurrent collection.

Read in post: Java Collections
InterviewMidHow do getOrDefault, putIfAbsent, computeIfAbsent and merge differ?

getOrDefault only reads; putIfAbsent stores a value built up front; computeIfAbsent builds the value only when the key is missing; merge puts or combines.

  • getOrDefault(k, d): returns d for a missing key and writes nothing.
  • putIfAbsent(k, v): writes v when the key is absent (or mapped to null); v is built even if it isn't used.
  • computeIfAbsent(k, fn): calls fn only when the key is missing, which suits expensive values and multimaps (computeIfAbsent(k, x -> new ArrayList<>()).add(v)).
  • merge(k, v, fn): puts v if absent, otherwise combines with fn, which suits counting and summing.
  • A function returning null in compute/merge removes the entry.
Read in post: Java Collections
InterviewMidYou put Product in a HashSet: which fields go into equals/hashCode? Does adding a duplicate replace the old one?

Exactly the fields that make up the business identity (usually id, and they should be final); adding a duplicate replaces nothing and returns false.

Mutable fields such as price or name shouldn't take part, or changing a price after add makes the element "disappear" from the set. A record compares every field, so as records two products with the same ID and different prices are different elements. The set keeps the old object; for update-by-ID use a Map<Id, Product> and put.

Read in post: Java Collections
InterviewMidHow do you get the intersection and the difference of two lists? Any performance trap?

Copy the original, then call retainAll(other) for the intersection or removeAll(other) for the difference; wrap other in a HashSet to avoid O(n·m).

Both modify the collection they're called on and return true if it changed. Internally they call other.contains(x) for every element, so if other is an ArrayList the cost is O(n·m); with new HashSet<>(other) it's O(n + m). Calling them on an immutable list (List.of) throws UnsupportedOperationException.

Read in post: Java Collections
Edge caseJuniorA column named order and a table named user clash with SQL keywordsORDER is a reserved word in every DBMS, so CREATE TABLE chapter (..., order INT) or the SELECTs Hibernate generates fail with a syntax error. USER is reserved in PostgreSQL and H2 (not in MySQL), so @Table(name = "user") works on MySQL but breaks as soon as you test with H2 or move to PostgreSQL. The simplest fix is re

ORDER is a reserved word in every DBMS, so CREATE TABLE chapter (..., order INT) or the SELECTs Hibernate generates fail with a syntax error. USER is reserved in PostgreSQL and H2 (not in MySQL), so @Table(name = "user") works on MySQL but breaks as soon as you test with H2 or move to PostgreSQL.

The simplest fix is renaming: sort_order (or position) and users. You can keep the names and quote them (@Column(name = "\"order\""), or hibernate.globally_quoted_identifiers=true), but then every hand-written SQL statement has to quote them too.

Read in post: ORM and JPA
Trade-offMid@EmbeddedId (composite key) or an auto-increment id + unique constraint for a join table with attributesA join table rarely referenced by other tables gets a composite key; a table that will have children or is addressed by id through the API gets a surrogate id (an auto-increment id with no business meaning). @EmbeddedId + @MapsId (UserCourse): faithful to the slides' schema, no extra column, and looking up by (userId,

A join table rarely referenced by other tables gets a composite key; a table that will have children or is addressed by id through the API gets a surrogate id (an auto-increment id with no business meaning).

  • @EmbeddedId + @MapsId (UserCourse): faithful to the slides' schema, no extra column, and looking up by (userId, courseId) is a primary-key lookup. The cost: you write an id class with equals/hashCode; because the id is assigned up front, repository.save() treats the entity as "existing", goes down the merge path and fires an extra SELECT before the INSERT (avoid it with entityManager.persist, implementing Persistable, or adding @Version).
  • Auto-increment id + UNIQUE(user_id, course_id, lesson_id) (UserCourseLesson): a simpler entity, save() goes down the persist path, and other tables can point at it with a single FK column. The price is one more column and one more index.

Either way, a unique constraint on the FK pair is mandatory.

Read in post: ORM and JPA
Edge caseSeniorA composite FK to user_course doesn't guarantee the lesson belongs to that courselessonid only points at lesson, so nothing in the database prevents a row (user 1, course 1, lesson 99) when lesson 99 belongs to course 2: lesson → chapter → course is two hops away. Two options: Check in the service before writing (lesson.getChapter().getCourse().getId().equals(courseId)), ideally as one exists query

lesson_id only points at lesson, so nothing in the database prevents a row (user 1, course 1, lesson 99) when lesson 99 belongs to course 2: lesson → chapter → course is two hops away. Two options:

  • Check in the service before writing (lesson.getChapter().getCourse().getId().equals(courseId)), ideally as one exists query rather than loading two levels of associations.
  • If the database must enforce it: denormalize a course_id into lesson, add UNIQUE(id, course_id) on lesson, and give user_course_lesson a composite FK (lesson_id, course_id) → lesson(id, course_id). Airtight, but you must keep lesson.course_id consistent with its chapter.
Read in post: ORM and JPA
Trade-offMidSeparate user, admin and teacher tables, or one account table + rolesReal systems usually have one account table + a role table (or accountrole), with teacher-specific details in a one-to-one teacherprofile. The slides use three tables with almost identical columns (username, password, status, created/updated dates). Upside: each account type can have its own columns freely, and permiss

Real systems usually have one account table + a role table (or account_role), with teacher-specific details in a one-to-one teacher_profile.

  • The slides use three tables with almost identical columns (username, password, status, created/updated dates). Upside: each account type can have its own columns freely, and permissions by table are simple.
  • Downside: login has to look in three places, username is only unique per table (someone who is both a teacher and a learner needs two accounts), and the authentication code is triplicated.

In JPA, shared columns live in a @MappedSuperclass (like BaseEntity). Real entity inheritance (@Inheritance) deserves careful thought, because every strategy has a cost (joining several tables, or NULL-heavy columns).

Read in post: ORM and JPA
TILSeniorHibernate picks the column order of a composite primary key when it generates the tableWhen Hibernate generated the DDL for UserCourse, it created primary key (courseid, userid), not the declared userId, courseId order. The column order decides which lookups the index serves: (courseid, userid) is great for "learners of course X" but useless for "courses of user Y". One more reason to write the schema as

When Hibernate generated the DDL for UserCourse, it created primary key (course_id, user_id), not the declared userId, courseId order. The column order decides which lookups the index serves: (course_id, user_id) is great for "learners of course X" but useless for "courses of user Y".

One more reason to write the schema as migrations (Flyway) instead of relying on ddl-auto, and to add an index for the other lookup direction deliberately.

Read in post: ORM and JPA
Edge caseMidReturning bidirectional entities from an API makes Jackson recurse foreverUser.fullName + FullName.user (or User.addresses + Address.users) make Jackson serialize in circles forever. Jackson 2.16 and later stop at depth 1000 with Document nesting depth (1001) exceeds the maximum allowed; older versions report Infinite recursion (StackOverflowError). The error only appears while serializing t

User.fullName + FullName.user (or User.addresses + Address.users) make Jackson serialize in circles forever. Jackson 2.16 and later stop at depth 1000 with Document nesting depth (1001) exceeds the maximum allowed; older versions report Infinite recursion (StackOverflowError).

The error only appears while serializing the response, after the service has finished and the transaction has committed, so it's easy to miss when you test the service on its own. The real fix is mapping to DTOs; @JsonIgnore or @JsonBackReference merely break the cycle.

Read in post: ORM and JPA
Edge caseJuniorReturning entities from an API leaks the password column and every internal columnAn entity maps the whole table, so returning it returns every column: password (even a hash leaking is a security incident, since it can be cracked offline), internal states, system timestamps. @JsonIgnore on password patches one field, but every new column added to the table automatically shows up in the API until som

An entity maps the whole table, so returning it returns every column: password (even a hash leaking is a security incident, since it can be cracked offline), internal states, system timestamps. @JsonIgnore on password patches one field, but every new column added to the table automatically shows up in the API until someone remembers to block it.

A DTO works the other way round: only the fields you list go out, and adding a column to the table doesn't change the API contract.

Read in post: ORM and JPA
Edge caseMidSerializing a Hibernate LAZY proxy fails on hibernateLazyInitializerAn unloaded @ManyToOne(fetch = LAZY) association is a proxy (a stand-in object generated by Hibernate, a class like Teacher$HibernateProxy). Jackson hits the internal hibernateLazyInitializer field and fails with InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInter

An unloaded @ManyToOne(fetch = LAZY) association is a proxy (a stand-in object generated by Hibernate, a class like Teacher$HibernateProxy). Jackson hits the internal hibernateLazyInitializer field and fails with InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor (reproduced with getReference followed by serialization). Touch the proxy after the transaction has closed and the error becomes LazyInitializationException.

Don't "fix" it with @JsonIgnoreProperties({"hibernateLazyInitializer"}), EAGER or open-in-view: the error goes away, but every response now fires uncontrolled extra queries (N+1). Map to a DTO inside the service while the transaction is open, and fetch exactly what you need.

Read in post: ORM and JPA
Trade-offMidBreaking the JSON cycle: @JsonIgnore, @JsonBackReference, @JsonIdentityInfo or DTOsEvery real API uses DTOs; I only accept returning entities in prototypes or internal tools. @JsonIgnore, the @JsonManagedReference/@JsonBackReference pair: the quickest fix (one annotation), but they tie the API format to the entity, drop one direction of the relationship from every response, and still expose every oth

Every real API uses DTOs; I only accept returning entities in prototypes or internal tools.

  • @JsonIgnore, the @JsonManagedReference/@JsonBackReference pair: the quickest fix (one annotation), but they tie the API format to the entity, drop one direction of the relationship from every response, and still expose every other column.
  • @JsonIdentityInfo: keeps both directions but produces awkward JSON (sometimes an object, sometimes an id).
  • DTOs: one more class and one mapping function per response. In return only the needed fields go out, schema changes don't break the API, there are no proxies or lazy loading during serialization, and each endpoint picks its own JSON shape. You can also use DTO projections at the query level, see part 4.
Read in post: ORM and JPA
TILMidJackson 3 moved packages, but @JsonIgnore stayed where it wasSpring Boot 4 moves to Jackson 3, whose core changed packages from com.fasterxml.jackson.core/databind to tools.jackson. (for example com.fasterxml.jackson.databind.ObjectMapper became tools.jackson.databind.ObjectMapper, usually created through JsonMapper.builder()). The annotations such as @JsonIgnore, @JsonProperty

Spring Boot 4 moves to Jackson 3, whose core changed packages from com.fasterxml.jackson.core/databind to tools.jackson.* (for example com.fasterxml.jackson.databind.ObjectMapper became tools.jackson.databind.ObjectMapper, usually created through JsonMapper.builder()).

The annotations such as @JsonIgnore, @JsonProperty and @JsonManagedReference, however, still live in com.fasterxml.jackson.annotation. Annotated DTOs and entities don't need changes when you upgrade; code that uses ObjectMapper directly does.

Read in post: ORM and JPA
InterviewJuniorWhy shouldn't you return JPA entities directly from an API?

Because entities expose every column, cause infinite recursion and uncontrolled queries, and tie the API to the schema; DTOs decouple the API contract from the storage model.

An entity maps the whole table, so it exposes password and internal fields too. Bidirectional relationships send Jackson into infinite recursion, LAZY associations cause LazyInitializationException or proxy serialization errors, and every association Jackson touches fires another query (N+1). Rename a column and clients break.

Read in post: ORM and JPA
InterviewJuniorWhat's wrong with naming a column order or a table user?

Both clash with SQL keywords: ORDER in every DBMS, USER in PostgreSQL and H2. Renaming (sort_order, users) is the cleanest fix.

An unquoted order column fails with a syntax error. A user table works on MySQL but breaks when you test with H2 or switch databases. Quoting works, but then every hand-written SQL statement must quote too.

Read in post: ORM and JPA
InterviewMidJackson reports infinite recursion when serializing an entity. Why, and how do you fix it?

A bidirectional relationship (User.fullName and FullName.user) makes Jackson go round in circles; the proper fix is mapping to DTOs in the service.

Newer Jackson stops at depth 1000 with a "nesting depth" error, older versions report Infinite recursion (StackOverflowError). Quick fixes: @JsonIgnore or @JsonBackReference on the reverse side, or @JsonIdentityInfo. With DTOs, entities need no Jackson annotations and there's no cycle.

Read in post: ORM and JPA
InterviewMidHow do you map a many-to-many join table that has extra columns (rating, status)?

Turn the join table into its own entity with two @ManyToOnes, because @ManyToMany only manages the two FK columns.

The primary key can be an @EmbeddedId made of the two FKs, with @MapsId so the columns are both PK and FK; or an auto-increment id plus a unique constraint on the FK pair. Either way, the FK pair must be unique.

Read in post: ORM and JPA
InterviewMidWhat is the No serializer found for class ...ByteBuddyInterceptor error when returning an entity?

Jackson is serializing an unloaded Hibernate LAZY proxy and trips over its internal hibernateLazyInitializer field.

If the transaction has already closed, it becomes LazyInitializationException. Don't paper over it with @JsonIgnoreProperties or EAGER; fetch exactly what you need in the service (fetch join, @EntityGraph) and map to a DTO.

Read in post: ORM and JPA
InterviewSeniorWhat's unusual about saving an @EmbeddedId entity with repository.save()?

save() goes down the merge path and fires a SELECT before every INSERT, because a composite key is always assigned up front, so Spring Data thinks the entity already exists.

Spring Data decides between persist and merge from the id: a non-null id means "already exists". Fix it with entityManager.persist, by implementing Persistable<ID> with your own isNew(), or by adding a @Version field (a null version means a new entity).

Read in post: ORM and JPA
InterviewSeniorHow would you constrain lesson progress so it can only be recorded for an enrolled course and a lesson that belongs to it?

A composite FK (user_id, course_id) to user_course guarantees the enrolment; "the lesson belongs to the course" must be checked in the service or enforced by denormalizing course_id into lesson.

A plain lesson_id FK can't guarantee it, because lesson reaches course through chapter. Either check it with one exists query on lesson.chapter.course.id, or add lesson.course_id, UNIQUE(id, course_id) and a composite FK (lesson_id, course_id). The database option is airtight, but lesson.course_id must be kept in sync with the chapter.

Read in post: ORM and JPA
Edge caseSeniorsave() with an assigned id always runs merge and an extra SELECTSpring Data's save() calls persist if the entity is "new" (null id, or null @Version), otherwise merge. If you assign ids yourself (say, UUIDs generated in the app), save always goes down the merge path and fires an extra SELECT before every INSERT. Fix: implement Persistable<ID or add a @Version field.

Spring Data's save() calls persist if the entity is "new" (null id, or null @Version), otherwise merge. If you assign ids yourself (say, UUIDs generated in the app), save always goes down the merge path and fires an extra SELECT before every INSERT. Fix: implement Persistable<ID> or add a @Version field.

Read in post: ORM and JPA
TILMidHibernate updates every column by default; @DynamicUpdate writes only changed onesBy default Hibernate updates all columns of a changed entity, not just the changed ones, so it can reuse a prepared statement. @DynamicUpdate writes only the changed columns, which helps on wide tables.

By default Hibernate updates all columns of a changed entity, not just the changed ones, so it can reuse a prepared statement. @DynamicUpdate writes only the changed columns, which helps on wide tables.

Read in post: ORM and JPA
Trade-offMidLAZY vs EAGER for entity associationsGo LAZY everywhere, including @ManyToOne/@OneToOne (which default to EAGER). EAGER is a static decision applied to every use case: screens that need the teacher pay for it, and so do screens that don't. With JPQL, EAGER associations aren't joined; they're loaded with a separate query per row, which is N+1 in disguise.

Go LAZY everywhere, including @ManyToOne/@OneToOne (which default to EAGER). EAGER is a static decision applied to every use case: screens that need the teacher pay for it, and so do screens that don't. With JPQL, EAGER associations aren't joined; they're loaded with a separate query per row, which is N+1 in disguise. LAZY plus deliberate, per-use-case fetching keeps you in control.

Read in post: ORM and JPA
Trade-offMidFixing N+1: fetch join vs @EntityGraph vs batch size vs DTO projection
Approach Queries Pros Cons
Fetch join 1 Precise control Collection fetch + paging pages in memory; can't fetch two Lists at once
@EntityGraph 1 No JPQL needed Same limits as fetch join
Batch size 1 + N/size Configure once, safe with paging Still more than one query
DTO projection 1 Lightest, exactly the columns needed Can't modify entities, you write the query
Read in post: ORM and JPA
Edge caseSeniorA collection join fetch with Pageable pages in memoryHibernate can't apply LIMIT (each teacher is multiplied into several rows), so it loads everything and pages in memory, logging warning HHH90003004. On a large table that's an OOM (out of heap memory). Instead, query a page of ids first, then fetch-join by those ids; or rely on batch fetching (@BatchSize). The cart and

Hibernate can't apply LIMIT (each teacher is multiplied into several rows), so it loads everything and pages in memory, logging warning HHH90003004. On a large table that's an OOM (out of heap memory). Instead, query a page of ids first, then fetch-join by those ids; or rely on batch fetching (@BatchSize). The cart and checkout post hits this exact warning on the admin orders page.

Read in post: ORM and JPA
TILMidHibernate 6 de-duplicates fetch-join resultsIn Hibernate 6, collection join fetch results are de-duplicated automatically; you no longer need DISTINCT as in Hibernate 5.

In Hibernate 6, collection join fetch results are de-duplicated automatically; you no longer need DISTINCT as in Hibernate 5.

Read in post: ORM and JPA
InterviewJuniorWhat is JPA's first-level cache?

It's the persistence context tied to one EntityManager, which in Spring usually lives for one transaction.

Within that transaction a second findById(1) runs no SQL and returns the object already loaded, and one database row always maps to exactly one Java object. It isn't shared across transactions or requests; a cache shared between requests is the second-level cache, a different thing you have to enable explicitly.

Read in post: ORM and JPA
InterviewJuniorHow is a flush different from a commit?

A flush sends pending SQL to the database but stays inside the transaction; a commit ends the transaction and makes the changes durable.

After a flush, other transactions can't see the changes yet and a rollback still undoes them. Hibernate flushes automatically before commit and before queries that pending changes could affect.

Read in post: ORM and JPA
InterviewMidName the entity states. How do persist and merge differ?

Transient, managed, detached, removed. persist makes the object itself managed; merge copies it onto a managed instance and returns that.

Transient is new and not managed; managed lives in the persistence context and its changes are written automatically; detached means the context has closed; removed is scheduled for deletion. After merge, the argument stays detached.

Read in post: ORM and JPA
InterviewMidWhat is dirty checking? Why does changing an entity produce an UPDATE without calling save?

Hibernate compares each managed entity with the snapshot taken at load time and issues UPDATEs for changed ones on flush.

Flushes run before commit or before a related query, so a managed entity inside a transaction doesn't need save. The flip side: modifying an entity just for display also gets persisted.

Read in post: ORM and JPA
InterviewMidWhen does LazyInitializationException happen and how do you fix it?

When you access a lazy association after the persistence context has closed; fix it by fetching what you need in the service and returning DTOs.

It usually happens in the controller or while Jackson serializes an entity. Fetch with a fetch join, @EntityGraph or a DTO projection inside the service's transaction. Don't "fix" it with EAGER or open-in-view; that hides the problem and causes N+1.

Read in post: ORM and JPA
InterviewSeniorWhat is N+1, and how do you detect and fix it?

One query loads N parent rows, then each row triggers a lazy query: N+1 round trips. Fix it per use case.

Detect it with SQL logging, Hibernate statistics or tests that assert the statement count. Fix: fetch join or @EntityGraph for to-one associations, batch fetching (default_batch_fetch_size) as a safety net, DTO projections for read-only screens. For collections with pagination, query a page of ids first and then fetch by id, to avoid in-memory paging.

Read in post: ORM and JPA
InterviewSeniorA JPA batch job processing a million rows runs out of memory and gets slower over time. Why, and what do you do?

The persistence context keeps every loaded entity plus its snapshot, so the heap grows linearly and every flush dirty-checks everything.

Fix:

  • Process in chunks (read with keyset pagination), flush() + clear() after each chunk.
  • Enable hibernate.jdbc.batch_size with order_inserts/order_updates, and use SEQUENCE ids so inserts can batch.
  • Use readOnly or a StatelessSession when you don't need dirty checking, or bulk UPDATEs / plain JDBC for mass operations.
Read in post: ORM and JPA
Edge caseMidChanges made only on the mappedBy side are not written to the databaseThe slides describe mappedBy as "marks the entity that owns the relationship (the one without the foreign key)". The part about the FK location is right, but the terminology is reversed: per the JPA spec the mappedBy side is the inverse side and the FK holder is the owning side. Getting this wrong leads to a classic bu

The slides describe mappedBy as "marks the entity that owns the relationship (the one without the foreign key)". The part about the FK location is right, but the terminology is reversed: per the JPA spec the mappedBy side is the inverse side and the FK holder is the owning side.

Getting this wrong leads to a classic bug: calling teacher.getCourses().add(course) without course.setTeacher(teacher) leaves teacher_id as null.

Read in post: ORM and JPA
Edge caseSeniorThe inverse side of a @OneToOne can't be lazyIn a bidirectional @OneToOne (User.profile has mappedBy, UserProfile holds the FK), the inverse side can't be lazy in Hibernate without bytecode enhancement. Hibernate has to query to find out whether it's null or not, so loading a User always triggers a query for its UserProfile. If you don't really need to navigate f

In a bidirectional @OneToOne (User.profile has mappedBy, UserProfile holds the FK), the inverse side can't be lazy in Hibernate without bytecode enhancement. Hibernate has to query to find out whether it's null or not, so loading a User always triggers a query for its UserProfile. If you don't really need to navigate from User, drop the profile field altogether.

Read in post: ORM and JPA
Trade-offMidCascade ALL vs only PERSIST/MERGE on @OneToManyThe slides use CascadeType.ALL on Teacher.courses. But ALL includes REMOVE: deleting a teacher deletes every course, and if courses cascade to enrolments, student data goes too. For important business data you usually cascade only PERSIST/MERGE, or nothing. ALL (with orphanRemoval) only fits true composition, where the

The slides use CascadeType.ALL on Teacher.courses. But ALL includes REMOVE: deleting a teacher deletes every course, and if courses cascade to enrolments, student data goes too.

For important business data you usually cascade only PERSIST/MERGE, or nothing. ALL (with orphanRemoval) only fits true composition, where the child can't exist without its parent (Order and OrderLine).

Read in post: ORM and JPA
Edge caseMidA List in @ManyToMany deletes and re-inserts the whole join tableUse a Set, not a List. A List without @OrderColumn is a Hibernate "bag": removing one element makes Hibernate delete all of that entity's rows in the join table and re-insert the rest.

Use a Set, not a List. A List without @OrderColumn is a Hibernate "bag": removing one element makes Hibernate delete all of that entity's rows in the join table and re-insert the rest.

Read in post: ORM and JPA
Trade-offMid@ManyToMany vs a dedicated join entity@ManyToMany + @JoinTable is enough when the join table holds only the two FK columns (coursetags). If it needs extra columns (enrolment date, grade...), promote it to an entity with two @ManyToOnes, like Enrollment. You manage one more entity, but you can store attributes of the relationship and put a unique constraint

@ManyToMany + @JoinTable is enough when the join table holds only the two FK columns (course_tags). If it needs extra columns (enrolment date, grade...), promote it to an entity with two @ManyToOnes, like Enrollment. You manage one more entity, but you can store attributes of the relationship and put a unique constraint on the FK pair.

Read in post: ORM and JPA
InterviewJuniorIn a one-to-many relationship, where does the foreign key go and why?

On the "many" table (each course stores teacher_id).

On the "one" side a single cell would have to hold many values, which breaks first normal form. In JPA the @ManyToOne side holds the FK and is the owning side.

Read in post: ORM and JPA
InterviewJuniorWhat is mappedBy for?

It marks the inverse side of a bidirectional relationship; its value is the field name on the other entity.

The mappedBy side holds no FK, and changes made only there aren't written to the database. Hibernate relies solely on the owning side (the one with @JoinColumn/@JoinTable).

Read in post: ORM and JPA
InterviewJuniorWhat does a unidirectional @OneToMany without @JoinColumn produce?

An extra join table (e.g. teacher_courses), because Hibernate treats it like a many-to-many.

Every child you add means another INSERT into that table, even though the business only needs a teacher_id column on the child table. If you need only one direction, map @ManyToOne on the child; if you need both, add @OneToMany(mappedBy = ...) on the parent.

Read in post: ORM and JPA
InterviewMidHow do CascadeType.REMOVE and orphanRemoval differ?

REMOVE deletes children when the parent is deleted; orphanRemoval deletes a child when it's removed from the parent's collection, even if the parent lives on.

Both only make sense for true ownership, and never on @ManyToMany.

Read in post: ORM and JPA
InterviewMidWhy use a Set instead of a List for @ManyToMany?

Because a List without an order column is a bag: removing one element makes Hibernate delete all of that entity's rows in the join table and re-insert the rest.

A Set lets it delete exactly one row. Fetch-joining two bags at once also throws MultipleBagFetchException.

Read in post: ORM and JPA
InterviewMidWhen do you use @ManyToMany, and when do you turn the join table into its own entity?

@ManyToMany when the join table holds only the two FK columns; once the relationship needs attributes of its own, make it an entity.

Two-column examples: course–tag, user–address. With an enrolment date, grade, status or rating it must be a separate entity with two @ManyToOnes and a unique constraint on the FK pair. Many teams default to a separate entity from day one, because relationships tend to grow columns.

Read in post: ORM and JPA
InterviewSeniorWhy is the inverse side of a @OneToOne loaded eagerly even when marked LAZY?

Because to create a proxy Hibernate must know whether the association is null, and the inverse side has no FK column, so it has to query the other table.

The owning side has an FK column, so it knows immediately. Workarounds: use @MapsId and map only the child-to-parent direction, enable bytecode enhancement, or replace the association with an explicit query when needed.

Read in post: ORM and JPA
Edge caseMidExtending a concrete class couples you to its implementationThis is the fragile base class problem: change the parent's internals and the subclass breaks. class InstrumentedSet extends HashSet counts additions by overriding both add and addAll. But HashSet.addAll calls add internally, so every element is counted twice. Stack extends Vector in the JDK is a design mistake: Stack

This is the fragile base class problem: change the parent's internals and the subclass breaks.

  • class InstrumentedSet extends HashSet counts additions by overriding both add and addAll. But HashSet.addAll calls add internally, so every element is counted twice.
  • Stack extends Vector in the JDK is a design mistake: Stack exposes add(index, e) and breaks LIFO.
Read in post: Object-oriented programming
Trade-offMidComposition vs inheritanceFavor composition (wrap an object and delegate to it, see part 5). Inherit only for a genuine is-a relationship that respects the Liskov Substitution Principle: anywhere a parent is used, a child must work without changing the behavior. The famous counterexample: Square extends Rectangle (see right below).

Favor composition (wrap an object and delegate to it, see part 5). Inherit only for a genuine is-a relationship that respects the Liskov Substitution Principle: anywhere a parent is used, a child must work without changing the behavior. The famous counterexample: Square extends Rectangle (see right below).

Read in post: Object-oriented programming
Edge caseJuniorUML inheritance arrows point from the subclass to the parentThe slide draws arrows from parent to child (Quadrilateral → Parallelogram), which reads more like a taxonomy chart than UML. In UML, generalization (the inheritance relationship) is a solid line with a hollow triangle at the parent's end, running from Square to Rectangle. The reason: the extends lives in the subclass'

The slide draws arrows from parent to child (Quadrilateral → Parallelogram), which reads more like a taxonomy chart than UML. In UML, generalization (the inheritance relationship) is a solid line with a hollow triangle at the parent's end, running from Square to Rectangle. The reason: the extends lives in the subclass's code, so the subclass depends on the parent, not the other way round.

Read in post: Object-oriented programming
Edge caseMidSquare extends Rectangle breaks Liskov once shapes have settersIf Rectangle has independent setWidth/setHeight, Square must change both sides together. Code that is correct for Rectangle then breaks when it gets a Square: The fix: make shapes immutable (records, no setters, "resizing" returns a new object), or have them implement a common sealed interface Shape instead of extendin

If Rectangle has independent setWidth/setHeight, Square must change both sides together. Code that is correct for Rectangle then breaks when it gets a Square:

static void stretch(Rectangle r) {
    r.setWidth(5);
    r.setHeight(4);
    assert r.area() == 20;   // with a Square: setHeight(4) also changes the width, area() = 16
}

The fix: make shapes immutable (records, no setters, "resizing" returns a new object), or have them implement a common sealed interface Shape instead of extending each other. With no state-changing operations left, "a square is a rectangle" is safe again.

Read in post: Object-oriented programming
Edge caseMidGetters and setters for every field is not encapsulationThe slides say "data should be private and accessed through getters and setters": true but not enough. Private fields with a setter for each one are no different from public fields. Real encapsulation moves behavior into the object (tell, don't ask: tell the object to do the job instead of pulling its data out and doin

The slides say "data should be private and accessed through getters and setters": true but not enough. Private fields with a setter for each one are no different from public fields. Real encapsulation moves behavior into the object (tell, don't ask: tell the object to do the job instead of pulling its data out and doing it for it):

// Not encapsulated: the business rule lives outside, and anyone can make the balance negative
account.setBalance(account.getBalance() - amount);

// Encapsulated: the "balance never goes negative" invariant is guarded in exactly one place
public class Account {
    private BigDecimal balance = BigDecimal.ZERO;

    public void withdraw(BigDecimal amount) {
        if (amount.signum() <= 0) throw new IllegalArgumentException("amount must be > 0");
        if (balance.compareTo(amount) < 0) throw new IllegalStateException("insufficient funds");
        balance = balance.subtract(amount);
    }

    public BigDecimal balance() { return balance; }
}
Read in post: Object-oriented programming
Edge caseMidStatic methods are hidden, not overriddenA static method with the same signature in a subclass only hides the parent's. Which one runs depends on the declared type, not the runtime type.

A static method with the same signature in a subclass only hides the parent's. Which one runs depends on the declared type, not the runtime type.

class Parent { static String who() { return "Parent"; } }
class Child extends Parent { static String who() { return "Child"; } }
Parent p = new Child();
p.who();   // "Parent": statics are resolved by declared type, with no dynamic dispatch
Read in post: Object-oriented programming
Edge caseJuniorlist.remove(1) on a List<Integer> removes by indexWith a List<Integer, list.remove(1) removes the element at index 1, because remove(int index) is a closer match than remove(Object o). To remove the value 1, write list.remove(Integer.valueOf(1)).

With a List<Integer>, list.remove(1) removes the element at index 1, because remove(int index) is a closer match than remove(Object o). To remove the value 1, write list.remove(Integer.valueOf(1)).

Read in post: Object-oriented programming
Edge caseMidOverloads are resolved in three phases: widening, then boxing, then varargsWhen several overloads match, the compiler searches in order: (1) an exact match or primitive widening (int → long), (2) boxing/unboxing, (3) varargs. Within a phase it picks the most specific method. You can't overload on the return type alone (int add(int, int) plus double add(int, int) is a duplicate-method error),

When several overloads match, the compiler searches in order: (1) an exact match or primitive widening (int → long), (2) boxing/unboxing, (3) varargs. Within a phase it picks the most specific method.

static void m(long x)    { }   // m(5) picks this one: widening beats boxing
static void m(Integer x) { }
static void k(Integer x) { }   // k(5) picks this one: boxing beats varargs
static void k(int... x)  { }
static void n(Object o)  { }
static void n(String s)  { }   // n(null) picks String: the most specific
// With both p(String) and p(Integer), p(null) fails: reference to p is ambiguous

You can't overload on the return type alone (int add(int, int) plus double add(int, int) is a duplicate-method error), because add(1, 2) gives the compiler no way to choose. Adding an overload to a public API can silently change which method old code calls the next time it's compiled.

Read in post: Object-oriented programming
TILSeniorThe JIT makes monomorphic virtual calls almost freeAn instance method call compiles to invokevirtual. Each class has a vtable (virtual method table), and at runtime the JVM looks up the entry for the object's actual class. The JIT goes further: a call site that has only ever seen one class (a monomorphic call site) gets the method inlined, so polymorphism costs almost

An instance method call compiles to invokevirtual. Each class has a vtable (virtual method table), and at runtime the JVM looks up the entry for the object's actual class. The JIT goes further: a call site that has only ever seen one class (a monomorphic call site) gets the method inlined, so polymorphism costs almost nothing.

Read in post: Object-oriented programming
Trade-offSeniorDowncasts all over the code mean polymorphism is missingA chain of if (x instanceof A) ... else if (x instanceof B) ... repeated across the codebase means the behavior lives outside the types. Add a subclass and you must hunt down every chain; miss one and it silently does the wrong thing. Push the behavior into the type (an abstract method like shape.area()): best when the

A chain of if (x instanceof A) ... else if (x instanceof B) ... repeated across the codebase means the behavior lives outside the types. Add a subclass and you must hunt down every chain; miss one and it silently does the wrong thing.

  • Push the behavior into the type (an abstract method like shape.area()): best when the set of subclasses is open and the behavior belongs to the object.
  • Sealed hierarchy + pattern-matching switch (Java 21): best when the set of cases is closed (Success | Failure) and the logic belongs to the caller (mapping to an HTTP response or a DTO). The compiler checks exhaustiveness, so adding a subclass breaks every incomplete switch at compile time.
  • instanceof is still fine at system boundaries: equals(Object o), an Object coming from a library, classifying exceptions.
Read in post: Object-oriented programming
Edge caseMidFields aren't polymorphic: field access uses the declared typeOnly instance methods are picked by the runtime type; fields are picked by the declared type. A subclass field with the same name merely hides the parent's, and the object ends up with two separate fields. How to avoid it: keep fields private, access them through methods, and never reuse a field name between parent and

Only instance methods are picked by the runtime type; fields are picked by the declared type. A subclass field with the same name merely hides the parent's, and the object ends up with two separate fields.

class Parent { String name = "parent"; String name() { return name; } }
class Child extends Parent {
    String name = "child";                       // hides Parent's field
    @Override String name() { return name; }
}

Parent p = new Child();
p.name;            // "parent": field chosen by the declared type Parent
p.name();          // "child":  method chosen by the runtime type Child
((Child) p).name;  // "child"

How to avoid it: keep fields private, access them through methods, and never reuse a field name between parent and child.

Read in post: Object-oriented programming
InterviewJuniorWhat are the four pillars of OOP? Give an example of each.

Encapsulation, inheritance, polymorphism and abstraction.

  • Encapsulation: Account.withdraw() checks the balance itself.
  • Inheritance: Dog extends Animal.
  • Polymorphism: shape.area() runs the version matching the object's real type.
  • Abstraction: code depends on a PaymentGateway interface without knowing whether Stripe or VNPay sits behind it.
Read in post: Object-oriented programming
InterviewJuniorDoes Java support multiple inheritance? What is super for?

Not for classes: a class can extend only one class, but it can implement many interfaces. super calls the parent's constructor or methods.

Single inheritance avoids the "diamond problem" when two parents carry conflicting state or implementations. super(...) must be the first statement of a constructor; leave it out and the compiler inserts a no-arg super(). super.method() calls the parent's version from inside an override. Constructors aren't inherited, so a subclass always declares its own.

Read in post: Object-oriented programming
InterviewMidWhat is the difference between overloading and overriding? Can static methods be overridden?

Overloads are picked at compile time from the arguments' declared types; overrides at runtime from the object's actual type. Static methods can't be overridden, only hidden.

Overloading means the same name with different parameters. Overriding means a subclass redefines a method with the same signature. With statics (hiding), which one runs depends on the variable's declared type.

Read in post: Object-oriented programming
InterviewMidGiven Animal a = new Dog();, which methods can a call? When is a downcast safe?

The declared type Animal decides what you can call, the runtime type Dog decides which version runs. A downcast is safe only when the object really is the target type.

a can't call Dog's own wagTail(), but a.sound() runs Dog's version. Fields aren't polymorphic: a.name reads the field declared in Animal. A wrong downcast throws ClassCastException; check with instanceof, or since Java 16 write if (a instanceof Dog d). instanceof on null returns false.

Read in post: Object-oriented programming
InterviewMidWhen several overloads match a call, which one does the compiler pick?

Three phases: exact match or widening, then boxing/unboxing, then varargs; within a phase, the most specific method wins.

  • m(long) and m(Integer): m(5) calls m(long).
  • n(Object) and n(String): n(null) calls n(String).
  • p(String) and p(Integer): p(null) is an ambiguity error.

All of this uses the declared types of the arguments, not their runtime types, and you can't overload on the return type alone.

Read in post: Object-oriented programming
InterviewSeniorWhat does "favor composition over inheritance" mean? Give an example of inheritance causing harm.

Inheritance ties a subclass to its parent's implementation details (fragile base class); composition depends only on the public API, so it's more flexible.

  • A counting subclass of HashSet double-counts because addAll calls add internally.
  • Stack extends Vector exposes methods that break LIFO.

Composition (wrapping an object and delegating to it) can also be swapped at runtime. Inherit only for a real is-a relationship that respects the Liskov Substitution Principle.

Read in post: Object-oriented programming
InterviewSeniorHow does dynamic dispatch work in the JVM? Is it expensive?

The JVM looks up the vtable/itable for the object's actual class, and the JIT inlines call sites that see few types, so it's rarely a bottleneck.

Instance calls use invokevirtual/invokeinterface. The JIT profiles each call site: monomorphic (one type) and bimorphic (two types) sites get inlined behind a cheap type check. Only megamorphic sites pay for a real table lookup.

Read in post: Object-oriented programming
InterviewSeniorA square is a rectangle in geometry. So what's wrong with Square extends Rectangle, and when is it acceptable?

LSP requires a subclass to honor every behavioral contract of its parent, and Square can't honor "width and height change independently". It's acceptable once shapes are immutable.

Changing a Square's height also changes its width, so code written against Rectangle gets wrong results. If shapes are immutable (no setters, changes return new objects), the contract shrinks to reads like area(), which a square satisfies. In practice I usually prefer a sealed interface Shape with sibling records: simpler, and a switch over it is checked for exhaustiveness.

Read in post: Object-oriented programming
Trade-offJuniorStatic vs instance membersThe deciding question: does this value or behavior depend on the state of a particular object? name and age differ for every animal, so they are instance fields. Stateless utilities (Math.max, List.of, Integer.parseInt), constants (static final) and factory methods (methods that create objects instead of a bare new, e.

The deciding question: does this value or behavior depend on the state of a particular object?

  • name and age differ for every animal, so they are instance fields.
  • Stateless utilities (Math.max, List.of, Integer.parseInt), constants (static final) and factory methods (methods that create objects instead of a bare new, e.g. Order.create(...)) are good static candidates.
Read in post: Object-oriented programming
Edge caseMidMutable static state is a global variable in disguiseMutable static state (static Map cache) is a global variable: hard to test (you can't mock it, and data leaks between tests), not thread-safe, and a memory leak if it keeps growing. In Spring, let the container manage singleton beans instead of using statics.

Mutable static state (static Map cache) is a global variable: hard to test (you can't mock it, and data leaks between tests), not thread-safe, and a memory leak if it keeps growing. In Spring, let the container manage singleton beans instead of using statics.

Read in post: Object-oriented programming
Trade-offMidPackage by feature vs package by layerYour package layout expresses the architecture. Packaging by feature (order, payment) is usually easier to maintain than packaging by layer (controller, service, repository), because more classes can stay package-private.

Your package layout expresses the architecture. Packaging by feature (order, payment) is usually easier to maintain than packaging by layer (controller, service, repository), because more classes can stay package-private.

Read in post: Object-oriented programming
Edge caseJuniorprotected also opens access to the whole packageprotected also grants access to the whole package, not just to subclasses. Many people don't realize this.

protected also grants access to the whole package, not just to subclasses. Many people don't realize this.

Read in post: Object-oriented programming
Edge caseMidAcross packages, protected only works through a subclass-typed referenceA subclass in another package can read a protected field of its parent through this (or a variable of the subclass's own type), but not through a variable typed as the parent: The reason: protected gives a subclass access to its "own" part of the hierarchy, not the right to read every object of the parent class. Inside

A subclass in another package can read a protected field of its parent through this (or a variable of the subclass's own type), but not through a variable typed as the parent:

package test;
class Sub extends model.Emp {
    void f(model.Emp other) {
        System.out.println(this.department);   // OK
        System.out.println(other.department);  // error: department has protected access in Emp
    }
}

The reason: protected gives a subclass access to its "own" part of the hierarchy, not the right to read every object of the parent class. Inside the same package the restriction doesn't apply, because protected includes package access.

Read in post: Object-oriented programming
InterviewJuniorWhat is the difference between a class and an object?

A class is a blueprint; an object is a concrete instance created from it with new.

The class defines fields and methods. The object has its own state on the heap. One class can produce many objects.

Read in post: Object-oriented programming
InterviewJuniorHow does a constructor differ from a regular method? When do you get a default constructor?

A constructor has the class's name, no return type, and runs only during object creation. The default constructor is generated only if the class declares no constructors at all.

Once you write a constructor with parameters, you must add a no-arg one yourself if you need it.

Read in post: Object-oriented programming
InterviewJuniorWhat are Java's four access levels?

private (same class), package-private/default (same package), protected (same package plus subclasses), public (everywhere).

A top-level class can only be public or package-private.

Read in post: Object-oriented programming
InterviewJuniorCan a static method call an instance method directly? Why is main static?

No: a static method isn't tied to any object, so there's no this; you need an object (new App().run()). main is static because the JVM calls it before any object of the class exists.

The other direction is fine: instance methods call static methods freely. A static variable has exactly one copy per class, initialized once when the class is loaded.

Read in post: Object-oriented programming
InterviewMidWhere can a protected member be accessed from? Can a subclass in another package read a protected field through a parent-typed variable?

protected means package-private access plus subclasses in other packages. Through a parent-typed variable, no.

  • Inside the same package, every class can use it like default access.
  • A subclass in another package can only reach it through this or a reference typed as that subclass; through Parent other it's a has protected access error.
  • Because it opens the whole package, protected is wider than most people think; usually keep fields private and expose only protected methods to subclasses.
Read in post: Object-oriented programming
InterviewSeniorWhat problems does static mutable state cause in a Spring application?

It's global state shared across every request and thread, so it invites race conditions, poor testability and memory leaks.

  • State leaks between tests and can't be mocked.
  • Ever-growing maps leak memory; in multi-classloader environments it may never be released.
  • Use container-managed singleton beans, bounded caches (Caffeine), or external stores such as Redis or a database.
Read in post: Object-oriented programming
Edge caseMidIn a composition, the whole creates its parts, not the part classThe slides get this backwards: they say the attributes "must be initialized inside the part class". It should be inside the whole: the whole creates the part (lines.add(new OrderLine(...)) inside Order) and controls its lifecycle.

The slides get this backwards: they say the attributes "must be initialized inside the part class". It should be inside the whole: the whole creates the part (lines.add(new OrderLine(...)) inside Order) and controls its lifecycle.

Read in post: Object-oriented programming
Edge caseMidA class whose setters take its parts from outside is aggregation, not compositionThe slides' composition example is a Human made of a Head and a Body, yet Human has public setHead(Head) and setBody(Body). The parts are created outside and plugged in, so they can be shared or swapped: that's aggregation. A real composition has the whole create its parts and expose no setters:

The slides' composition example is a Human made of a Head and a Body, yet Human has public setHead(Head) and setBody(Body). The parts are created outside and plugged in, so they can be shared or swapped: that's aggregation. A real composition has the whole create its parts and expose no setters:

public final class Human {
    private final Head head;
    private final Body body;

    public Human(String name) {
        this.head = new Head(name);   // the parts are born with the whole
        this.body = new Body();
    }
    // no setHead/setBody; if callers need to read them, return copies or immutable values
}
Read in post: Object-oriented programming
Trade-offMidAggregation vs association: decide by who owns the lifecycleAggregation: the whole holds the part but the part lives independently. Association: two classes just know each other long-term. The line is blurry, and many people draw them the same way. What matters is not the symbol but who is responsible for creating and destroying the object: that decides your database cascades a

Aggregation: the whole holds the part but the part lives independently. Association: two classes just know each other long-term. The line is blurry, and many people draw them the same way. What matters is not the symbol but who is responsible for creating and destroying the object: that decides your database cascades and how you write the code.

Read in post: Object-oriented programming
Edge caseMidBidirectional associations cause sync bugs, JSON recursion and N+1 queriesBidirectional associations (Customer.orders plus Order.customer) cost effort to keep in sync, can cause infinite recursion when serialized to JSON, and invite N+1 queries in JPA. Keep them one-way unless you really need both.

Bidirectional associations (Customer.orders plus Order.customer) cost effort to keep in sync, can cause infinite recursion when serialized to JSON, and invite N+1 queries in JPA. Keep them one-way unless you really need both.

Read in post: Object-oriented programming
Edge caseMidA depends on B when a change in B can force A to changeThe slides have two slips: the section is titled "association (dependencies)" when it's about dependency, and it says "if changing class A affects class B, then A depends on B", which is backwards. Correctly: A depends on B when a change in B may force A to change. The dashed arrow points from A (the user) to B (the th

The slides have two slips: the section is titled "association (dependencies)" when it's about dependency, and it says "if changing class A affects class B, then A depends on B", which is backwards. Correctly: A depends on B when a change in B may force A to change. The dashed arrow points from A (the user) to B (the thing being used).

Read in post: Object-oriented programming
Trade-offMidComposition over inheritanceComposition lets you change behavior at runtime (pass in a different List), is easier to test, and doesn't drag in unwanted parent methods. It's the basis of Decorator, Strategy and Adapter.
// Inheritance: InstrumentedList is chained to ArrayList's implementation details
class InstrumentedList<E> extends ArrayList<E> { ... }

// Composition: wraps any List and depends only on the interface's public API
final class CountingList<E> {
    private final List<E> delegate;
    private int added;
    CountingList(List<E> delegate) { this.delegate = delegate; }
    void add(E e) { delegate.add(e); added++; }
    int added() { return added; }
}

Composition lets you change behavior at runtime (pass in a different List), is easier to test, and doesn't drag in unwanted parent methods. It's the basis of Decorator, Strategy and Adapter.

Read in post: Object-oriented programming
InterviewJuniorWhat do +, -, # and ~ mean in a UML class diagram?

Public, private, protected and package-private, respectively.

Static members are underlined, abstract methods are italic, and / marks a derived attribute (computed from other data).

Read in post: Object-oriented programming
InterviewJuniorHow are inheritance and interface realization drawn differently in UML?

Both use a hollow triangle; inheritance is a solid line, realization a dashed one.

Inheritance (generalization) goes from the subclass to the parent; realization goes from the class to the interface. With several subclasses you can draw one arrow each or merge them into one shared triangle at the parent; both mean the same thing.

Read in post: Object-oriented programming
InterviewMidHow do composition and aggregation differ, and how does that show up in code?

Composition: the whole creates and owns the part, which dies with it. Aggregation: the part is created elsewhere, passed in, and lives independently.

Examples: Order and OrderLine (composition), Team and Player (aggregation, can be shared). In code, the difference is who calls new and who owns the lifecycle. In the database, it shows up as cascade deletes and orphan removal.

Read in post: Object-oriented programming
InterviewMidHow do association and dependency differ when you look at the code?

Association holds a long-lived reference (a field); dependency only uses B temporarily (parameter, local variable, return type, static call).

Examples: Driver has a Car field; ReportService.export(report, renderer) only receives the renderer as a parameter. Direction: A depends on B when a change in B can force A to change, and the dashed arrow goes from A to B.

Read in post: Object-oriented programming
InterviewMidCar has a public setEngine(Engine). Is Car–Engine a composition?

Not really: if the engine is created elsewhere, plugged in, and can be swapped or shared, Car doesn't control its lifecycle, so it's aggregation.

For composition, Car must create its own Engine (in its constructor or its own factory), expose no setter that takes an engine from outside, and the engine goes away with the car. In persistence, that maps to cascades and orphan removal.

Read in post: Object-oriented programming
InterviewSeniorHow do you decide between composition and aggregation, and how does that affect persistence design?

By lifecycle and the consistency boundary: a part that only makes sense inside the whole is composition (a DDD aggregate); a part that lives independently is referenced by ID.

  • Composition: invariants are checked together; saved and deleted together, cascaded, modified only through the aggregate root, within one transaction.
  • Independent part referenced from many places: hold its ID instead of the object, and don't cascade, so aggregates stay small and you don't lock too many rows.
Read in post: Object-oriented programming
InterviewSeniorOutside interviews, when do you draw a UML class diagram, and how detailed do you make it?

When designing a new module with many interacting classes or reviewing a large change, and only the parts that matter for the decision at hand.

  • Example modules: a domain model, an aggregate, a set of strategies. Leave out getters, setters and minor fields.
  • Keep diagrams as code (Mermaid, PlantUML) in the repo so they're reviewed with the code; a diagram that has drifted from the code is worse than none.
  • At the system level (services, databases, queues), use an architecture diagram such as C4 rather than a class diagram.
Read in post: Object-oriented programming
TILJuniorArray access is O(1) and cache-friendlyThe address of element i = the array's base address + i × element size, which the CPU computes instantly. Contiguous elements also play well with the CPU cache (a small, very fast memory inside the CPU that loads whole blocks of neighbouring data). That's why iterating over an int[] is much faster than over a LinkedLis

The address of element i = the array's base address + i × element size, which the CPU computes instantly. Contiguous elements also play well with the CPU cache (a small, very fast memory inside the CPU that loads whole blocks of neighbouring data). That's why iterating over an int[] is much faster than over a LinkedList<Integer>, even though both are O(n).

Read in post: Java basics
Edge caseJuniorA 3D point needs a 1D array of length 3, not a 3D arrayThe slides say "to store the coordinates of a point in Oxyz space, use a 3D array". That example is off: three coordinates need a one-dimensional array of length 3 (double[] p = {x, y, z}), or better, record Point(double x, double y, double z). A 3D array is for volumetric data: the temperature at every cell [x][y][z]

The slides say "to store the coordinates of a point in Oxyz space, use a 3D array". That example is off: three coordinates need a one-dimensional array of length 3 (double[] p = {x, y, z}), or better, record Point(double x, double y, double z). A 3D array is for volumetric data: the temperature at every cell [x][y][z] of a grid, or an RGB image [height][width][3].

Read in post: Java basics
Edge caseMidtoUpperCase() without arguments depends on the machine's locale"title".toUpperCase() uses the JVM's default locale (language and region setting). With a Turkish locale the result is "TİTLE" (a dotted capital I), and "TITLE".toLowerCase() gives "tıtle". Code that compares keys, HTTP headers or enum names, such as status.toUpperCase().equals("ACTIVE"), breaks on a server with a diff

"title".toUpperCase() uses the JVM's default locale (language and region setting). With a Turkish locale the result is "TİTLE" (a dotted capital I), and "TITLE".toLowerCase() gives "tıtle". Code that compares keys, HTTP headers or enum names, such as status.toUpperCase().equals("ACTIVE"), breaks on a server with a different locale. For technical strings (not shown to users), always write toUpperCase(Locale.ROOT) or use equalsIgnoreCase.

Read in post: Java basics
InterviewJuniorWhat are the default element values of new int[3], new boolean[2] and new String[2]?

0, false and null.

Local variables have no default value; reading one before assignment is a compile error.

Read in post: Java basics
InterviewJuniorWhat is the difference between length, length() and size()?

array.length is a field of an array, string.length() is a method on String, list.size() is a method on collections.

string.length() returns the number of UTF-16 units (an emoji can count as 2). They differ because arrays are a special JVM type, while String and List are ordinary classes.

Read in post: Java basics
InterviewJuniorHow do you compare two strings, and two arrays, correctly?

Strings with equals; arrays with Arrays.equals (or Arrays.deepEquals for multi-dimensional arrays).

  • Strings: a == b only compares references (sometimes true thanks to the string pool, never rely on it). Write "CONST".equals(x) or Objects.equals(a, b) to be null-safe.
  • Arrays: an array's own equals also only compares references.
Read in post: Java basics
InterviewMidHow is a 2D array stored in Java? Why is row-by-row iteration faster than column-by-column?

A 2D array is an array of references, each row a separate 1D array; row-by-row iteration reads neighbouring cells, so it uses the cache well.

Rows can have different lengths. Elements within a row are contiguous, so row-major iteration uses CPU cache lines (the block of data the CPU loads at once) well. Column-major iteration hops between different objects and causes cache misses.

Read in post: Java basics
InterviewMidWhy is + concatenation in a loop slow? How do StringBuilder and StringBuffer differ?

Each s = s + x creates a new string and copies all the old content, so n concatenations cost O(n²); StringBuilder appends in amortized O(1), and StringBuffer does the same but synchronized.

  • StringBuilder keeps a growable array.
  • StringBuffer has the same API with every method synchronized, which is slightly slower and almost never needed, because a string under construction usually belongs to one thread.
  • For a few values on one line, just use +; since Java 9 the compiler emits an optimised invokedynamic call for it.
Read in post: Java basics
InterviewMidWhat does it mean that Arrays.copyOf makes a shallow copy? How do you copy a 2D array?

A shallow copy copies each cell's value; in an object array or a 2D array the cells are references, so the copy still shares the underlying objects. To deep-copy a 2D array, copy each row.

Arrays.copyOf, clone() and System.arraycopy all copy shallowly. For a primitive array that's a real copy. For a 2D array, changing copy[0][0] changes original[0][0] too. Deep copy: int[][] copy = new int[m.length][]; for (int i = 0; i < m.length; i++) copy[i] = m[i].clone();.

Read in post: Java basics
InterviewSeniorWhy is ArrayList.add amortized O(1) when it sits on top of a fixed-size array?

Because each time it fills up, capacity grows by about 1.5 times, so the total copying across n adds is only O(n), or O(1) per add.

A single resize costs O(n), but it happens rarely. If you know the size up front, use new ArrayList<>(expectedSize) to avoid repeated copies and the extra garbage they create.

Read in post: Java basics
InterviewSeniorWhich algorithms does Arrays.sort use for primitive and object arrays, and why do they differ?

Primitives use dual-pivot quicksort (fast, memory-light, not stable); objects use TimSort (stable). They differ because only objects need equal elements to keep their order.

  • Two identical 5s can't be told apart, so instability doesn't matter for primitives.
  • TimSort is stable (equal elements keep their original order, which matters when you sort by several criteria in turn), very fast on partially ordered data, at the cost of up to n/2 extra memory.
  • For very large arrays there's Arrays.parallelSort, which runs on the ForkJoinPool.
Read in post: Java basics
Edge caseSeniorInner classes and lambdas hold a hidden reference to the outer object and can leak memoryInner classes, anonymous classes and lambdas that use this or a field all hold a strong reference to the outer object. Put them somewhere long-lived (a listener on a static event bus, a task on a never-ending executor, a cache entry) and the outer, with everything it holds, is never garbage-collected. Experiment: a Rep

Inner classes, anonymous classes and lambdas that use this or a field all hold a strong reference to the outer object. Put them somewhere long-lived (a listener on a static event bus, a task on a never-ending executor, a cache entry) and the outer, with everything it holds, is never garbage-collected.

Experiment: a ReportJob holding a 50 MB buffer registers an inner-class listener doing handled++; 100 jobs with -Xmx512m end in OutOfMemoryError. Fix: make the listener a static nested class that receives only what it needs (an AtomicInteger), and always unsubscribe. A heap dump shows the retention path EventBus.LISTENERS -> OnPriceChanged.this$0 -> ReportJob.

Read in post: Nested classes in Java
TILSeniorSince JDK 18, javac drops this$0 when the inner class doesn't use the outerBefore JDK 18, every inner class and anonymous class in a non-static context had a this$0 field, used or not. Since JDK 18 (JDK-8271623), javac keeps it only when the class body actually uses the outer instance; the exception is Serializable classes, which always keep it. Check with Inner.class.getDeclaredFields(): an

Before JDK 18, every inner class and anonymous class in a non-static context had a this$0 field, used or not. Since JDK 18 (JDK-8271623), javac keeps it only when the class body actually uses the outer instance; the exception is Serializable classes, which always keep it.

Check with Inner.class.getDeclaredFields(): an empty inner class has no this$0, but as soon as the body reads one outer field, it appears. So an anonymous HashMap (which is Serializable) in a non-static method always holds the outer object. Don't rely on this optimization to avoid leaks; static nested is still the default.

Read in post: Nested classes in Java
Edge caseMidDouble brace initialization creates an anonymous subclass that holds the outer objectnew HashMap<() {{ put("a", 1); }} is actually an anonymous subclass of HashMap with an instance initializer. Every use site produces a new class (Outer$1, Outer$2...), and getClass() is no longer HashMap. Because HashMap is Serializable, in a non-static method the object always carries a this$0 pointing at the outer, e

new HashMap<>() {{ put("a", 1); }} is actually an anonymous subclass of HashMap with an instance initializer. Every use site produces a new class (Outer$1, Outer$2...), and getClass() is no longer HashMap.

Because HashMap is Serializable, in a non-static method the object always carries a this$0 pointing at the outer, even on JDK 18+. Return that map or cache it and you keep the outer alive. Use Map.of(...), List.of(...) (immutable), or create the map and put normally.

Read in post: Nested classes in Java
Edge caseMidWorking around effectively final with a one-element array or AtomicInteger is usually a design smellint[] counter = {0}; list.forEach(x - counter[0]++); compiles because counter is never reassigned, only the array contents change. But it smuggles shared mutable state into the lambda: with parallelStream() or an executor, counter[0]++ is a race condition that gives wrong results with no error. With streams, use the bu

int[] counter = {0}; list.forEach(x -> counter[0]++); compiles because counter is never reassigned, only the array contents change. But it smuggles shared mutable state into the lambda: with parallelStream() or an executor, counter[0]++ is a race condition that gives wrong results with no error.

With streams, use the built-in reductions (count(), sum(), reduce, Collectors.groupingBy(..., counting())). If you really need a counter shared across threads, use AtomicInteger/LongAdder deliberately, not as a trick to satisfy the compiler. See the threads and concurrency post.

Read in post: Nested classes in Java
Trade-offMidAnonymous class or lambdaLambda: the default for any functional interface. Short, this refers to the enclosing class, no extra class file, and no outer capture unless it uses the outer. Anonymous class: when you need to extend an (abstract) class, implement an interface with several abstract methods, keep your own fields (a counter belonging t
  • Lambda: the default for any functional interface. Short, this refers to the enclosing class, no extra class file, and no outer capture unless it uses the outer.
  • Anonymous class: when you need to extend an (abstract) class, implement an interface with several abstract methods, keep your own fields (a counter belonging to the handler), or need this to be the handler (self-unsubscribing with bus.unsubscribe(this)).
  • Method reference (Order::total, this::handle): when the lambda just calls one existing method; even easier to read than a lambda.
  • Once the logic grows beyond a few lines, extract a named method, or a separate class you can test on its own.
Read in post: Nested classes in Java
InterviewJuniorWhat's the difference between a static nested class and an inner class?

A static nested class isn't tied to any outer instance; an inner class is tied to one and keeps a hidden reference to it.

You create a static nested class with new Outer.Nested() and it can only use the outer's static members. You create an inner class with outer.new Inner() and it can use all of the outer's fields. Default to static nested and only use inner when you really need the outer's state.

Read in post: Nested classes in Java
InterviewJuniorHow do you create an inner-class object from outside the outer class? How does a local class differ from an anonymous class?

From outside you need an outer object: order.new CustomerInfo(...). A local class is named and reusable; an anonymous class is unnamed and used once.

Inside an instance method of the outer class, plain new CustomerInfo(...) works (an implicit this.new). A local class is declared inside a method, has constructors and can be reused several times in that method. An anonymous class is declared and instantiated in one expression, has no constructor of its own (it uses an instance initializer), and either extends one class or implements one interface.

Read in post: Nested classes in Java
InterviewMidWhat does this refer to inside a lambda versus inside an anonymous class?

In an anonymous class, this is the anonymous object itself; in a lambda, this is the enclosing class instance.

A lambda doesn't introduce a new scope (which is also why it can't redeclare a local variable name from outside). In practice: if a handler needs to unsubscribe itself with unsubscribe(this), you need an anonymous class; and toString() called inside a lambda is the enclosing class's.

Read in post: Nested classes in Java
InterviewMidWhy must local variables used in a lambda be effectively final?

Because the lambda gets a copy of the variable's value, not the variable; allowing reassignment would make the copy and the original diverge.

A lambda may run after the method has returned, or on another thread, while locals live on the method's stack. Java forbids reassignment to avoid divergence and race conditions. Fields aren't restricted because the lambda captures this. The one-element-array workaround compiles but is usually bad design; with streams, use reduce or collectors.

Read in post: Nested classes in Java
InterviewMidWhy is a builder usually a static nested class?

Because a builder exists before the object it builds, so there's no outer instance to attach it to.

As an inner class you'd need an existing object just to create the builder, which makes no sense. As a nested class it can call the outer's private constructor, so only the builder can create objects and every validation goes through it. It lives in the outer's namespace (HttpCall.Builder), and being static it holds no hidden reference to any object.

Read in post: Nested classes in Java
InterviewSeniorDescribe a backend scenario where an inner class or lambda leaks memory, and how you'd find it.

An inner-class or field-using lambda listener registered on a static event bus or executor and never removed pins a large outer object forever. Find it with a heap dump and the path to GC roots.

  • Scenario: a report-processing object holding a lot of data registers a listener on a static event bus, or schedules it on a periodic executor without cancelling it. The listener holds this$0 or this, so the large object is never collected.
  • Symptom: heap usage after each full GC creeps up until an OOM.
  • Find it: take a heap dump, look at the dominator tree and the path to GC roots, and you'll see static field -> listener -> this$0 -> large object.
  • Fix: make the listener a static nested class that holds only what it needs, always unsubscribe (return an AutoCloseable handle), or use weak references where appropriate.
Read in post: Nested classes in Java
TILJuniorHibernate 6 detects the dialect itself; you don't need hibernate.dialectSince Hibernate 6 (Spring Boot 3), the dialect (each database's flavour of SQL) is inferred from the JDBC connection's metadata. MySQL8Dialect is deprecated and folded into MySQLDialect. The line spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect from older tutorials only produces a deprecation warning on

Since Hibernate 6 (Spring Boot 3), the dialect (each database's flavour of SQL) is inferred from the JDBC connection's metadata. MySQL8Dialect is deprecated and folded into MySQLDialect. The line spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect from older tutorials only produces a deprecation warning on Boot 3, so just delete it.

Read in post: ORM and JPA
Trade-offMidJPA id generation: IDENTITY vs SEQUENCE vs UUIDThe slides describe @GeneratedValue as "marks an auto-increment field"; it really chooses an id generation strategy: IDENTITY: the database's auto-increment, common with MySQL. Hibernate must run the INSERT immediately to learn the id, which disables JDBC batch inserts. SEQUENCE: a database sequence (PostgreSQL, Oracle

The slides describe @GeneratedValue as "marks an auto-increment field"; it really chooses an id generation strategy:

  • IDENTITY: the database's auto-increment, common with MySQL. Hibernate must run the INSERT immediately to learn the id, which disables JDBC batch inserts.
  • SEQUENCE: a database sequence (PostgreSQL, Oracle). Hibernate pre-allocates a block of ids (pooled optimizer, allocationSize=50), so inserts can be batched. The best choice when the database supports it. MySQL has no sequences; Hibernate emulates them with a table, which is slow.
  • UUID: ids generated in the application. Random UUID v4 fragments InnoDB's B-tree index; use a time-ordered one (UUID v7).
Read in post: ORM and JPA
Edge caseJuniorEnumType.ORDINAL corrupts old data when you insert an enum constantUse @Enumerated(EnumType.STRING) instead of the default ORDINAL. With ORDINAL, JPA stores the constant's position, so inserting a new constant in the middle silently corrupts existing data.

Use @Enumerated(EnumType.STRING) instead of the default ORDINAL. With ORDINAL, JPA stores the constant's position, so inserting a new constant in the middle silently corrupts existing data.

Read in post: ORM and JPA
Edge caseMidLombok @Data on an entity causes hidden queries and StackOverflowErrorThe toString/hashCode that @Data generates walk lazy associations, triggering surprise queries, LazyInitializationException, or a StackOverflowError on bidirectional relationships.

The toString/hashCode that @Data generates walk lazy associations, triggering surprise queries, LazyInitializationException, or a StackOverflowError on bidirectional relationships.

Read in post: ORM and JPA
Edge caseSeniorA hashCode based on a generated id makes entities "vanish" from a HashSetThe id is null before persist, so an id-based hashCode changes after saving and the object "vanishes" from a HashSet. Safe options: an immutable natural key if you have one, or compare by id while returning a class-constant hashCode (section 3.8).

The id is null before persist, so an id-based hashCode changes after saving and the object "vanishes" from a HashSet. Safe options: an immutable natural key if you have one, or compare by id while returning a class-constant hashCode (section 3.8).

Read in post: ORM and JPA
Edge caseMidA derived deleteBy... query loads every entity and deletes them one by onedeleteByStatus(...) (or removeBy...) SELECTs the matching entities and calls remove on each one, so cascades and lifecycle callbacks still run. Deleting 10,000 rows = one SELECT + 10,000 DELETEs, and the method must run inside @Transactional. For a single DELETE ... WHERE, use @Modifying @Query (which in turn bypasses

deleteByStatus(...) (or removeBy...) SELECTs the matching entities and calls remove on each one, so cascades and lifecycle callbacks still run. Deleting 10,000 rows = one SELECT + 10,000 DELETEs, and the method must run inside @Transactional. For a single DELETE ... WHERE, use @Modifying @Query (which in turn bypasses cascades and the persistence context; details in part 5 of the ORM series).

Read in post: ORM and JPA
Trade-offMidfindById vs getReferenceByIdfindById(id): SELECTs right away (or serves from the persistence context) and returns an Optional, so you know the row exists. Use it when you need the data or a clean 404. getReferenceById(id) (formerly getOne/getById, now deprecated): returns a proxy holding only the id, with no SELECT. Ideal when you just set a fore
  • findById(id): SELECTs right away (or serves from the persistence context) and returns an Optional, so you know the row exists. Use it when you need the data or a clean 404.
  • getReferenceById(id) (formerly getOne/getById, now deprecated): returns a proxy holding only the id, with no SELECT. Ideal when you just set a foreign key: course.setTeacher(teacherRepository.getReferenceById(teacherId)). The catch: a missing id surfaces late, as an EntityNotFoundException when you touch a proxy field or an FK violation on INSERT.
  • Rule of thumb: need the data or an early error? findById. Only need a reference to write an FK? getReferenceById.
Read in post: ORM and JPA
Trade-offMidMapping entities to DTOs in the service or in the controllerIn the service: the controller never holds an entity, LAZY associations are read while the transaction is open so there's no LazyInitializationException, and you can switch open-in-view off. The cost: the service returns API-shaped types (CourseResponse); when one service serves several kinds of client, add an internal
  • In the service: the controller never holds an entity, LAZY associations are read while the transaction is open so there's no LazyInitializationException, and you can switch open-in-view off. The cost: the service returns API-shaped types (CourseResponse); when one service serves several kinds of client, add an internal DTO layer or a mapper (MapStruct).
  • In the controller: the service looks "cleaner" and returns entities, but the controller reads LAZY associations after the transaction has closed, so you must pre-fetch everything or enable open-in-view (holding a connection for the whole request).
  • My default: services take and return DTOs; read-only screens query straight into DTO projections.
Read in post: ORM and JPA
Edge caseSeniorCalling a remote API inside @Transactional holds a connection and drains the poolA @Transactional method that calls a payment service over HTTP for 2 seconds holds a connection for those 2 seconds, even though it runs no SQL. With a pool of 10, ten concurrent requests are enough: the eleventh waits and then fails with SQLTransientConnectionException: ... Connection is not available, request timed o

A @Transactional method that calls a payment service over HTTP for 2 seconds holds a connection for those 2 seconds, even though it runs no SQL. With a pool of 10, ten concurrent requests are enough: the eleventh waits and then fails with SQLTransientConnectionException: ... Connection is not available, request timed out after 30000ms. Spring grabs the connection as soon as the method is entered (to switch off autocommit), not at the first SQL statement. The fix: make remote calls before or after the transaction, and always set timeouts on the HTTP client.

Read in post: ORM and JPA
Trade-offMidddl-auto=update vs Flyway vs Liquibaseddl-auto=update: no SQL to write, but it never drops or renames columns (renaming a field adds a new column and strands the data in the old one), doesn't migrate data, keeps no history, can't be reviewed, and lets environments drift. Only for prototypes. Flyway: plain SQL files, readable at a glance. Rolling back means
  • ddl-auto=update: no SQL to write, but it never drops or renames columns (renaming a field adds a new column and strands the data in the old one), doesn't migrate data, keeps no history, can't be reviewed, and lets environments drift. Only for prototypes.
  • Flyway: plain SQL files, readable at a glance. Rolling back means a new forward migration (undo migrations are a paid feature).
  • Liquibase: XML/YAML/SQL changelogs, declarative rollback, SQL generation for many databases; more powerful, more complex.
Read in post: ORM and JPA
Edge caseMidEditing a migration that has already run stops the app from startingChange V1createcourses.sql after it has run, and the next startup fails with Validate failed: Migrations have failed validation (checksum mismatch). Applied migrations are immutable: to change something, add a new V3... file. Only reach for flyway repair when you know exactly why (say, you edited a comment).

Change V1__create_courses.sql after it has run, and the next startup fails with Validate failed: Migrations have failed validation (checksum mismatch). Applied migrations are immutable: to change something, add a new V3__... file. Only reach for flyway repair when you know exactly why (say, you edited a comment).

Read in post: ORM and JPA
Edge caseSeniorReading a Hibernate proxy's fields directly in equals always gives nullFor a lazy association, course.getTeacher() returns a proxy (a Hibernate-generated subclass) whose own fields are never populated; only method calls are forwarded to the real object. So id.equals(other.id) reads the proxy's id field, always null, and the comparison is wrong. Go through the getter other.getId() (Hiberna

For a lazy association, course.getTeacher() returns a proxy (a Hibernate-generated subclass) whose own fields are never populated; only method calls are forwarded to the real object. So id.equals(other.id) reads the proxy's id field, always null, and the comparison is wrong. Go through the getter other.getId() (Hibernate returns a proxy's id without a query), and check the type with instanceof instead of getClass() != o.getClass().

Read in post: ORM and JPA
InterviewJuniorWhat's the difference between JPA and Hibernate?

JPA is a specification; Hibernate is one implementation of it.

JPA (Jakarta Persistence) is a set of interfaces and annotations that define how objects map to tables. Hibernate implements it and adds features of its own. Code written against the JPA API can switch to another implementation such as EclipseLink. Spring Data JPA sits on top and generates repositories.

Read in post: ORM and JPA
InterviewJuniorWhy does an entity need a no-arg constructor?

Because Hibernate creates the object via reflection when reading from the database, then sets its fields.

The constructor can be protected so outside code can't create empty objects. Hibernate also creates proxies (subclasses) for lazy loading, so the class must not be final.

Read in post: ORM and JPA
InterviewJuniorWhy shouldn't you use ddl-auto=update in production?

Because it never drops or renames columns, doesn't migrate data, keeps no history and can't be reviewed.

Renaming a field just adds a new column and leaves the data in the old one; environments can drift apart. Production uses versioned migrations (Flyway, Liquibase) applied at deploy time, with Hibernate set to ddl-auto=validate so it only checks that the entities match the schema.

Read in post: ORM and JPA
InterviewMidWhat is a derived query? When do you switch to @Query?

A derived query is one Spring Data generates from the method name; switch to @Query when the name gets too long or needs something a name can't express.

Spring Data parses a name such as findByStatusAndTeacherId into JPQL at startup (a wrong field name stops the app from booting, so errors surface early). It's great for one or two conditions. Switch to @Query for joins or fetch joins, DTO projections, bulk updates/deletes, or database-specific features (native queries). For dynamic filters, use Specifications or Querydsl.

Read in post: ORM and JPA
InterviewMidHow do findById and getReferenceById differ?

findById SELECTs right away and returns an Optional; getReferenceById returns a proxy holding only the id, with no query.

findById (or the persistence context) tells you for sure the row exists. Use getReferenceById when you only need to set a foreign key and want to save a SELECT. If the id doesn't exist, the error only shows up when you touch a proxy field (EntityNotFoundException) or when the INSERT violates the FK.

Read in post: ORM and JPA
InterviewMidWhat is a connection pool? How many requests can a pool of 10 serve?

A pool keeps opened connections for reuse; how many requests it serves depends on how long each transaction holds a connection, not just on the number 10.

The pool avoids a TCP connect plus login per request. At most 10 transactions hold a connection at once; everyone else waits up to connection-timeout. By Little's law, if a transaction holds one for 20 ms, 10 connections serve about 500 transactions per second. That's why keeping transactions short matters more than growing the pool, and an oversized pool overloads the database.

Read in post: ORM and JPA
InterviewSeniorWhy does GenerationType.IDENTITY disable batch inserts? Which id strategy would you pick?

Because the id only exists after the INSERT runs, and Hibernate needs it as soon as you persist, so it inserts one row at a time.

Hibernate needs the id to put the entity in the persistence context. SEQUENCE with a pooled optimizer pre-allocates ids, so inserts batch nicely; that's the best choice on PostgreSQL/Oracle. On MySQL you usually live with IDENTITY, or generate time-ordered ids in the application (UUID v7, Snowflake) to avoid index fragmentation, plus Persistable so save doesn't issue a needless SELECT.

Read in post: ORM and JPA
InterviewSeniorHow do you implement equals/hashCode for a JPA entity?

Prefer an immutable natural key; with only a generated id, equals on a non-null id and a class-level constant hashCode.

equals returns true for the same object, or when the id is non-null and equals the other object's id. Read through the getter because proxies have empty fields, and check the type with instanceof because a proxy is a subclass. A constant hashCode doesn't change when the id is assigned on persist. Avoid Lombok's @Data/default @EqualsAndHashCode, which use every field, lazy associations included.

Read in post: ORM and JPA
InterviewSeniorHow do you rename a column on a large table without downtime?

Expand and contract over several releases, because during a rolling deploy two code versions run side by side and the schema must work with both.

  1. A migration adds the new column.
  2. The code writes both columns.
  3. Backfill old rows in small batches so the table isn't locked for long.
  4. The code reads the new column.
  5. Stop writing the old column.
  6. A later release drops it.

On MySQL, check whether the ALTER TABLE runs online (ALGORITHM=INSTANT/INPLACE), or use gh-ost or pt-online-schema-change for very large tables.

Read in post: ORM and JPA
Trade-offMidLoad-and-modify vs bulk @Modifying updateThe "standard" JPA way: load the entity, modify a field, and let dirty checking (Hibernate comparing the entity with its snapshot from load time) issue the UPDATE. Every update costs a SELECT; updating 10,000 rows means loading 10,000 entities. The fix: bulk update/delete with @Modifying + @Query (JPQL or native), one

The "standard" JPA way: load the entity, modify a field, and let dirty checking (Hibernate comparing the entity with its snapshot from load time) issue the UPDATE. Every update costs a SELECT; updating 10,000 rows means loading 10,000 entities.

The fix: bulk update/delete with @Modifying + @Query (JPQL or native), one SQL statement that touches many rows directly.

But "select first" isn't always bad. Load-and-modify gives you business validation, @Version, @PreUpdate callbacks, cascades and auditing; bulk updates skip all of it. If you only need to set a foreign key, getReferenceById(id) hands you a proxy without any SELECT.

Read in post: ORM and JPA
Edge caseMidJPQL FROM takes the entity name, not the table nameA bug in the slides' example: SELECT u FROM user u with a lowercase user. What follows FROM is the entity name, which defaults to the class name (User) and is case-sensitive. from user only works if you declared @Entity(name = "user"). Also, user is a reserved word in PostgreSQL, so name the table users.

A bug in the slides' example: SELECT u FROM user u with a lowercase user. What follows FROM is the entity name, which defaults to the class name (User) and is case-sensitive. from user only works if you declared @Entity(name = "user"). Also, user is a reserved word in PostgreSQL, so name the table users.

Read in post: ORM and JPA
TILMidSince Spring 6.1, omitting @Param needs the -parameters flagOne slide example omits @Param on an update method. That only works if the code is compiled with the -parameters flag (the Spring Boot parent POM turns it on). Since Spring 6.1, Spring no longer reads parameter names from debug info, so without the flag the app fails at runtime. Explicit @Param is the safe choice.

One slide example omits @Param on an update method. That only works if the code is compiled with the -parameters flag (the Spring Boot parent POM turns it on). Since Spring 6.1, Spring no longer reads parameter names from debug info, so without the flag the app fails at runtime. Explicit @Param is the safe choice.

Read in post: ORM and JPA
Edge caseSeniorBulk @Modifying queries bypass the persistence context, @Version and callbacksWhat the slides don't say but regularly causes bugs: They go straight to the database and bypass the persistence context (the EntityManager's in-memory cache of entities). Loaded entities keep stale values. clearAutomatically = true clears the context afterwards; flushAutomatically = true flushes pending changes first

What the slides don't say but regularly causes bugs:

  • They go straight to the database and bypass the persistence context (the EntityManager's in-memory cache of entities). Loaded entities keep stale values. clearAutomatically = true clears the context afterwards; flushAutomatically = true flushes pending changes first so they aren't lost.
  • They bypass @Version: the version isn't bumped (unless you write set u.version = u.version + 1), so optimistic locking can't protect you.
  • They bypass cascades and callbacks (@PreUpdate, @PreRemove, Envers auditing). Bulk-deleting a parent doesn't delete its children; the FK constraint will complain.
  • They bypass the per-entity second-level cache: Hibernate invalidates the whole cache region for that entity.
  • clearAutomatically has a cost too: it detaches every loaded entity, so changes made to them after the bulk statement are silently lost. The cart and checkout post hits exactly this with the cart: keep only flushAutomatically, then refresh any entity that needs the new values.
Read in post: ORM and JPA
TILMidJPQL isn't slow because of translation: query plans are cachedThe slides say JPQL is "slower than native queries because it has to be translated to SQL". Not really accurate: translation happens once and is kept in the query plan cache. Real slowness comes from the generated SQL (extra joins, extra columns, no vendor features) and from results being managed entities (snapshots, d

The slides say JPQL is "slower than native queries because it has to be translated to SQL". Not really accurate: translation happens once and is kept in the query plan cache. Real slowness comes from the generated SQL (extra joins, extra columns, no vendor features) and from results being managed entities (snapshots, dirty checking).

Read in post: ORM and JPA
Trade-offMidDerived query vs JPQL vs native query vs SpecificationFor truly complex reporting, consider jOOQ or JdbcClient (Spring 6.1+).
Derived query JPQL @Query Native @Query Specification / Criteria
Simple lookups Best Fine Overkill Overkill
Joins, group by Very limited Good Good Possible but verbose
Dynamic conditions No Poor Poor Best
Vendor features No Limited Full No
Checked at startup Yes Yes (parsed on boot) No Yes (type-safe with the metamodel)
Database lock-in No No Yes No

For truly complex reporting, consider jOOQ or JdbcClient (Spring 6.1+).

Read in post: ORM and JPA
Edge caseMid(:p is null or col = :p) defeats index selectionA popular shortcut to avoid: JPQL like where (:status is null or c.status = :status). Quick to write, but the database struggles to pick a good index for every combination. Also, like '%keyword%' can't use a B-tree index; real search belongs in a full-text index or Elasticsearch.

A popular shortcut to avoid: JPQL like where (:status is null or c.status = :status). Quick to write, but the database struggles to pick a good index for every combination. Also, like '%keyword%' can't use a B-tree index; real search belongs in a full-text index or Elasticsearch.

Read in post: ORM and JPA
Edge caseMid@Transactional is ignored on self-invocationSelf-invocation. Calling this.method() doesn't go through the proxy, so @Transactional on the called method is silently ignored. Fix: move generateOne into another bean (cleanest), or open the transaction programmatically with TransactionTemplate.

Self-invocation. Calling this.method() doesn't go through the proxy, so @Transactional on the called method is silently ignored.

@Service
public class ReportService {
    public void generateAll() {
        for (long id : ids) {
            generateOne(id);     // called via "this": NO new transaction
        }
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void generateOne(long id) { ... }
}

Fix: move generateOne into another bean (cleanest), or open the transaction programmatically with TransactionTemplate.

Read in post: ORM and JPA
Edge caseMidChecked exceptions don't trigger rollback by defaultBy default Spring rolls back only on RuntimeException and Error. Throw an IOException or a custom checked exception and the transaction still commits. Use @Transactional(rollbackFor = Exception.class) or unchecked exceptions.

By default Spring rolls back only on RuntimeException and Error. Throw an IOException or a custom checked exception and the transaction still commits. Use @Transactional(rollbackFor = Exception.class) or unchecked exceptions.

Read in post: ORM and JPA
Edge caseSeniorSwallowing an inner transactional exception causes UnexpectedRollbackExceptionThe inner method joins the same transaction. When it throws through its proxy, Spring marks the whole transaction rollback-only, and catching the exception outside doesn't clear the mark. If the loyalty step should be independent, give it REQUIRESNEW, or better, do it asynchronously via an event or the outbox pattern.
@Transactional
public void placeOrder(...) {
    orderRepository.save(order);
    try {
        loyaltyService.addPoints(customerId); // also @Transactional (REQUIRED), throws RuntimeException
    } catch (RuntimeException e) {
        log.warn("Could not add points", e);  // looks like "ignore the error"
    }
}   // commit → UnexpectedRollbackException: the transaction was marked rollback-only

The inner method joins the same transaction. When it throws through its proxy, Spring marks the whole transaction rollback-only, and catching the exception outside doesn't clear the mark. If the loyalty step should be independent, give it REQUIRES_NEW, or better, do it asynchronously via an event or the outbox pattern.

Read in post: ORM and JPA
Edge caseSeniorREQUIRES_NEW can deadlock the connection poolThe outer transaction keeps its connection while the new one borrows a second. Under heavy load, every thread holds one connection and waits for another, the pool runs dry and the system hangs. Use it sparingly and size the pool accordingly.

The outer transaction keeps its connection while the new one borrows a second. Under heavy load, every thread holds one connection and waits for another, the pool runs dry and the system hangs. Use it sparingly and size the pool accordingly.

Read in post: ORM and JPA
Edge caseSeniorSlow calls inside @Transactional hold connections and locksMaking an HTTP call, sending an email or uploading a file inside @Transactional holds a database connection (and possibly row locks) the whole time. Do slow work outside the transaction, or use @TransactionalEventListener(phase = AFTERCOMMIT) to run it after commit.

Making an HTTP call, sending an email or uploading a file inside @Transactional holds a database connection (and possibly row locks) the whole time. Do slow work outside the transaction, or use @TransactionalEventListener(phase = AFTER_COMMIT) to run it after commit.

Read in post: ORM and JPA
TILSeniorreadOnly = true changes Hibernate's flush mode, it isn't just a hintWith Hibernate, Spring sets the flush mode to MANUAL and marks the session read-only: no snapshots, no dirty checking, less memory and CPU. With the MySQL driver it also sends SET SESSION TRANSACTION READ ONLY. A routing datasource can use it to send queries to a replica. But it does not stop you from running a @Modify

With Hibernate, Spring sets the flush mode to MANUAL and marks the session read-only: no snapshots, no dirty checking, less memory and CPU. With the MySQL driver it also sends SET SESSION TRANSACTION READ ONLY. A routing datasource can use it to send queries to a replica. But it does not stop you from running a @Modifying query inside (whether that fails depends on the database), so don't treat it as a security mechanism.

Read in post: ORM and JPA
Trade-offSeniorOptimistic vs pessimistic locking vs conditional UPDATE
Optimistic (@Version) Pessimistic (FOR UPDATE) Conditional UPDATE
Good fit Rare conflicts, read-heavy Frequent conflicts, "hot" resources Simple single-row operations
Cost without conflict Nearly zero Locks held, others wait Low
On conflict Exception, retry Wait (possible timeout, deadlock) 0 rows affected
Across requests (editing a form for 5 minutes) Yes (version travels with the DTO/ETag) No Not applicable
Risks Retry storms under load Deadlocks, connection starvation Skips entity logic
Read in post: ORM and JPA
Trade-offSeniorShould open-session-in-view stay onWhy you should turn it off: It holds a connection longer than needed: from the first database access until the end of the request, including rendering and calls to other services. Under load, the pool drains fast. It hides N+1: lazy loading in the view layer runs silently, one query at a time, in auto-commit mode outsi

Why you should turn it off:

  • It holds a connection longer than needed: from the first database access until the end of the request, including rendering and calls to other services. Under load, the pool drains fast.
  • It hides N+1: lazy loading in the view layer runs silently, one query at a time, in auto-commit mode outside any transaction.
  • It blurs layer boundaries: controllers and serializers quietly hit the database.

Turn it off with spring.jpa.open-in-view=false. Code that relied on it will throw LazyInitializationException, and that's a good thing: it points at exactly where you need a fetch join, entity graph or DTO projection in the service.

Read in post: ORM and JPA
InterviewJuniorHow does JPQL differ from SQL?

JPQL is written against entities and Java fields and is database-agnostic; SQL (a native query) is written against tables and columns and ties you to one database.

Hibernate translates JPQL to your database's SQL. A native query runs as-is and can use every feature of that database.

Read in post: ORM and JPA
InterviewJuniorWhat is @Modifying for?

It marks a @Query as an UPDATE/DELETE (or INSERT for native queries) so Spring Data calls executeUpdate() instead of expecting results.

It must run inside a transaction and returns the number of affected rows.

Read in post: ORM and JPA
InterviewJuniorWhen do derived queries stop being a good fit?

When method names get too long, when you need group by/having/subqueries/aggregates, or when filters are dynamic.

At that point switch to @Query (JPQL or native) or Specifications.

Read in post: ORM and JPA
InterviewMidWhat side effects does a @Modifying bulk update have?

It goes straight to the database, so the persistence context doesn't know, and it bypasses @Version, cascades, lifecycle callbacks and auditing.

Loaded entities keep stale values (use clearAutomatically); unflushed changes can be overwritten (use flushAutomatically).

Read in post: ORM and JPA
InterviewMidWhy doesn't @Transactional work when a method calls another method in the same class?

Because transactions are applied by the proxy wrapping the bean, and this.method() calls the real object directly, skipping the proxy.

Fix it by moving the method to another bean or using TransactionTemplate.

Read in post: ORM and JPA
InterviewMidDoes a transaction roll back on a checked exception?

Not by default: Spring rolls back only on RuntimeException and Error.

Declare rollbackFor to roll back on checked exceptions. If the exception is caught and swallowed inside the method, the proxy never sees it and the transaction commits.

Read in post: ORM and JPA
InterviewMidHow do optimistic and pessimistic locking differ?

Optimistic takes no lock and detects conflicts at write time with @Version; pessimistic locks the row on read with SELECT ... FOR UPDATE.

Optimistic issues WHERE version = ?; a conflict throws and you retry. It suits rare conflicts and flows spanning several requests. Pessimistic makes other transactions wait; it suits highly contended resources in short transactions.

Read in post: ORM and JPA
InterviewSeniorWhat is open-session-in-view and why turn it off?

OSIV keeps the EntityManager open for the whole request so lazy loading works in controllers and during serialization; turn it off because it holds connections long and hides N+1.

Under load the pool runs out, and the view layer hits the database outside a transaction. Turn it off with spring.jpa.open-in-view=false, fetch what you need in the service and return DTOs.

Read in post: ORM and JPA
InterviewSeniorExplain UnexpectedRollbackException.

A REQUIRED inner method throws a RuntimeException through its proxy, so the transaction is marked rollback-only; the outer method swallows it and commits, Spring sees the flag, rolls back and throws UnexpectedRollbackException.

If the inner work should fail independently, use REQUIRES_NEW (accepting the extra connection) or move it to asynchronous processing.

Read in post: ORM and JPA
InterviewSeniorWhat's the risk of REQUIRES_NEW under heavy load?

A connection-pool deadlock: the outer transaction is suspended but keeps its connection, and the new transaction needs a second one.

If every pooled thread is in that state, nobody can get a second connection and the system hangs until timeouts fire. Mitigate by limiting REQUIRES_NEW, sizing the pool above the number of threads that can nest transactions, or redesigning to avoid nesting.

Read in post: ORM and JPA
InterviewSeniorHow would you design a "limited seats" booking feature that's correct under concurrency?

It depends on contention; the simplest and fastest is a conditional UPDATE set seats = seats - 1 where id = ? and seats > 0, checking the affected row count.

  • Rich entity logic: @Version + retry for low contention, SELECT ... FOR UPDATE with a lock timeout for high contention.
  • Always back it with a unique constraint to block duplicate bookings.
  • Massive flash sale: move the counter to Redis (DECR) or a queue and write to the database asynchronously.
Read in post: ORM and JPA
Trade-offJuniorSearch with GET and query parameters or POST /searchUse GET with query parameters, not POST /hotels/search: search is a read-only, safe, idempotent operation. With GET it can be cached (CDN, browser), bookmarked and shared. The parameters build up step by step: ?city=hanoi → add &sleeps=2 → add &checkin=...&checkout=.... They're all filters, so they belong in the query

Use GET with query parameters, not POST /hotels/search: search is a read-only, safe, idempotent operation. With GET it can be cached (CDN, browser), bookmarked and shared.

The parameters build up step by step: ?city=hanoi → add &sleeps=2 → add &checkin=...&checkout=.... They're all filters, so they belong in the query string; hotelId identifies a resource, so it goes in the path.

Read in post: The hotel booking example
Edge caseMidCheck-then-act on inventory causes overbookingThe naive approach: read the number of free rooms, and if there are enough, write the booking and decrement the rooms. Two requests read at the same time, both see "1 room left", both write: overbooking.

The naive approach: read the number of free rooms, and if there are enough, write the booking and decrement the rooms.

// WRONG under concurrency: check-then-act
int available = inventoryRepo.available(roomTypeId, date);
if (available >= qty) {
    inventoryRepo.setBooked(roomTypeId, date, booked + qty);   // two threads both pass the if
}

Two requests read at the same time, both see "1 room left", both write: overbooking.

Read in post: The hotel booking example
Trade-offSeniorPreventing overbooking: conditional update, pessimistic lock, optimistic lock or RedisFor a pet project, and for plenty of real systems, the conditional update is the best choice.
Approach Idea Pros Cons
Conditional (atomic) update UPDATE ... SET booked = booked + q WHERE ... AND total - booked >= q, then check the affected row count One SQL statement, no read first, very fast The condition lives in SQL
Pessimistic locking SELECT ... FOR UPDATE, then update Easy to follow; complex checks can stay in Java Holds locks longer; deadlock risk if lock order differs
Optimistic locking A version column, update WHERE version = ?, retry on failure No locks held High contention (hot rooms, holidays) means endless retries
Holds in Redis Place a TTL "hold" first, write to the DB later Handles huge load Another system, and two sources of truth to keep in sync

For a pet project, and for plenty of real systems, the conditional update is the best choice.

Read in post: The hotel booking example
Edge caseMid@Transactional doesn't roll back on checked exceptionsBusiness exceptions are RuntimeExceptions, so @Transactional rolls back by default. With a checked exception, Spring does not roll back unless you set rollbackFor, a classic bug (see Exceptions in Java).

Business exceptions are RuntimeExceptions, so @Transactional rolls back by default. With a checked exception, Spring does not roll back unless you set rollbackFor, a classic bug (see Exceptions in Java).

Read in post: The hotel booking example
Edge caseSeniorTwo concurrent requests with the same Idempotency-Key both miss the existing bookingTwo concurrent requests with the same Idempotency-Key might both miss the existing booking. The (userid, idempotencykey) unique constraint makes the second one fail with DataIntegrityViolationException: catch it and return the booking that already exists.

Two concurrent requests with the same Idempotency-Key might both miss the existing booking. The (user_id, idempotency_key) unique constraint makes the second one fail with DataIntegrityViolationException: catch it and return the booking that already exists.

Read in post: The hotel booking example
Edge caseJuniorCompare BigDecimal with compareTo, not equalsMoney is BigDecimal with an explicit RoundingMode, compared with compareTo, not equals (2.0 and 2.00 are not equals).

Money is BigDecimal with an explicit RoundingMode, compared with compareTo, not equals (2.0 and 2.00 are not equals).

Read in post: The hotel booking example
Edge caseMidWalking a lazy @OneToMany across a list causes N+1 queriesN+1: one query for the list, then one more query per item. If Hotel maps a lazy @OneToMany List<RoomType and you walk each hotel in a list, Hibernate fires 1 + N queries. Details page: @EntityGraph(attributePaths = {"location", "roomTypes"}) or join fetch. List page: a DTO projection (like the native query above). More

N+1: one query for the list, then one more query per item. If Hotel maps a lazy @OneToMany List<RoomType> and you walk each hotel in a list, Hibernate fires 1 + N queries.

  • Details page: @EntityGraph(attributePaths = {"location", "roomTypes"}) or join fetch.
  • List page: a DTO projection (like the native query above).

More in ORM and JPA.

Read in post: The hotel booking example
Trade-offMidTesting with H2 or real MySQL via TestcontainersUse real MySQL through Testcontainers instead of H2. H2 differs from MySQL in syntax, CHECK enforcement and locking behaviour, so a test that passes on H2 proves nothing about production.

Use real MySQL through Testcontainers instead of H2. H2 differs from MySQL in syntax, CHECK enforcement and locking behaviour, so a test that passes on H2 proves nothing about production.

Read in post: The hotel booking example
InterviewJuniorWhy is the search API a GET with query parameters rather than a POST?

Because search only reads, so it's safe and idempotent, exactly what GET means; that makes it cacheable and shareable.

Filters go in the query string; resource identifiers (like hotelId) go in the path. POST only makes sense when the filter is too complex or too long for a URL.

Read in post: The hotel booking example
InterviewJuniorWhy does the create-booking API return 201 Created with a Location header instead of 200?

201 says a new resource was created, more specific than 200's plain "success"; Location gives the client its URL.

The Location header carries /api/v1/bookings/1001 so the client can follow it without building paths itself. The body usually includes the created representation, saving an extra GET. When a client resends the same Idempotency-Key, the server can replay the original response (201 with the same body) or answer 200, as long as it's consistent and documented.

Read in post: The hotel booking example
InterviewMidWhat is each layer (controller, service, repository) responsible for? Why not return entities from controllers?

The controller handles HTTP, the service handles use cases and transactions, the repository handles data access; returning entities turns your database structure into your API contract.

  • Controller: accepts and validates DTOs, calls the service, maps results and errors to status codes.
  • Service: use cases, business rules, transaction boundaries.
  • Returning entities: rename a column and clients break; lazy-loading errors outside the transaction, JSON cycles on bidirectional relationships, leaked sensitive fields. DTOs decouple the API contract from the data model.
Read in post: The hotel booking example
InterviewMidWhat is an idempotency key and how would you implement it for the booking API?

A unique key the client sends with each booking intent; when the server sees the key again, it returns the original result instead of creating a new booking.

The client generates a UUID and sends it in a header. The server stores the key with the booking under a unique constraint on (user_id, key), so clients can safely retry after a timeout. Two requests with the same key arriving concurrently: the unique constraint rejects the second one, so you catch that error and return the existing booking.

Read in post: The hotel booking example
InterviewMidWhy test against real MySQL (Testcontainers) instead of H2?

Because the most critical parts of this system (the conditional update, unique constraints, the search query) are exactly where H2 can behave differently from MySQL.

H2 differs from MySQL in syntax, date functions, CHECK enforcement, collations and locking/isolation behaviour. Testcontainers runs the same MySQL version as production, so the tests mean something.

Read in post: The hotel booking example
InterviewMidWhy might a @Transactional method fail to roll back on an exception?

Usually because the exception is checked, it's swallowed inside the method, or the call doesn't go through the proxy.

  • Checked exception: by default Spring only rolls back on RuntimeException and Error, so you need rollbackFor.
  • The exception is caught and swallowed inside the method.
  • The method is called internally via this and bypasses the proxy.
  • The method isn't public (with proxy-based transactions in older Spring versions).
  • The table engine doesn't support transactions.
Read in post: The hotel booking example
InterviewSeniorTwo people book the last room at the same time. How do you prevent overbooking?

Inventory per room type per night, one conditional UPDATE over the date range, affected rows must equal the number of nights, otherwise roll back and return 409.

  • The update: booked = booked + q WHERE ... AND total - booked >= q.
  • InnoDB locks each row on update and re-evaluates the condition against the latest version, so the second request fails.
  • Add a CHECK constraint booked <= total as a safety net.
  • Alternatives: SELECT FOR UPDATE, optimistic locking with a version column (poor under high contention), or Redis holds at very large scale.
  • And you need a concurrency test that proves it.
Read in post: The hotel booking example
InterviewSeniorThe service runs as 3 instances. How do you stop the expired-booking job from running twice?

Make the operation itself safe to run twice with a conditional status update, then add a distributed lock if you want.

  • Update WHERE status = 'PENDING' AND expires_at < now() and only release rooms for the rows whose status actually changed, in the same transaction.
  • Extra layer: a distributed lock such as ShedLock (a lock table in the database) so only one instance runs each cycle.
  • Or SELECT ... FOR UPDATE SKIP LOCKED (skip rows someone else has locked) so instances split the work in batches.
Read in post: The hotel booking example
InterviewSeniorSearch traffic grows 100x. How do you scale it?

Measure first, then scale in order of cost: indexes, read replicas, caching, a search engine; bookings still go to the primary database.

  • Measure: p95, EXPLAIN plans, cache hit ratio.
  • The right indexes (city, sleeps, the inventory primary key).
  • Read replicas for search: a few seconds of lag is fine because search results are only indicative, and the booking step re-checks availability for real.
  • Cache results per parameter set with a short TTL.
  • Move search to a search engine (Elasticsearch/OpenSearch) kept in sync via events or CDC.
Read in post: The hotel booking example
Edge caseMidA single available_rooms column can't answer "is there a room from date A to date B"(1) A single availablerooms column on RoomType can't answer "is there a room from date A to date B?". Availability differs night by night; with one number, a December booking eats January's rooms. The fix is a roominventory table where each row is one room type × one night, with total rooms, booked rooms and that night

(1) A single available_rooms column on RoomType can't answer "is there a room from date A to date B?". Availability differs night by night; with one number, a December booking eats January's rooms. The fix is a room_inventory table where each row is one room type × one night, with total rooms, booked rooms and that night's price (which also solves prices changing over time).

Read in post: Requirements analysis and data design through a hotel booking example
Trade-offMidPhotos and amenities: a text column, separate tables or a JSON column(3) Photos and amenities shouldn't be a single text column. A comma-separated list breaks 1NF (each cell holds one value) and can't be queried ("hotels with a pool"). Split them into hotelimage and an amenity table with a junction table. If you truly only ever read and write the whole list, a MySQL JSON column is an ac

(3) Photos and amenities shouldn't be a single text column. A comma-separated list breaks 1NF (each cell holds one value) and can't be queried ("hotels with a pool"). Split them into hotel_image and an amenity table with a junction table. If you truly only ever read and write the whole list, a MySQL JSON column is an acceptable compromise.

Read in post: Requirements analysis and data design through a hotel booking example
Edge caseJuniorMoney must be DECIMAL, never FLOAT/DOUBLE(5) Money is DECIMAL, never FLOAT/DOUBLE. And use an explicit coupontype plus discountvalue, instead of two columns ("rate" and "amount") where one is always empty.

(5) Money is DECIMAL, never FLOAT/DOUBLE. And use an explicit coupon_type plus discount_value, instead of two columns ("rate" and "amount") where one is always empty.

Read in post: Requirements analysis and data design through a hotel booking example
Edge caseMidMySQL only enforces CHECK constraints from 8.0.16The chknooverbooking constraint is the last safety net (MySQL only enforces CHECK from 8.0.16; older versions parse it and ignore it): even if the code has a bug, the database refuses negative or over-capacity values. Indexes, locking and normalisation are covered in the Database post.

The chk_no_overbooking constraint is the last safety net (MySQL only enforces CHECK from 8.0.16; older versions parse it and ignore it): even if the code has a bug, the database refuses negative or over-capacity values. Indexes, locking and normalisation are covered in the Database post.

Read in post: Requirements analysis and data design through a hotel booking example
Edge caseMidAn enrolment's DONE status must be derived consistently from per-lesson progressusercourse.status (START/PROCESSING/DONE) and usercourselesson.status are two sources for the same fact. If the service updates a lesson's progress but forgets the enrolment (or does it in a separate transaction), you get a DONE course with unfinished lessons, or the other way round. Update both in one transaction. Wri

user_course.status (START/PROCESSING/DONE) and user_course_lesson.status are two sources for the same fact. If the service updates a lesson's progress but forgets the enrolment (or does it in a separate transaction), you get a DONE course with unfinished lessons, or the other way round.

  • Update both in one transaction.
  • Write the transition rules down, including what happens when a teacher adds a lesson to a course someone has finished.
  • Run a periodic reconciliation query to catch drift.
Read in post: Requirements analysis and data design through a hotel booking example
TILMidA unique direct_key column prevents duplicate 1-to-1 chatsdirectkey = "smaller id:larger id" with a unique constraint guarantees two people only ever have one direct chat, even if both hit "message" at the same moment.

direct_key = "smaller id id" with a unique constraint guarantees two people only ever have one direct chat, even if both hit "message" at the same moment.

Read in post: Requirements analysis and data design through a hotel booking example
Trade-offSeniorRead state: last_read_message_id or a per-message read tablelastreadmessageid on the membership row replaces a per-message "read by" table. That's far cheaper: one row per person per room instead of one per person per message.

last_read_message_id on the membership row replaces a per-message "read by" table. That's far cheaper: one row per person per room instead of one per person per message.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewJuniorWhy should a booking store its price instead of joining to the room type's current price?

Because prices change over time, and a booking is a settled transaction.

The guest pays what was agreed at booking time, and invoices and reconciliation rely on that number. Joining to the current price would make old bookings "change price" whenever the hotel updates its rates.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewJuniorHow do you represent the many-to-many relationship between Booking and Coupon in a relational database?

With a junction table booking_coupon(booking_id, coupon_id) whose composite primary key is made of two foreign keys.

The junction table can also hold data about the relationship itself, such as the discount applied to that booking.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewJuniorWhy do money columns use DECIMAL instead of FLOAT/DOUBLE?

Because FLOAT/DOUBLE are binary floating-point numbers that can't represent many decimal fractions exactly (0.1 + 0.2 isn't 0.3).

Errors accumulate across calculations and break reconciliation. DECIMAL(p, s) stores exact decimals with a fixed number of digits. In Java, use BigDecimal with an explicit RoundingMode, or store integers in the smallest unit (cents, dong).

Read in post: Requirements analysis and data design through a hotel booking example
InterviewMidWhy store inventory per room type per night instead of an available_rooms column?

Because availability differs from night to night; a single number can't answer "is a room free from date A to date B?".

  • Without it, a booking this month would eat into another month's rooms.
  • A room_inventory(room_type_id, stay_date) table lets you check and decrement each night with one conditional update, add CHECK (booked_rooms <= total_rooms) as a safety net, and keep the nightly price there too.
  • The costs: you have to pre-generate rows for future dates (a job that creates inventory a few months ahead), and the table is bigger: 10,000 hotels × a few room types × 365 nights is in the tens of millions of rows, which a composite primary key handles fine.
Read in post: Requirements analysis and data design through a hotel booking example
InterviewMid"The system must be fast": how do you turn a non-functional requirement like that into something verifiable?

Attach a number, a load condition and a way to measure it, for example "search API p95 < 300 ms at 50 req/s with 10,000 hotels, measured with k6 on seeded data".

Use percentiles rather than averages, because averages hide the slow tail that real users hit. Do the same for availability (99.9% per month), correctness (no overbooking, checked by a concurrency test and a constraint), security and operations. An NFR with no way to measure it can't be reviewed or signed off.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewMidWhat would you ask before designing the E-Learning pet project?

The things that change the schema or the flows; where nobody can answer, pick an assumption, write it down and turn it into BDD.

  • One teacher per course or several; whether one person can both learn and teach.
  • What "lesson completed" means for a video or a PDF; when an enrolment moves START → PROCESSING → DONE.
  • Who can rate and whether ratings can be edited; how the progress percentage changes when lessons are added or hidden.

An assumption written as a BDD scenario means a later change breaks a test straight away.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewSeniorHow do you turn a vague requirement like "users can book a room" into a spec?

Actors and goals → open questions → in/out of scope → Given/When/Then acceptance criteria → measurable NFRs.

  • Open questions: payment, how long rooms are held, cancellation, multiple rooms, time zones, concurrent bookings.
  • Given/When/Then covers the happy path, edge cases and errors.
  • NFRs: p95 latency, load, zero overbooking, availability.
  • Anything that can't be answered right away becomes a documented assumption with an owner to confirm it.

The result is something reviewable that maps directly to tests.

Read in post: Requirements analysis and data design through a hotel booking example
InterviewSeniorDesign the database for a chat app with both one-to-one and group chats. What changes at billions of messages?

Treat a one-to-one chat as a conversation with exactly two members, so three tables are enough: conversation, conversation_member, message; at very large scale, split by conversation_id.

  • Prevent duplicate one-to-one chats with a unique direct_key ("smaller id id").
  • Store read state as last_read_message_id on the member row instead of a per-message read table.
  • Load messages with keyset pagination on an (conversation_id, id) index.
  • At scale: partition or shard by conversation_id, since every access goes through one conversation; or move message to a wide-column store like Cassandra with conversation_id plus a time bucket as the partition key so partitions don't grow forever, and Snowflake-style message ids so messages still sort by time without a global auto-increment.
Read in post: Requirements analysis and data design through a hotel booking example
TILMidSince Java 11 there is no separate JRE; use jlink for a minimal runtimeSince Java 11, Oracle no longer ships a separate JRE. The modern approach: use jlink to build a minimal runtime with only the modules your app needs, or use a distribution's JDK/JRE images (Temurin, Corretto) in Docker.

Since Java 11, Oracle no longer ships a separate JRE. The modern approach: use jlink to build a minimal runtime with only the modules your app needs, or use a distribution's JDK/JRE images (Temurin, Corretto) in Docker.

Read in post: Backend interview review
Edge caseJuniorequals() defaults to ==, and overriding equals means overriding hashCodeThe slides say "equals() compares values", which is incomplete: Object.equals() is == by default. It only compares contents in classes that override it, such as String, Integer, LocalDate and records. Whenever you override equals, you must override hashCode consistently, or HashMap/HashSet will misbehave.

The slides say "equals() compares values", which is incomplete: Object.equals() is == by default. It only compares contents in classes that override it, such as String, Integer, LocalDate and records.

Whenever you override equals, you must override hashCode consistently, or HashMap/HashSet will misbehave.

Read in post: Backend interview review
TILSeniorThe Java Memory Model guarantees final field visibility after the constructorThe Java Memory Model is the set of rules for when one thread sees another thread's data. It guarantees that once the constructor finishes, other threads see the correct values of final fields without synchronisation. This is the foundation of immutable objects.

The Java Memory Model is the set of rules for when one thread sees another thread's data. It guarantees that once the constructor finishes, other threads see the correct values of final fields without synchronisation. This is the foundation of immutable objects.

Read in post: Backend interview review
Edge caseJuniorAn overriding method doesn't need the same return type (covariant return type)A correction to the slides: an overriding method's return type doesn't have to be identical. It may be a subtype (covariant return type). Other rules: you can't reduce visibility (public → protected is an error), and you can't throw broader checked exceptions. Always use @Override so the compiler catches typos.

A correction to the slides: an overriding method's return type doesn't have to be identical. It may be a subtype (covariant return type).

Other rules: you can't reduce visibility (public → protected is an error), and you can't throw broader checked exceptions. Always use @Override so the compiler catches typos.

Read in post: Backend interview review
Trade-offMidAbstract class or interfaceDefault to an interface for contracts: easy to mock, and a class can play several roles. Abstract class when subclasses genuinely share state and a common algorithm skeleton (template method). Example: an AbstractPaymentProcessor that already does validate → charge → log, where subclasses only implement charge. Java 17
  • Default to an interface for contracts: easy to mock, and a class can play several roles.
  • Abstract class when subclasses genuinely share state and a common algorithm skeleton (template method). Example: an AbstractPaymentProcessor that already does validate → charge → log, where subclasses only implement charge.
  • Java 17+: a sealed interface plus records is a neat way to model a closed set of types.
Read in post: Backend interview review
Trade-offMidArrayList, LinkedList, ArrayDeque or a plain arrayArrayList beats LinkedList almost every time thanks to cache locality (data sits together, so the CPU reads it fast). For adding/removing at both ends, use ArrayDeque. Plain arrays when the size is fixed and you need maximum performance, or for primitives to avoid boxing (wrapping int in Integer).
  • ArrayList beats LinkedList almost every time thanks to cache locality (data sits together, so the CPU reads it fast).
  • For adding/removing at both ends, use ArrayDeque.
  • Plain arrays when the size is fixed and you need maximum performance, or for primitives to avoid boxing (wrapping int in Integer).
Read in post: Backend interview review
InterviewJuniorWhen you override equals(), what else must you do, and why?

Override hashCode() so that objects that are equals have the same hash code.

HashMap/HashSet find the bucket by hashCode first and only then compare with equals. If two equal objects have different hashes, the map treats them as different keys. Records and Lombok's @EqualsAndHashCode generate both for you.

Read in post: Backend interview review
InterviewJuniorWhen do you use @PathVariable vs @RequestParam?

PathVariable for the part of the path that identifies a resource (/users/1); RequestParam for the query string.

The query string is usually for filtering, sorting and pagination, optionally with defaults (?page=2&size=20).

Read in post: Backend interview review
InterviewJuniorIs Java pass-by-value or pass-by-reference?

Always pass-by-value. For objects, the value being copied is the reference.

So a method can modify the object's contents, but reassigning the parameter to a new object isn't visible to the caller.

Read in post: Backend interview review
InterviewMidWhy prefer constructor injection?

Because dependencies can be final and the object is never missing a dependency.

Required dependencies are visible in the signature, you can test with new without a container, and dependency cycles are detected at startup. A very long constructor is a sign the class breaks single responsibility.

Read in post: Backend interview review
InterviewMidAbstract class or interface after Java 8: how do you choose?

Default to an interface; pick an abstract class when you need shared state, constructors or a common algorithm skeleton.

Interfaces are contracts and capabilities: a class can implement many, and default methods let an API evolve without breaking existing implementations. Abstract classes suit a family of closely related classes sharing a template method. Java 17 adds sealed interfaces to restrict the set of implementations.

Read in post: Backend interview review
InterviewMidArrayList or LinkedList?

Almost always ArrayList.

ArrayList has O(1) access, contiguous memory that's friendly to the CPU cache, and amortised O(1) appends. LinkedList only has a theoretical edge when inserting or removing in the middle while already holding an iterator at that spot, but it uses much more memory and iterates slowly. For a double-ended queue, use ArrayDeque.

Read in post: Backend interview review
InterviewMidWhat does HTTPS protect, and what doesn't it protect?

It protects data in transit (confidentiality, integrity) and authenticates the server through its certificate; it protects nothing outside the wire.

It doesn't protect data once it reaches the server (storage, logs), bugs in the application itself (SQL injection, broken authorisation), or metadata such as IP addresses and the domain name (SNI is still visible unless ECH is used).

Read in post: Backend interview review
Trade-offJuniorListing technologies vs describing problems you solvedListing technologies ("Spring Boot, JPA, MySQL, Docker, Redis"): easy to write and gets you past HR keyword filters, but doesn't set you apart from someone who followed a tutorial. Describing the problem and the fix ("prevented overbooking with a conditional update inside a transaction"): harder to write, but shows you
  • Listing technologies ("Spring Boot, JPA, MySQL, Docker, Redis"): easy to write and gets you past HR keyword filters, but doesn't set you apart from someone who followed a tutorial.
  • Describing the problem and the fix ("prevented overbooking with a conditional update inside a transaction"): harder to write, but shows you understand why, and steers the interview toward your strongest ground.
  • A sensible mix: one short tech-stack line for the filters, and the rest spent on problems, solutions and measured results.
Read in post: Backend interview review
Edge caseJuniorA number on your CV that you can't explain backfires"Fast API" or "optimized performance" says nothing. But writing "< 200 ms" and not knowing whether it's the average or p95, how many requests it was measured with, or on how much data, is worse: the interviewer starts doubting everything else. Only put numbers you measured yourself and can describe the conditions for.

"Fast API" or "optimized performance" says nothing. But writing "< 200 ms" and not knowing whether it's the average or p95, how many requests it was measured with, or on how much data, is worse: the interviewer starts doubting everything else.

  • Only put numbers you measured yourself and can describe the conditions for.
  • If you list "Kafka" or "Redis", be ready to say why you needed it and what happens when it fails.
  • Don't say "we did" throughout; make clear which part you did.
Read in post: Backend interview review
InterviewJuniorTell me about a project you worked on.

Follow the six-point template in about a minute, then let the interviewer pick where to dig.

The six points: project name; role (Backend Developer); team size and which part you owned; what the system does and for whom; the hardest problem and how you solved it; the result with a number.

For example: "Hotel Booking System. I was the backend developer in a team of four. Guests book rooms and staff manage them. The hardest part was two people booking the same room at the same moment; I used a transaction with a conditional update so only one booking succeeds. The booking API's p95 is under 200 ms at 100 concurrent users."

Read in post: Backend interview review
InterviewMidYour CV says "API p95 < 200 ms". How did you measure that?

Give the full measurement setup: tool, scenario, data, environment, and make clear the metric is a percentile, not an average.

  • Tool: k6, JMeter, Gatling.
  • Scenario: how many concurrent users, for how long, read/write mix.
  • Data: how many rows in the tables. Environment: local machine or staging, and its specs.
  • Metric: p95/p99, because averages hide slow requests.

Add the bottleneck you found and what you changed (say, an index or a bigger connection pool). If you only measured on your laptop, say so; being honest about the limits of a measurement earns more credit than a pretty number.

Read in post: Backend interview review
Trade-offMidsynchronized vs AtomicInteger vs LongAdder for shared statesynchronized (or ReentrantLock): protects several variables at once and whole check-then-act sequences. Simple and readable. The cost: threads wait for each other under heavy contention, and holding a lock across an I/O call slows everything down with it. AtomicInteger/AtomicLong/AtomicReference: lock-free thanks to CA
  • synchronized (or ReentrantLock): protects several variables at once and whole check-then-act sequences. Simple and readable. The cost: threads wait for each other under heavy contention, and holding a lock across an I/O call slows everything down with it.
  • AtomicInteger/AtomicLong/AtomicReference: lock-free thanks to CAS, very fast for one variable. Check-then-act has to be written as a CAS loop (compareAndSet, updateAndGet). You can't combine two atomics into one atomic operation.
  • LongAdder: fastest when lots of threads add, at the cost of more memory and a non-atomic total. Great for metrics, wrong for "if there's stock left, take one".

Order of preference: don't share state (per-thread data or immutable objects) > one variable, use an atomic > several variables or complex logic, use a lock > state that must be correct across app instances, use a lock or constraint in the database, because a JVM lock means nothing across two pods.

Read in post: Java concurrency
Edge caseMidsynchronized and ReentrantLock don't exclude each othersynchronized (account) uses the object's hidden monitor; account.lock.lock() uses a separate ReentrantLock object. The two know nothing about each other, so if two transfer paths use different styles, two threads still modify balance at the same time. While writing the demo, mixing the two styles over 100,000 transfers

synchronized (account) uses the object's hidden monitor; account.lock.lock() uses a separate ReentrantLock object. The two know nothing about each other, so if two transfer paths use different styles, two threads still modify balance at the same time. While writing the demo, mixing the two styles over 100,000 transfers between 5 accounts turned a total of 5,000 into 6,051.

A piece of state must be guarded by exactly one lock, and every read and write (reads included) has to go through it. Document which lock guards which field.

Read in post: Java concurrency
Edge caseMidvolatile guarantees visibility, not atomicityvolatile does two things: every write becomes visible to other threads right away, and the compiler/CPU can't reorder instructions across that read or write. It does not make count++ atomic: a volatile int count still loses increments, because read-add-write is still three steps that can interleave. Use volatile for si

volatile does two things: every write becomes visible to other threads right away, and the compiler/CPU can't reorder instructions across that read or write. It does not make count++ atomic: a volatile int count still loses increments, because read-add-write is still three steps that can interleave.

Use volatile for single-writer status flags (running, shutdownRequested) or to publish a reference to an immutable object. For counters or check-then-act, use AtomicXxx or a lock. Double-checked locking for a singleton also requires volatile on the instance field; otherwise another thread can see a half-constructed object.

Read in post: Java concurrency
Trade-offMidFixed lock ordering vs tryLock with a timeout to avoid deadlocksLock ordering: every place that needs several locks takes them in the same order (by id, by table name...). Simple, no runtime cost, works with synchronized. Hard when locks have no natural order, or when a library you don't control takes locks. tryLock(timeout) (ReentrantLock): tolerates any acquisition order and can
  • Lock ordering: every place that needs several locks takes them in the same order (by id, by table name...). Simple, no runtime cost, works with synchronized. Hard when locks have no natural order, or when a library you don't control takes locks.
  • tryLock(timeout) (ReentrantLock): tolerates any acquisition order and can report an error instead of hanging forever. The cost is longer code, unlock in finally, and a risk of livelock (both threads keep backing off and retrying in lockstep), so you need a random backoff.

Better still: design so you don't need several locks at once (keep related state in one place, hold locks briefly, never do I/O or call unknown callbacks while holding a lock).

Read in post: Java concurrency
InterviewJuniorHow does synchronized work?

Every object has a monitor; only one thread at a time can be inside a synchronized block on the same monitor.

Any other thread trying to enter is BLOCKED. An instance method locks on this, a static synchronized method on the Class object. The lock is reentrant and is released even when the block exits with an exception. Besides mutual exclusion, an unlock happens-before the next lock of the same monitor, so whatever was written inside the block is visible to the next thread.

Read in post: Java concurrency
InterviewMidWhat is a race condition, and how do you fix count++ on a shared variable?

A race condition is when the result depends on how threads interleave; fix count++ with AtomicInteger, LongAdder or a lock, not volatile.

count++ is read-add-write, so two threads that read the same value lose an increment. AtomicInteger.incrementAndGet() uses CAS; LongAdder suits many writers (e.g. metrics); synchronized/a lock when you must protect several variables or a whole check-then-act sequence.

Read in post: Java concurrency
InterviewMidWhat does volatile guarantee, and what doesn't it?

It guarantees visibility and ordering, not atomicity.

Once written, other threads read the new value; there's no reordering across the volatile access; a volatile write happens-before later reads. Multi-step operations like count++ are still not atomic. Use it for stop flags, publishing references to immutable objects, and double-checked locking.

Read in post: Java concurrency
InterviewMidWhy does if (left.get() > 0) left.decrementAndGet() still oversell, even with an AtomicInteger?

Because each call is atomic, but the check-then-act pair isn't.

Several threads see left == 1, all pass the if, then all decrement, and stock goes negative. Fix it with a CAS loop (compareAndSet(current, current - 1) only succeeds if nobody changed the value in between), with a conditional updateAndGet, or by putting both the check and the decrement inside one synchronized block.

Read in post: Java concurrency
InterviewSeniorWhat is a deadlock, and how do you detect and prevent it?

Threads hold locks and wait for each other's locks in a cycle; detect it with a thread dump, prevent it with a global lock order or tryLock with a timeout.

  • It needs all four Coffman conditions: mutual exclusion, hold and wait, no preemption, circular wait.
  • Detect: jstack/jcmd Thread.print (prints "Found one Java-level deadlock"), ThreadMXBean.findDeadlockedThreads(), or the symptom of low CPU with hanging requests.
  • Prevent: a global lock order, tryLock with a timeout plus backoff, short critical sections with no I/O or foreign callbacks inside, and avoiding the need for several locks at once.
Read in post: Java concurrency
InterviewSeniorWhat is happens-before? Name a few important happens-before relationships.

The Java Memory Model's rule: if A happens-before B, everything A wrote is visible to B and the two can't be reordered past each other.

Without it, another thread may see stale values or even a half-constructed object. The main ones: program order within a thread; unlocking a monitor → a later lock of the same monitor; a volatile write → a later read; Thread.start() → code in that thread; code in a thread → join() returning; submitting a task to an executor → the task running; a task completing → Future.get() returning; and transitivity.

Read in post: Java concurrency
InterviewSeniorThe app runs 3 instances. Does synchronized prevent overselling stock?

No. A JVM lock only works within one process; three pods means three unrelated monitors.

An invariant shared across instances has to be enforced where the state is shared: UPDATE ... SET stock = stock - 1 WHERE id = ? AND stock > 0 and then check the affected row count, a row lock (SELECT ... FOR UPDATE), optimistic locking with a version column, or an atomic DECR in Redis. A JVM lock can still reduce contention inside one instance, but it isn't the final guarantee.

Read in post: Java concurrency
TILJuniorThe URL fragment is never sent to the serverThe fragment (the part after ) points to a part of the resource. It is never sent to the server; the browser handles it.

The fragment (the part after #) points to a part of the resource. It is never sent to the server; the browser handles it.

Read in post: REST APIs
Edge caseMidA long id above 2^53 gets rounded in JavaScriptJavaScript numbers are 64-bit doubles, so a long id above 2^53 gets rounded in the frontend. Serialize Snowflake-style ids as strings. For money, use BigDecimal or an integer amount in the smallest unit (cents), never double.

JavaScript numbers are 64-bit doubles, so a long id above 2^53 gets rounded in the frontend. Serialize Snowflake-style ids as strings. For money, use BigDecimal or an integer amount in the smallest unit (cents), never double.

Read in post: REST APIs
Trade-offMidSoft delete with DELETE or PATCH a statusUsing DELETE /users/34 to disable a user (a soft delete) is fine if, from the client's point of view, the resource disappears (a later GET returns 404). If disabled users must still be readable, PATCH /users/34 with {"status": "DISABLED"} is more honest.

Using DELETE /users/34 to disable a user (a soft delete) is fine if, from the client's point of view, the resource disappears (a later GET returns 404). If disabled users must still be readable, PATCH /users/34 with {"status": "DISABLED"} is more honest.

Read in post: REST APIs
Edge caseMidA + in a query string decodes to a spaceA bug in one of the slide examples: ?sort=+price,-name. In a query string + decodes to a space (form-encoding rules), so the server receives " price". A literal + has to be encoded as %2B. Safer: sort=price,-name, sort=price:asc,name:desc (the slides' other example), or the Spring Data style sort=price,asc&sort=name,de

A bug in one of the slide examples: ?sort=+price,-name. In a query string + decodes to a space (form-encoding rules), so the server receives " price". A literal + has to be encoded as %2B. Safer: sort=price,-name, sort=price:asc,name:desc (the slides' other example), or the Spring Data style sort=price,asc&sort=name,desc.

A second bug: /users?sort=+price,-name?offset=0&limit=10 contains two ?. Only the first starts the query string; later parameters are joined with & (?sort=price,-name&offset=0&limit=10). Otherwise the server gets sort = " price,-name?offset=0" and no offset at all.

Read in post: REST APIs
Trade-offSeniorOffset vs cursor (keyset) paginationThe slides show page/size and offset/limit; both are offset pagination and translate to LIMIT 10 OFFSET 1000 in SQL. The problems: The database still reads and throws away the first 1000 rows, so deep pages get slower and slower. Rows inserted or deleted between two calls cause items to be duplicated or skipped. Cursor

The slides show page/size and offset/limit; both are offset pagination and translate to LIMIT 10 OFFSET 1000 in SQL. The problems:

  • The database still reads and throws away the first 1000 rows, so deep pages get slower and slower.
  • Rows inserted or deleted between two calls cause items to be duplicated or skipped.

Cursor (keyset) pagination remembers where the previous page ended:

-- Next page after the last item with (created_at, id) = ('2026-11-01 10:00', 981)
SELECT id, title, created_at
FROM courses
WHERE (created_at, id) < ('2026-11-01 10:00', 981)
ORDER BY created_at DESC, id DESC
LIMIT 20;

With an index on (created_at, id) every page is equally fast; the price is that you can't jump straight to "page 37". The response returns a next_cursor (often base64 of the last values) for the client to send back.

Offset Cursor/keyset
Jump to any page Yes No
Deep-page performance Degrades Stable
Stable while data changes Duplicates/skips Stable
Good fit Small admin tables Feeds, infinite scroll, public APIs

Always cap size (say, 100) so a client can't pull the whole table.

Read in post: REST APIs
Trade-offSeniorAPI versioning: URI, header, media type or queryURI versioning is the most common choice and the one the course uses. The compatibility policy matters more: Adding fields or endpoints: compatible (clients must ignore unknown fields). Renaming, removing, retyping or changing meaning: a breaking change, needs a new version. Retiring an old version: announce it with th
Approach Example Pros Cons
URI /api/v1/users Obvious, easy to route and cache "Not pure REST": one resource, two URIs
Custom header X-API-Version: 2 Clean URLs Hard to test in a browser, easy to forget
Media type Accept: application/vnd.example.v2+json Closest to the spirit of HTTP Complex, rarely used
Query ?version=2 Simple Easily confused with filters

URI versioning is the most common choice and the one the course uses. The compatibility policy matters more:

  • Adding fields or endpoints: compatible (clients must ignore unknown fields).
  • Renaming, removing, retyping or changing meaning: a breaking change, needs a new version.
  • Retiring an old version: announce it with the Deprecation and Sunset headers.
Read in post: REST APIs
TILMidSpring Framework 7 has built-in API versioningSpring Framework 7 / Spring Boot 4 add first-class versioning (@GetMapping(version = "1.1") plus a path/header/media-type strategy). Before that you rolled your own with path prefixes.

Spring Framework 7 / Spring Boot 4 add first-class versioning (@GetMapping(version = "1.1") plus a path/header/media-type strategy). Before that you rolled your own with path prefixes.

Read in post: REST APIs
Edge caseSeniorShallowEtagHeaderFilter doesn't save CPU or database workSpring's ShallowEtagHeaderFilter derives the ETag from a hash of the body. It saves bandwidth but not CPU or database work, because the server still builds the whole response before hashing it.

Spring's ShallowEtagHeaderFilter derives the ETag from a hash of the body. It saves bandwidth but not CPU or database work, because the server still builds the whole response before hashing it.

Read in post: REST APIs
Trade-offSeniorWhen to pick REST, gRPC, GraphQL or SOAPREST for public APIs and frontends, gRPC for performance-sensitive internal services, GraphQL when many client types need different shapes of data (often as a Backend-for-Frontend), SOAP when you have to integrate with something that already speaks it.

REST for public APIs and frontends, gRPC for performance-sensitive internal services, GraphQL when many client types need different shapes of data (often as a Backend-for-Frontend), SOAP when you have to integrate with something that already speaks it.

Read in post: REST APIs
Trade-offMidPackage-by-layer vs package-by-featureThe above is package-by-layer. As a project grows, many teams move to package-by-feature: course/, enrollment/, payment/, each with its own controller, service and repository. Related code stays together, and package-private hides internals. Enforce layer rules (a controller must not call a repository directly) with Ar

The above is package-by-layer. As a project grows, many teams move to package-by-feature: course/, enrollment/, payment/, each with its own controller, service and repository. Related code stays together, and package-private hides internals. Enforce layer rules (a controller must not call a repository directly) with ArchUnit or Spring Modulith instead of relying on code review.

Read in post: REST APIs
Edge caseMidJackson's naming strategy doesn't apply to query parametersWith spring.jackson.property-naming-strategy=SNAKECASE, the teacherId field appears as teacherid in JSON. But query parameters don't go through Jackson, so teacherid in the URL won't map to teacherId in CourseSearchParams: use camelCase query names or declare @RequestParam("teacherid"). For PATCH, accept a Map or JsonN

With spring.jackson.property-naming-strategy=SNAKE_CASE, the teacherId field appears as teacher_id in JSON. But query parameters don't go through Jackson, so teacher_id in the URL won't map to teacherId in CourseSearchParams: use camelCase query names or declare @RequestParam("teacher_id"). For PATCH, accept a Map or JsonNode so you can tell "field not sent" from "field sent as null", which a record can't express.

Read in post: REST APIs
TILJunior.gitkeep is a convention, not a Git featureGit tracks files, not directories, so empty folders never get committed. .gitkeep is just an empty file, by convention, that keeps the folder alive.

Git tracks files, not directories, so empty folders never get committed. .gitkeep is just an empty file, by convention, that keeps the folder alive.

Read in post: REST APIs
InterviewJuniorWhy shouldn't you return entities directly from an API?

Because an entity is the persistence model, not the API contract: exposing it leaks data and ties clients to the database schema.

Concretely: you leak sensitive fields, you hit lazy-loading errors or infinite recursion when Jackson serializes bidirectional relationships, and every schema change becomes a breaking API change. DTOs decouple the API contract from the persistence model.

Read in post: REST APIs
InterviewJuniorHow is Spring Boot different from the Spring Framework?

Spring Boot doesn't replace Spring; it runs Spring underneath with sensible defaults.

It adds auto-configuration (beans created based on what's on the classpath, only if you haven't declared your own), starters plus a BOM that pins compatible versions, an embedded server so java -jar is enough, and Actuator for health checks and metrics. You can still override every default; run with --debug to see which auto-configurations were applied and why.

Read in post: REST APIs
InterviewMidWhat does "stateless" mean in REST? Is an app with a database still stateless?

Yes. Stateless refers to conversation state: the server keeps no client session between requests; business state still lives in the database.

Each request carries everything needed (a JWT, for example). The payoff is easy horizontal scaling: any instance can handle any request, no sticky sessions required.

Read in post: REST APIs
InterviewMidWhat's wrong with offset pagination, and what's the alternative?

Deep pages are slow and changing data causes duplicates or gaps; the alternative is keyset (cursor) pagination.

OFFSET n forces the database to read and discard n rows. Keyset filters on the last values of the previous page (WHERE (created_at, id) < (?, ?)) with a matching index. Performance is stable, but you can't jump to an arbitrary page.

Read in post: REST APIs
InterviewMidHow do no-cache and no-store differ? What is an ETag for?

no-cache allows storing but requires revalidation before use; no-store forbids storing. An ETag is a version tag for a representation.

With If-None-Match the server can answer 304 when nothing changed, and with If-Match the ETag provides optimistic concurrency control (412 if someone else changed it first).

Read in post: REST APIs
InterviewSeniorHow would you version an API and manage breaking changes?

URI versioning (/v1) by default, but what really matters is the compatibility policy and how you retire old versions.

  • URI versioning is obvious and easy to route and cache.
  • Additive changes (new fields or endpoints) don't bump the version, and clients must ignore unknown fields. Renaming, removing, retyping or changing meaning is breaking and needs a new version.
  • Run both versions side by side for a while, announce retirement with Deprecation/Sunset, and watch traffic on the old version before switching it off.
  • Contract tests in CI (OpenAPI diff, consumer-driven contracts) catch breaking changes early.
Read in post: REST APIs
InterviewSeniorWhen would you choose gRPC or GraphQL over REST?

gRPC for internal calls that need low latency and strict contracts; GraphQL when many client types need different data. REST stays the default for public APIs.

  • gRPC: small payloads, streaming; the cost is harder debugging and no direct browser calls.
  • GraphQL: fewer round trips; the cost is weak HTTP caching, fighting N+1 in resolvers (DataLoader) and limiting query depth and complexity.
  • REST: simple, cache-friendly, great tooling.
Read in post: REST APIs
InterviewSeniorHow would you design the error format for a system of many services?

Pick one standard such as RFC 9457 Problem Details and ship it as a shared library or enforce it at the API gateway so every service is consistent.

  • Fields: type (a stable URI identifying the error kind that clients can switch on), title, status, detail, instance, plus extensions like errors for validation and a trace_id to find the logs.
  • Status codes must carry the right semantics so retries and monitoring work.
  • Never expose stack traces, SQL or internal class names.
Read in post: REST APIs
InterviewSeniorA heavily used GET endpoint is slow. How do you approach it?

Measure first (APM, slow query log), then work from the query up to caching, and make every cache layer answer "how stale is acceptable?".

  • Fix queries and indexes, remove N+1.
  • HTTP caching (Cache-Control, ETag/304, a CDN for public data).
  • An application cache (Caffeine, Redis) with a clear invalidation strategy.
  • Smaller payloads (pagination, field selection, gzip/br); HTTP/2 and keep-alive.
  • Protect the system with rate limits and timeouts.
Read in post: REST APIs
Trade-offJuniorextends Thread vs Runnable vs Callableextends Thread: mixes the work with how it runs. You lose your one superclass, it doesn't fit a thread pool, and every run needs a new thread. Almost never used. Runnable: describes only the work, no result, no checked exceptions. Runs on new Thread(r), executor.execute(r) or a virtual thread. Good for fire-and-forget
  • extends Thread: mixes the work with how it runs. You lose your one superclass, it doesn't fit a thread pool, and every run needs a new thread. Almost never used.
  • Runnable: describes only the work, no result, no checked exceptions. Runs on new Thread(r), executor.execute(r) or a virtual thread. Good for fire-and-forget work.
  • Callable<V>: like Runnable, but returns a result and may throw checked exceptions; submit it with ExecutorService.submit to get a Future<V>.

Rule of thumb: write tasks as Runnable/Callable and let an ExecutorService (or the framework) pick the thread. Production code rarely calls new Thread() directly.

Read in post: Threads in Java
Edge caseJuniorCalling run() instead of start() doesn't create a new threadthread.run() is a plain method call: the code runs on the current thread, sequentially. Only thread.start() asks the JVM to create a new OS thread and call run() on it. The mistake is silent: the result is still correct, just slower and not concurrent; the giveaway is that Thread.currentThread().getName() inside the ta

thread.run() is a plain method call: the code runs on the current thread, sequentially. Only thread.start() asks the JVM to create a new OS thread and call run() on it. The mistake is silent: the result is still correct, just slower and not concurrent; the giveaway is that Thread.currentThread().getName() inside the task prints main or the caller's thread name.

A Thread object can be start()ed only once; a second call throws IllegalThreadStateException, even after the thread has finished. To run again, create a new thread, or better, submit the task to an executor.

Read in post: Threads in Java
Edge caseJuniorgetState() right after start() is not guaranteed to be RUNNABLEMany examples call t.start(), print t.getState() and label it "RUNNABLE". That isn't guaranteed: when main reads it, the new thread may not be scheduled yet (RUNNABLE), may have reached sleep() (TIMEDWAITING) or may have finished (TERMINATED). Ordering between two unsynchronized threads is undefined. Likewise, Thread.s

Many examples call t.start(), print t.getState() and label it "RUNNABLE". That isn't guaranteed: when main reads it, the new thread may not be scheduled yet (RUNNABLE), may have reached sleep() (TIMED_WAITING) or may have finished (TERMINATED). Ordering between two unsynchronized threads is undefined.

Likewise, Thread.sleep(100) "to make sure the other thread reached point X" is fine in a demo only. In tests and real code, synchronize with tools that have clear semantics: CountDownLatch, join(), Future.get().

Read in post: Threads in Java
Edge caseMidCatching InterruptedException and just calling printStackTrace() swallows the stop requestWhen sleep/wait/poll throws InterruptedException, the JVM has already cleared the interrupt flag. If the catch only logs and carries on, the "please stop" signal is gone: a while (!isInterrupted()) loop keeps going, shutdownNow() can't stop the task, and the app shuts down slowly or hangs. There are only two correct wa

When sleep/wait/poll throws InterruptedException, the JVM has already cleared the interrupt flag. If the catch only logs and carries on, the "please stop" signal is gone: a while (!isInterrupted()) loop keeps going, shutdownNow() can't stop the task, and the app shuts down slowly or hangs.

There are only two correct ways:

  1. Declare throws InterruptedException and let the caller decide.
  2. If you can't rethrow (for example inside Runnable.run()): call Thread.currentThread().interrupt() to restore the flag, then get out of what you're doing.

Never wrap it in a RuntimeException without restoring the flag.

Read in post: Threads in Java
InterviewJuniorWhat's the difference between a process and a thread?

A process is a running program with its own memory; a thread is a path of execution inside a process that shares the heap but has its own stack.

The thread is the unit the OS schedules. Threads are cheaper and communicate faster (by sharing objects), but because they share memory they need careful synchronization.

Read in post: Threads in Java
InterviewJuniorWhat's the difference between start() and run()?

start() asks the JVM to create a new thread and call run() on it; calling run() directly is just a method call on the current thread.

Calling run() gives no concurrency. start() can only be called once per Thread object; a second call throws IllegalThreadStateException.

Read in post: Threads in Java
InterviewJuniorHow do Runnable and Callable differ, and why prefer them over extends Thread?

Callable returns a result and may throw checked exceptions, Runnable can't; both separate the work from the thread that runs it.

A Callable<V> is submitted via ExecutorService.submit to get a Future<V>. Being separate from the thread, both work with thread pools and virtual threads and don't use up your single superclass, unlike extends Thread.

Read in post: Threads in Java
InterviewJuniorWhat states can a Java thread be in?

Six: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; there's no separate RUNNING state.

NEW is not started; RUNNABLE is running or waiting for a CPU, including blocked on I/O; BLOCKED is waiting to enter synchronized; WAITING is wait, join, park with no timeout; TIMED_WAITING is sleep and the timed variants; TERMINATED is finished.

Read in post: Threads in Java
InterviewMidHow does sleep() differ from wait()?

sleep keeps its locks and can be called anywhere; wait must hold the monitor and releases it while waiting.

Thread.sleep is static and pauses the current thread. obj.wait() without holding obj's monitor throws IllegalMonitorStateException; it waits for notify/notifyAll or a timeout, and must sit in a while (!condition) loop because of spurious wakeups. New code should use BlockingQueue, CountDownLatch or Condition.

Read in post: Threads in Java
InterviewMidHow should you handle InterruptedException?

Either rethrow it, or call Thread.currentThread().interrupt() to restore the flag and stop what you're doing.

The blocking method cleared the flag when it threw. Swallowing it with an empty catch or just a log line means shutdownNow() and Future.cancel(true) can't stop the task.

Read in post: Threads in Java
TILJuniorJava does roughly 10⁸ simple operations per secondAt n = 10⁶, O(n²) is 10¹² operations, about three hours; O(n log n) is around 0.2 seconds. Back-of-the-envelope math like this lets you rule out an approach in an interview before writing any code.

At n = 10⁶, O(n²) is 10¹² operations, about three hours; O(n log n) is around 0.2 seconds. Back-of-the-envelope math like this lets you rule out an approach in an interview before writing any code.

Read in post: Basic algorithms
Edge caseJuniorSelection sort must compare against a[min], not a[i]The selection sort code on the slide (an image) writes if (a[j] < a[i]) min = j;. Then min isn't the position of the minimum; it's the last position whose value is smaller than a[i]. Take [3, 1, 2]: for i = 0, both 1 and 2 are smaller than 3, so min ends at index 2; the swap gives [2, 1, 3]; for i = 1 nothing is smalle

The selection sort code on the slide (an image) writes if (a[j] < a[i]) min = j;. Then min isn't the position of the minimum; it's the last position whose value is smaller than a[i].

Take [3, 1, 2]: for i = 0, both 1 and 2 are smaller than 3, so min ends at index 2; the swap gives [2, 1, 3]; for i = 1 nothing is smaller than 1. The result is [2, 1, 3], not sorted.

The code above is already correct (a[j] < a[min]); if you copied the slide, fix this line. To catch bugs like this, test small arrays where several elements are smaller than the first one, and compare with Arrays.sort.

Read in post: Basic algorithms
Trade-offJuniorInsertion vs bubble vs selection sortInsertion sort: stable, close to O(n) on nearly sorted data, tiny overhead on small arrays. Selection sort: only earns its place when writes are very expensive, since it does at most n - 1 swaps. Bubble sort: does the most swaps and is almost never the right choice.
Best Average Worst Extra memory Stable Swaps
Insertion O(n) O(n²) O(n²) O(1) Yes O(n²) shifts
Bubble (with flag) O(n) O(n²) O(n²) O(1) Yes O(n²)
Selection O(n²) O(n²) O(n²) O(1) No O(n)
  • Insertion sort: stable, close to O(n) on nearly sorted data, tiny overhead on small arrays.
  • Selection sort: only earns its place when writes are very expensive, since it does at most n - 1 swaps.
  • Bubble sort: does the most swaps and is almost never the right choice.
Read in post: Basic algorithms
InterviewJuniorWhat is Big-O, and why do we drop constants?

Big-O is an upper bound on how cost grows as n gets large; constants are dropped because for large enough n, the shape of the function is what dominates.

Constants depend on the machine, the language and the compiler, while n versus n² is a fundamental difference. For small n, though, constants still matter in practice.

Read in post: Basic algorithms
InterviewJuniorWhat does a stable sort mean?

Elements with equal keys keep the relative order they had before sorting.

Insertion and bubble sort are stable; selection sort isn't.

Read in post: Basic algorithms
InterviewJuniorIf the input doubles, how does the running time of O(1), O(log n), O(n) and O(n²) change?

O(1) stays the same, O(log n) adds one step, O(n) doubles, O(n²) quadruples.

O(log n) adds only one step because log₂(2n) = log₂ n + 1. O(n log n) slightly more than doubles; O(2ⁿ) gets squared. It's also a quick benchmark check: measure at n and 2n, and the ratio tells you the growth rate.

Read in post: Basic algorithms
InterviewMidA selection sort uses if (a[j] < a[i]) min = j;. What's wrong? Give a counter-example.

It must compare against a[min] (the smallest value found so far), not a[i]; the counter-example [3, 1, 2] ends up as [2, 1, 3].

Against a[i], min is just the last position that's smaller than a[i]. For [3, 1, 2], the first pass ends with min = 2 and the swap gives [2, 1, 3]; later passes change nothing. The lesson: in a "pick the best element" algorithm, the running best is what you compare against; and always test on small arrays with several competing elements, checking against Arrays.sort.

Read in post: Basic algorithms
InterviewMidWhy do standard libraries still use insertion sort if it's O(n²)?

Because its constant factors are tiny on small arrays, and on nearly sorted data it's close to O(n).

No recursion, sequential access, very little overhead. That's why hybrid algorithms like TimSort and the JDK's dual-pivot quicksort fall back to insertion sort for small ranges (a few dozen elements).

Read in post: Basic algorithms
InterviewMidWhat's the difference between best, average and worst case, and amortized cost?

Best/average/worst case describe one run on different kinds of input; amortized is the average over a sequence of operations, with no probability involved.

  • Insertion sort: O(n) at best on sorted input, O(n²) at worst on reversed input, O(n²) on average.
  • ArrayList.add is occasionally O(n) when it resizes, but n adds cost O(n) in total, so each is O(1) amortized.
  • Average case needs an assumption about the input distribution; amortized doesn't.
Read in post: Basic algorithms
InterviewMidWhy isn't selection sort stable, and when is it still worth using?

Because its long-distance swap can jump an element over another with the same key; it's only worth using when writes are very expensive.

For [2a, 2b, 1], swapping 2a with 1 gives [1, 2b, 2a], so the two 2s are reversed. Its one strength is at most n - 1 swaps, which helps when writes are expensive (flash memory, for instance); otherwise insertion sort is better.

Read in post: Basic algorithms
InterviewSeniorWhen can an O(n log n) algorithm be slower than an O(n²) one in practice?

When n is small: constants and hardware effects dominate, because Big-O only describes the trend as n → ∞.

Insertion sort on 20 elements beats merge sort because it doesn't allocate, doesn't recurse and accesses memory sequentially. That's why hybrid algorithms exist, and why you measure with a benchmark (JMH) instead of reasoning alone.

Read in post: Basic algorithms
TILSeniorDatabases use external merge sort when ORDER BY spills out of sort memoryExternal sorting is for data bigger than RAM, say a 100 GB log file. Split it into chunks that fit in memory, sort each one, write them to disk, then do a k-way merge with a PriorityQueue holding the head of each chunk. Databases do exactly this when an ORDER BY result doesn't fit in workmem (PostgreSQL) or sortbuffers

External sorting is for data bigger than RAM, say a 100 GB log file. Split it into chunks that fit in memory, sort each one, write them to disk, then do a k-way merge with a PriorityQueue holding the head of each chunk.

Databases do exactly this when an ORDER BY result doesn't fit in work_mem (PostgreSQL) or sort_buffer_size (MySQL): EXPLAIN ANALYZE shows "external merge".

Read in post: Basic Algorithms
Edge caseMidQuicksort with a fixed pivot degrades to O(n²) on sorted inputIf every pivot happens to be the smallest or largest element, each round removes just one element: n + (n-1) + ... + 1 = O(n²). The textbook case: always taking the first or last element as the pivot on already sorted input. Real data is often partly sorted (increasing IDs, timestamps...).

If every pivot happens to be the smallest or largest element, each round removes just one element: n + (n-1) + ... + 1 = O(n²). The textbook case: always taking the first or last element as the pivot on already sorted input. Real data is often partly sorted (increasing IDs, timestamps...).

Read in post: Basic Algorithms
Edge caseMidLomuto partition degrades to O(n²) when every element is equalEven with a random pivot, Lomuto on an array where every element is equal is still O(n²), because everything lands on one side. Three-way partitioning fixes it: On a million identical elements this version finishes in a single O(n) pass (I tried it).

Even with a random pivot, Lomuto on an array where every element is equal is still O(n²), because everything lands on one side. Three-way partitioning fixes it:

static void quickSort3Way(int[] a, int lo, int hi) {
    if (lo >= hi) return;
    int pivot = a[ThreadLocalRandom.current().nextInt(lo, hi + 1)];
    int lt = lo, i = lo, gt = hi;
    // invariant: a[lo..lt-1] < pivot, a[lt..i-1] == pivot, a[gt+1..hi] > pivot
    while (i <= gt) {
        if (a[i] < pivot) swap(a, lt++, i++);
        else if (a[i] > pivot) swap(a, i, gt--);   // don't advance i: the swapped-in value is unexamined
        else i++;
    }
    quickSort3Way(a, lo, lt - 1);
    quickSort3Way(a, gt + 1, hi);
}

On a million identical elements this version finishes in a single O(n) pass (I tried it).

Read in post: Basic Algorithms
Trade-offSeniorHoare partition vs Lomuto partitionHoare partition is Tony Hoare's original scheme: two pointers move inward from both ends and swap pairs that are on the wrong side. It does about three times fewer swaps than Lomuto and handles duplicates better. The price is that it's easier to get wrong: the index it returns is not the pivot's final position. Lomuto

Hoare partition is Tony Hoare's original scheme: two pointers move inward from both ends and swap pairs that are on the wrong side. It does about three times fewer swaps than Lomuto and handles duplicates better. The price is that it's easier to get wrong: the index it returns is not the pivot's final position.

Lomuto is easier to write and to prove correct, but degrades with many duplicates.

Read in post: Basic Algorithms
Trade-offMidQuicksort vs merge sort in practiceBoth are O(n log n), yet quicksort is usually faster in practice: it sorts in place with no copying to and from a buffer, its scanning loops are sequential and cache-friendly, and its constants are small. The price is no stability and an O(n²) worst case. Merge sort costs O(n) extra memory but is stable and guaranteed

Both are O(n log n), yet quicksort is usually faster in practice: it sorts in place with no copying to and from a buffer, its scanning loops are sequential and cache-friendly, and its constants are small. The price is no stability and an O(n²) worst case.

Merge sort costs O(n) extra memory but is stable and guaranteed O(n log n). Pick it when you need stability, guaranteed time, or are sorting a linked list / doing an external sort.

Read in post: Basic Algorithms
TILSeniorArrays.sort for primitives was rewritten in Java 14 with an O(n log n) worst caseIn Java 14 (JDK-8226297) the Dual-Pivot Quicksort behind Arrays.sort(int[]) was rewritten: insertion sort for tiny ranges; detection and merging of existing sorted runs, so nearly sorted data is very fast; a fallback to heapsort when recursion gets too deep, so the worst case is O(n log n). Large enough byte[], char[]

In Java 14 (JDK-8226297) the Dual-Pivot Quicksort behind Arrays.sort(int[]) was rewritten:

  • insertion sort for tiny ranges;
  • detection and merging of existing sorted runs, so nearly sorted data is very fast;
  • a fallback to heapsort when recursion gets too deep, so the worst case is O(n log n).

Large enough byte[], char[] and short[] arrays use counting sort.

Read in post: Basic Algorithms
Trade-offMidWhy Java sorts primitives with quicksort but objects with TimSortObjects have identity and multiple fields, so object sorting must be stable. If you sort orders by amount and then by customer, you want orders from the same customer to stay in amount order. Primitives get quicksort: fast, in-place, unstable, but equal values are indistinguishable. Objects get TimSort: stable, at the

Objects have identity and multiple fields, so object sorting must be stable. If you sort orders by amount and then by customer, you want orders from the same customer to stay in amount order.

Primitives get quicksort: fast, in-place, unstable, but equal values are indistinguishable. Objects get TimSort: stable, at the cost of up to n/2 references of extra memory.

Read in post: Basic Algorithms
TILMidCollections.sort on a LinkedList is still O(n log n)Collections.sort(list) just calls list.sort(null). ArrayList.sort sorts its internal array directly. The default List.sort copies to an array, sorts it and writes back through a ListIterator, so sorting a LinkedList is still O(n log n), not a disaster.

Collections.sort(list) just calls list.sort(null). ArrayList.sort sorts its internal array directly. The default List.sort copies to an array, sorts it and writes back through a ListIterator, so sorting a LinkedList is still O(n log n), not a disaster.

Read in post: Basic Algorithms
Edge caseSeniorArrays.parallelSort shares the ForkJoin common pool with the whole applicationArrays.parallelSort splits the array into chunks, sorts them in parallel on the ForkJoin common pool, then merges. It only actually goes parallel above a threshold of 8192 elements (1 << 13); below that it just calls Arrays.sort. The common pool is shared with parallelStream and default CompletableFuture tasks. So a pa

Arrays.parallelSort splits the array into chunks, sorts them in parallel on the ForkJoin common pool, then merges. It only actually goes parallel above a threshold of 8192 elements (1 << 13); below that it just calls Arrays.sort.

The common pool is shared with parallelStream and default CompletableFuture tasks. So a parallel sort inside a request handler can compete with the rest of your application.

Read in post: Basic Algorithms
Edge caseMidThe comparator (x, y) -> x - y breaks when subtraction overflowsTrap 1: comparing by subtraction. Integer.MINVALUE - 1 overflows to the largest positive int. Use Integer.compare, Long.compare or Comparator.comparingInt(...).

Trap 1: comparing by subtraction.

Comparator<Integer> bad = (x, y) -> x - y;          // WRONG with large negative numbers
bad.compare(Integer.MIN_VALUE, 1);                  // 2147483647: claims MIN_VALUE > 1 !
Comparator<Integer> good = Integer::compare;        // or Comparator.naturalOrder()

Integer.MIN_VALUE - 1 overflows to the largest positive int. Use Integer.compare, Long.compare or Comparator.comparingInt(...).

Read in post: Basic Algorithms
Edge caseSeniorA comparator that breaks its contract makes TimSort throw IllegalArgumentExceptionTrap 2: breaking the contract. A comparator must be antisymmetric (sgn(compare(a,b)) == -sgn(compare(b,a))), transitive, and give the same results throughout the sort. Examples of breaking it: comparing by a random value or the current time, or comparing doubles that may be NaN with </. TimSort may then throw IllegalAr

Trap 2: breaking the contract. A comparator must be antisymmetric (sgn(compare(a,b)) == -sgn(compare(b,a))), transitive, and give the same results throughout the sort. Examples of breaking it: comparing by a random value or the current time, or comparing doubles that may be NaN with </>.

TimSort may then throw IllegalArgumentException: Comparison method violates its general contract!. This often only shows up in production with large enough data: TimSort only notices the inconsistency in certain branches of its merge step, and those only run once runs get long enough.

Read in post: Basic Algorithms
Edge caseJuniorNatural-order comparators throw NullPointerException on nullTrap 3: null. Natural-order comparators throw NullPointerException on null. Use Comparator.nullsFirst(...) or nullsLast(...).

Trap 3: null. Natural-order comparators throw NullPointerException on null. Use Comparator.nullsFirst(...) or nullsLast(...).

Read in post: Basic Algorithms
Edge caseMidBigDecimal.compareTo is inconsistent with equalsTrap 4: compareTo inconsistent with equals. new BigDecimal("1.0") and new BigDecimal("1.00") have compareTo == 0 but equals == false. A TreeSet keeps one; a HashSet keeps both.

Trap 4: compareTo inconsistent with equals. new BigDecimal("1.0") and new BigDecimal("1.00") have compareTo == 0 but equals == false. A TreeSet keeps one; a HashSet keeps both.

Read in post: Basic Algorithms
Trade-offMidSort in the database or in the applicationThe practical rule: sort where the data lives. ORDER BY createdat DESC LIMIT 20 with an index on createdat lets the database read 20 rows in index order without sorting anything. Pulling a million rows into the application to list.sort(...) them costs network, heap and GC pressure. Sort in the application only when the

The practical rule: sort where the data lives. ORDER BY created_at DESC LIMIT 20 with an index on created_at lets the database read 20 rows in index order without sorting anything. Pulling a million rows into the application to list.sort(...) them costs network, heap and GC pressure.

Sort in the application only when the data is already in memory, or the order depends on logic you can't express in SQL. For a "top K" over a large stream, use a size-K PriorityQueue, O(n log K), instead of sorting everything.

Read in post: Basic Algorithms
Trade-offMidCounting sort vs merge sort vs quicksort for "Sort an Array"Merge sort: guaranteed O(n log n), O(n) extra memory. Three-way quicksort with a random pivot: only O(log n) expected stack, but O(n log n) is expected, not guaranteed. Counting sort: O(n + k), the fastest for this problem, but only because the value range is small and known up front. Being able to articulate that trad
  • Merge sort: guaranteed O(n log n), O(n) extra memory.
  • Three-way quicksort with a random pivot: only O(log n) expected stack, but O(n log n) is expected, not guaranteed.
  • Counting sort: O(n + k), the fastest for this problem, but only because the value range is small and known up front.

Being able to articulate that trade-off is a plus in an interview.

Read in post: Basic Algorithms
Edge caseMid.reversed() at the end of a comparator chain reverses the whole chain, not just the last keyTo reverse only the salary key, use thenComparing(keyExtractor, Comparator.reverseOrder()). Calling .reversed() at the end of the chain reverses the whole comparator built so far, which is a very common mistake.

To reverse only the salary key, use thenComparing(keyExtractor, Comparator.reverseOrder()). Calling .reversed() at the end of the chain reverses the whole comparator built so far, which is a very common mistake.

Read in post: Basic Algorithms
InterviewJuniorHow does merge sort work, and what's its complexity?

Split in half, recursively sort each half, merge with two pointers; O(n log n) in every case.

There are log n levels and each level's merging costs O(n). It needs O(n) extra memory and is stable.

Read in post: Basic Algorithms
InterviewJuniorHow does quicksort work, and when does it degrade to O(n²)?

Pick a pivot, partition smaller to the left and larger to the right, then recurse on both sides. It degrades to O(n²) when the pivot is repeatedly the min or max.

After partitioning the pivot is in its final spot. Worst-case example: taking the first element as the pivot on a sorted array.

Read in post: Basic Algorithms
InterviewJuniorWhat are the main differences between merge sort and quicksort?

Merge sort divides trivially and does the work when merging; quicksort does the work when partitioning and needs no merge.

Merge sort is stable, guaranteed O(n log n) and uses O(n) memory. Quicksort is in-place and usually faster in practice, but unstable with an O(n²) worst case.

Read in post: Basic Algorithms
InterviewMidHow do you avoid quicksort's worst case?

A random pivot or median-of-three, plus introsort to guarantee O(n log n).

  • Three-way partitioning when there are many duplicates.
  • Recurse into the smaller side to keep the stack at O(log n).
  • Like introsort, fall back to heapsort when recursion gets too deep.
Read in post: Basic Algorithms
InterviewMidWhich algorithms do Arrays.sort(int[]) and Arrays.sort(Object[]) use, and why the difference?

Primitives use Dual-Pivot Quicksort, objects use TimSort, because objects need stability and primitives don't.

Dual-Pivot Quicksort dates from Java 7 and was rewritten in Java 14 with a heapsort fallback. Equal primitives are indistinguishable, so a fast in-place algorithm wins. Objects have several fields and people often sort repeatedly by different keys.

Read in post: Basic Algorithms
InterviewMidWhy is (a, b) -> a - b a dangerous comparator?

The subtraction can overflow, so the comparator returns the wrong sign.

Integer.MIN_VALUE - 1 becomes positive, so the sort comes out wrong or TimSort throws "Comparison method violates its general contract!". Use Integer.compare or Comparator.comparingInt.

Read in post: Basic Algorithms
InterviewMidWhat's the lower bound for comparison sorting, and how does counting sort get around it?

Ω(n log n); counting sort doesn't compare but uses key values as indices, reaching O(n + k).

You have to distinguish n! orderings and each comparison gives one bit, so you need log₂(n!) ≈ n log n comparisons. Counting and radix sort only work for integer keys in a small range (or keys that split into digits).

Read in post: Basic Algorithms
InterviewSeniorHow does TimSort work, and why does it suit real-world data?

TimSort finds already ordered runs and merges them; real data usually has local order, so it gets close to O(n).

Descending runs get reversed; short runs are extended to minrun with binary insertion sort. Runs are merged according to invariants on a stack so merges stay balanced; when one side keeps winning it switches to galloping. Time-ordered appends or nearly sorted lists run close to O(n), while O(n log n) and stability are still guaranteed.

Read in post: Basic Algorithms
InterviewSeniorYou need to sort a 100 GB file on a machine with 8 GB of RAM. How?

External merge sort: sort RAM-sized chunks into temp files, then k-way merge them with a min-heap.

  • Read ~1 GB chunks, sort each in memory, write it to a temp file (about 100 runs).
  • Open every run and keep the head of each in a PriorityQueue; pop the minimum to the output and refill from the same run.
  • Use large buffers for sequential I/O. With too many runs, merge in several passes.

It's also how databases handle an ORDER BY that spills out of sort memory.

Read in post: Basic Algorithms
InterviewSeniorWhat does "Comparison method violates its general contract!" mean, and how do you debug it?

TimSort detected an inconsistent comparator: not antisymmetric, not transitive, or changing results mid-sort.

  • Common causes: overflowing subtraction, mishandled null/NaN, comparing data another thread is mutating, comparators based on time or randomness.
  • It only surfaces with large enough data, so it's typically seen in production.
  • Fix: build comparators with Comparator.comparing..., check the contract with property-based tests, sort an immutable snapshot.

The java.util.Arrays.useLegacyMergeSort flag only hides the bug.

Read in post: Basic Algorithms
InterviewSeniorShould you use Arrays.parallelSort inside a web service?

Usually not; it runs on the shared ForkJoin common pool, so under heavy load it can raise latency for other requests.

It only pays off for very large arrays (well past the 8192 threshold) when there are idle cores. In a service handling many concurrent requests the cores are already busy, so a sequential sort is often better; batch jobs are a better fit for parallelSort. Always benchmark.

Read in post: Basic Algorithms
InterviewSeniorYou need the top 100 best-selling products from a stream of 10 million records. Do you sort everything?

No. Keep a min-heap of size 100: O(n log k) time, O(k) memory, and it works on a stream.

For each record, if it beats the heap's top, replace the top. If the data lives in the database, use ORDER BY sales DESC LIMIT 100 with a suitable index. If everything is already in an array, quickselect gives O(n) on average.

Read in post: Basic Algorithms
Edge caseJunior== on Integer only works inside the -128..127 cacheFor objects, == compares addresses and equals() compares contents. A classic interview question:

For objects, == compares addresses and equals() compares contents. A classic interview question:

Integer x = 127, y = 127;
x == y;          // true: the Integer cache holds -128 to 127
Integer m = 128, n = 128;
m == n;          // false: two different objects
m.equals(n);     // true
Read in post: Java basics
Edge caseMidi++ is not atomici++ is not atomic (atomic: done in one indivisible step, with no other thread able to cut in). It is three steps, read, add, write, so several threads running count++ concurrently lose some increments. A shared counter needs AtomicInteger/LongAdder or a lock.

i++ is not atomic (atomic: done in one indivisible step, with no other thread able to cut in). It is three steps, read, add, write, so several threads running count++ concurrently lose some increments. A shared counter needs AtomicInteger/LongAdder or a lock.

Read in post: Java basics
Edge caseJuniorInteger.MAX_VALUE + 1 wraps to MIN_VALUE silentlyNegative numbers use two's complement: flip all the bits and add 1. That is why Integer.MAXVALUE + 1 == Integer.MINVALUE: overflow wraps around instead of throwing. The JDK gives you Integer.toBinaryString, Integer.parseInt("1101", 2) and Integer.toHexString.

Negative numbers use two's complement: flip all the bits and add 1. That is why Integer.MAX_VALUE + 1 == Integer.MIN_VALUE: overflow wraps around instead of throwing. The JDK gives you Integer.toBinaryString, Integer.parseInt("1101", 2) and Integer.toHexString.

Read in post: Java basics
Edge caseJunior~5 is -6 because an int has 32 bits, not 4The slide writes ~5 as ~0101 = 1010 and labels it -6, which makes it look as if 1010 were -6. An int actually has 32 bits, so ~5 also flips the 28 leading zeros: 11111111 11111111 11111111 11111010. The top bit is 1, so in two's complement it's negative; flip the bits and add 1 to read its value: 0…0101 + 1 = 6, so the

The slide writes ~5 as ~0101 = 1010 and labels it -6, which makes it look as if 1010 were -6. An int actually has 32 bits, so ~5 also flips the 28 leading zeros: 11111111 11111111 11111111 11111010. The top bit is 1, so in two's complement it's negative; flip the bits and add 1 to read its value: 0…0101 + 1 = 6, so the result is -6.

The general rule for any integer: ~x == -x - 1 (~0 == -1, ~-1 == 0). Check it with Integer.toBinaryString(~5).

Read in post: Java basics
Edge caseMidA ternary mixing int and Integer can throw NullPointerExceptionInteger v = flag ? 1 : nullableInteger; can throw a NullPointerException. The expression is unboxed to int (unboxing: taking the int value out of an Integer, and a null has nothing to take) before being boxed again.

Integer v = flag ? 1 : nullableInteger; can throw a NullPointerException. The expression is unboxed to int (unboxing: taking the int value out of an Integer, and a null has nothing to take) before being boxed again.

Read in post: Java basics
TILMidPattern matching for switch (Java 21)Pattern matching for switch (Java 21) lets you switch on types, with when guards:

Pattern matching for switch (Java 21) lets you switch on types, with when guards:

static String describe(Object o) {
    return switch (o) {
        case null -> "null";
        case Integer i when i > 100 -> "big number " + i;
        case Integer i -> "number " + i;
        case String s -> "string of length " + s.length();
        default -> "something else";
    };
}
Read in post: Java basics
Trade-offJuniorif/else if vs switchWhen an if/switch chain on some "kind" keeps growing, that is usually a sign to switch to polymorphism (see the OOP post) or a Map<Key, Handler.
if / else if switch
Condition Any boolean expression, including ranges Matches specific values (or patterns in Java 21)
Types Anything Restricted as above
Branches executed Exactly one One, or several if you forget break (classic form)
Exhaustiveness check No Yes, for switch expressions over enums/sealed types

When an if/switch chain on some "kind" keeps growing, that is usually a sign to switch to polymorphism (see the OOP post) or a Map<Key, Handler>.

Read in post: Java basics
Edge caseJuniorscore < 0 || score > 10 lets NaN throughEvery comparison with NaN is false, so Double.NaN < 0 || Double.NaN 10 is false and NaN passes the "out of range" check. If grade checked its input that way, NaN would slip past every if and come out as "Weak". Write the condition in its positive form and negate the whole thing, !(score = 0 && score <= 10), and NaN is

Every comparison with NaN is false, so Double.NaN < 0 || Double.NaN > 10 is false and NaN passes the "out of range" check. If grade checked its input that way, NaN would slip past every if and come out as "Weak".

Write the condition in its positive form and negate the whole thing, !(score >= 0 && score <= 10), and NaN is rejected. NaN does show up in practice, for example as 0.0 / 0 when averaging an empty list.

Read in post: Java basics
InterviewJuniorWhat are 7 / 2, 7 % -2 and -7 / 2?

3, 1 and -3.

Integer division truncates toward zero, and the remainder takes the sign of the dividend. For a remainder that is never negative, use Math.floorMod.

Read in post: Java basics
InterviewJuniorWhat is the difference between a++ and ++a?

a++ evaluates to the value before the increment, ++a to the value after it.

Both add 1 to a. The difference only matters when they are part of a larger expression, such as b = a++.

Read in post: Java basics
InterviewJuniorWhat is the difference between && and & on booleans?

Both compute AND, but && short-circuits (if the left side is false, the right side is skipped) while & always evaluates both sides.

That's why user != null && user.isActive() is safe while user != null & user.isActive() still throws NullPointerException when user is null. The same goes for || and |. On integers, & and | are bitwise operators.

Read in post: Java basics
InterviewJuniorCompute 5 & 3, 5 | 3, 5 ^ 3, 5 << 2, 5 >> 2 and ~5. Why is ~5 negative?

1, 7, 6, 20, 1, -6; ~5 is negative because flipping all 32 bits sets the sign bit.

5 = 0101 and 3 = 0011. 5 << 2 multiplies by 4, 5 >> 2 divides by 4 rounding down. In two's complement, ~x == -x - 1.

Read in post: Java basics
InterviewMidInteger a = 128, b = 128; a == b: what does it return, and why?

false, because Integer.valueOf only caches -128 to 127, so 128 gives two distinct objects.

Autoboxing (wrapping an int into an Integer automatically) calls Integer.valueOf, and == compares references. Always compare wrappers with equals (or Objects.equals).

Read in post: Java basics
InterviewMidWhat do switch expressions (Java 14+) improve over the classic switch?

No fall-through, they produce a value, and the compiler checks exhaustiveness for enums and sealed types.

Several labels can share a case with commas. Java 21 adds pattern matching and when guards.

Read in post: Java basics
InterviewMidDoes short s = 1; s = s + 1; compile? What about s += 1?

s = s + 1 doesn't compile; s += 1 does.

s + 1 is an int and won't narrow to short on its own. Compound assignment includes an implicit cast back to the left-hand type.

Read in post: Java basics
InterviewSeniorIs count++ on a field shared between threads safe?

No. It is a read, an add and a write; interleaved threads lose updates (a race condition).

volatile only guarantees visibility, not atomicity. Use AtomicInteger.incrementAndGet(), LongAdder for heavy write contention, or synchronized.

Read in post: Java basics
InterviewSeniorAn if/else or switch chain on some "type" keeps growing. How would you refactor it?

The goal is that adding a new type doesn't require editing existing code; pick polymorphism, a Map<Type, Handler> or a sealed interface depending on the case.

  • Polymorphism: one class per type implementing a shared interface, following the Open/Closed Principle.
  • A Map<Type, Handler> or a Strategy that Spring injects as a List<Handler>.
  • A sealed interface with pattern-matching switch, so the compiler enforces exhaustiveness.
Read in post: Java basics
Trade-offSeniorinnodb_flush_log_at_trx_commit: safety vs commit speed1 (the default) fsyncs the redo log on every commit, the safest option. 2 or 0 is faster but can lose about a second of transactions if the OS or machine crashes. Postgres has synchronouscommit with the same idea.

1 (the default) fsyncs the redo log on every commit, the safest option. 2 or 0 is faster but can lose about a second of transactions if the OS or machine crashes. Postgres has synchronous_commit with the same idea.

Read in post: Databases
Edge caseMid@Transactional is ignored when called from a method in the same class@Transactional works through a proxy. Calling a @Transactional method from another method in the same class (self-invocation) bypasses the proxy, so there is no transaction. By default Spring only rolls back on RuntimeException/Error; checked exceptions need rollbackFor. Don't make HTTP calls to other services inside a
  • @Transactional works through a proxy. Calling a @Transactional method from another method in the same class (self-invocation) bypasses the proxy, so there is no transaction.
  • By default Spring only rolls back on RuntimeException/Error; checked exceptions need rollbackFor.
  • Don't make HTTP calls to other services inside a transaction: a long transaction holds locks and a pool connection.
Read in post: Databases
Edge caseSeniorInnoDB REPEATABLE READ doesn't prevent lost updates or write skewMySQL InnoDB defaults to REPEATABLE READ. Plain reads (consistent reads) use a snapshot taken at the first read, so they see no phantoms. Locking reads (FOR UPDATE, UPDATE, DELETE) read the latest version and take next-key locks (the row plus the gap before it) to block phantom inserts. But RR doesn't detect lost updat
  • MySQL InnoDB defaults to REPEATABLE READ. Plain reads (consistent reads) use a snapshot taken at the first read, so they see no phantoms. Locking reads (FOR UPDATE, UPDATE, DELETE) read the latest version and take next-key locks (the row plus the gap before it) to block phantom inserts. But RR doesn't detect lost updates and doesn't prevent write skew.
  • PostgreSQL defaults to READ COMMITTED. Postgres RR is real snapshot isolation: if two transactions modify the same row, the second fails with could not serialize access due to concurrent update and must retry. SERIALIZABLE (SSI) also stops write skew.
  • Oracle has neither READ UNCOMMITTED nor REPEATABLE READ.
Read in post: Databases
Trade-offSeniorOptimistic vs pessimistic lockingOptimistic: a version column (UPDATE ... WHERE id = ? AND version = ?). Pessimistic: SELECT ... FOR UPDATE. JPA/Hibernate has @Version (throws OptimisticLockException) and @Lock(LockModeType.PESSIMISTICWRITE).

Optimistic: a version column (UPDATE ... WHERE id = ? AND version = ?). Pessimistic: SELECT ... FOR UPDATE. JPA/Hibernate has @Version (throws OptimisticLockException) and @Lock(LockModeType.PESSIMISTIC_WRITE).

Optimistic Pessimistic
Fits Rare conflicts, read-heavy Frequent conflicts, expensive retries
Cost Retry on conflict Holds locks, lowers throughput, can deadlock
Survives across requests Yes (the version goes to the client) No (locks live only inside the transaction)
Read in post: Databases
Trade-offSeniorREAD COMMITTED vs REPEATABLE READ on MySQLREPEATABLE READ: one snapshot for the whole transaction, so a report made of several SELECTs sees consistent data. The cost: locking reads use next-key/gap locks, so lock waits and deadlocks are likely when many transactions insert into the same range. READ COMMITTED: a fresh snapshot per statement, almost no gap locks
  • REPEATABLE READ: one snapshot for the whole transaction, so a report made of several SELECTs sees consistent data. The cost: locking reads use next-key/gap locks, so lock waits and deadlocks are likely when many transactions insert into the same range.
  • READ COMMITTED: a fresh snapshot per statement, almost no gap locks, and InnoDB releases locks on scanned rows that don't match the WHERE. Fewer deadlocks, better write throughput. The cost: two reads in one transaction can differ, and the binlog must be ROW format (the default since MySQL 5.7.7).

Neither prevents lost updates or write skew. PostgreSQL already defaults to READ COMMITTED.

Read in post: Databases
Edge caseSeniorAn UPDATE on an unindexed column can lock the whole tableUPDATE ... WHERE note = 'x' on an unindexed column has to scan and lock every row it scans (under RR). One update missing an index can lock the whole table.

UPDATE ... WHERE note = 'x' on an unindexed column has to scan and lock every row it scans (under RR). One update missing an index can lock the whole table.

Read in post: Databases
Trade-offSeniorA job queue in the database (SKIP LOCKED) vs a message brokerA job table + SKIP LOCKED handles tens to a few hundred jobs per second. Its big advantage: you create the job in the same transaction as the business data (placing an order and queuing its email commit or roll back together), with no extra infrastructure. The cost: every worker polls the database, the job table bloats

A job table + SKIP LOCKED handles tens to a few hundred jobs per second. Its big advantage: you create the job in the same transaction as the business data (placing an order and queuing its email commit or roll back together), with no extra infrastructure. The cost: every worker polls the database, the job table bloats without cleanup, and fanning one event out to many consumers is awkward.

A message broker (Kafka, RabbitMQ) fits high throughput, many independent consumers, or keeping an event stream. The cost: one more system to run, and you lose atomicity with the database. To write to the DB and publish an event safely you need a transactional outbox: write the event to an outbox table in the same transaction, and a separate process pushes it to the broker.

Read in post: Databases
Edge caseSeniorLong-running transactions bloat the undo log or dead tuplesA long-running transaction keeps an old snapshot alive, so the undo log (MySQL, watch history list length) or dead tuples (Postgres) can't be cleaned up. Tables bloat and every query slows down. A batch job holding a transaction for 2 hours, or a console session that ran BEGIN and went to lunch, both cause it.

A long-running transaction keeps an old snapshot alive, so the undo log (MySQL, watch history list length) or dead tuples (Postgres) can't be cleaned up. Tables bloat and every query slows down. A batch job holding a transaction for 2 hours, or a console session that ran BEGIN and went to lunch, both cause it.

Read in post: Databases
Edge caseSeniorSELECT ... FOR UPDATE on a missing row deadlocks when two requests insert at onceUnder RR, a FOR UPDATE that finds no row takes a gap lock on the range where the row would be. Gap locks from two transactions don't conflict, so both pass the check. Then each INSERT needs an insert intention lock on that same range and is blocked by the other's gap lock: a cycle, and InnoDB rolls one back with error

Under RR, a FOR UPDATE that finds no row takes a gap lock on the range where the row would be. Gap locks from two transactions don't conflict, so both pass the check. Then each INSERT needs an insert intention lock on that same range and is blocked by the other's gap lock: a cycle, and InnoDB rolls one back with error 1213.

The right way: let the unique constraint do the check. INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE and check affected rows (MySQL), INSERT ... ON CONFLICT DO NOTHING (Postgres), or just insert and catch the duplicate-key error.

Read in post: Databases
Edge caseSeniorRetrying inside the same transaction after a deadlock is meaninglessA deadlock victim (1213) has its whole transaction rolled back, not just the failed statement. Re-running that one UPDATE executes in a new autocommit transaction, losing every earlier change and leaving half-done data. In Spring the transaction is already marked rollback-only, so the final commit throws UnexpectedRoll

A deadlock victim (1213) has its whole transaction rolled back, not just the failed statement. Re-running that one UPDATE executes in a new autocommit transaction, losing every earlier change and leaving half-done data. In Spring the transaction is already marked rollback-only, so the final commit throws UnexpectedRollbackException.

Rule: the retry loop sits outside the transaction boundary, bounded, with randomized backoff. The work inside must be safe to re-run: don't send emails or call external APIs inside a transaction that may be retried.

Read in post: Databases
TILSeniorDatabases have built-in advisory locks for locking by name, no table neededMySQL: GETLOCK('report:42', 5) (waits up to 5 seconds, returns 1 if acquired) and RELEASELOCK('report:42'). The lock belongs to the session/connection, not the transaction: commit doesn't release it. With a connection pool, forgetting RELEASELOCK keeps the lock alive until the connection closes. PostgreSQL: pgadvisoryx
  • MySQL: GET_LOCK('report:42', 5) (waits up to 5 seconds, returns 1 if acquired) and RELEASE_LOCK('report:42'). The lock belongs to the session/connection, not the transaction: commit doesn't release it. With a connection pool, forgetting RELEASE_LOCK keeps the lock alive until the connection closes.
  • PostgreSQL: pg_advisory_xact_lock(key) releases automatically when the transaction ends, safer with pools; pg_try_advisory_lock tries without waiting.
  • ShedLock uses the same idea (with a lock table) so a @Scheduled task runs on only one instance.
Read in post: Databases
InterviewJuniorWhat does ACID stand for?

The four transaction properties: Atomicity, Consistency, Isolation, Durability.

Atomicity: all or nothing. Consistency: constraints always hold. Isolation: concurrent transactions don't see each other's half-done state (per the isolation level). Durability: committed data survives a crash, thanks to the redo log/WAL.

Read in post: Databases
InterviewJuniorHow do dirty reads, non-repeatable reads and phantom reads differ?

A dirty read sees uncommitted data; a non-repeatable read re-reads a row and gets a different value; a phantom read re-runs a condition and sees a new row.

Non-repeatable reads come from another transaction updating and committing; phantoms come from another transaction inserting. READ COMMITTED stops the first, REPEATABLE READ also stops the second, SERIALIZABLE stops all three.

Read in post: Databases
InterviewMidOptimistic vs pessimistic locking: what's the difference and when do you use each?

Optimistic doesn't lock and checks a version on write; pessimistic locks the row on read with SELECT ... FOR UPDATE.

Optimistic retries on conflict; it fits rare conflicts and state that spans several requests. Pessimistic fits frequent conflicts or expensive retries, but lowers throughput and can deadlock.

Read in post: Databases
InterviewMidWhat is a deadlock and how do you prevent it?

Two or more transactions wait for each other's locks in a cycle; InnoDB detects it and rolls one back (error 1213).

For example, T1 holds A and waits for B, T2 holds B and waits for A. Prevent it by locking in a consistent order, keeping transactions short, indexing the WHERE of UPDATE/DELETE so fewer rows are locked, and always having a bounded retry around the transaction, because deadlocks can't be eliminated entirely.

Read in post: Databases
InterviewMidWhat is FOR UPDATE SKIP LOCKED for?

Letting many workers take work from one table without fighting over it or waiting on each other.

Each worker locks a batch of ready rows and skips rows another worker already locked. Used for job queues in the database and handing out tickets/voucher codes from a pool. It needs an index on the filter and order, and handlers must be idempotent because a worker can die mid-job.

Read in post: Databases
InterviewSeniorDoes MySQL's REPEATABLE READ prevent lost updates? How does PostgreSQL compare?

No, not when the application reads and writes back a precomputed value; PostgreSQL RR detects it and raises a serialization error.

InnoDB lets the UPDATE overwrite the latest version without complaint. PostgreSQL RR sees the row was changed by another transaction after the snapshot and errors so the application retries. Database-neutral fixes: an atomic update (SET x = x + ?), a condition in the WHERE, FOR UPDATE, or an optimistic version.

Read in post: Databases
InterviewSeniorWhat is write skew and which isolation level prevents it?

Two transactions read the same data, each changes a different row, and together they break a rule; only SERIALIZABLE (Postgres SSI) or explicit locking stops it.

For example, two doctors both go off call when only two are on call. Snapshot isolation (MySQL RR, Postgres RR) doesn't stop it. Alternatives: FOR UPDATE on the relevant rows, locking one "representative" row, or turning the rule into a database constraint.

Read in post: Databases
InterviewSeniorHow does MVCC work in InnoDB, and why are long transactions dangerous?

Each row points to undo records holding old versions and a read view picks the visible one; a long transaction keeps an old read view, so purge can't clean the undo.

Each row stores the id of the last transaction that changed it and a pointer into the undo log. A consistent read rebuilds the version from undo when needed. A long transaction makes history list length grow, and every read wades through longer version chains. It also holds locks and metadata locks, which can block ALTER TABLE.

Read in post: Databases
InterviewSeniorAn UPDATE causes wide locking and deadlocks. How do you investigate?

First check whether the WHERE uses an index, because InnoDB locks every index record it scans.

Look at SHOW ENGINE INNODB STATUS (the LATEST DETECTED DEADLOCK section) and performance_schema.data_locks to see which locks are held and awaited. Fix: add the index, lock in a consistent order, shorten the transaction, consider READ COMMITTED to cut gap locks if the business allows it, and retry on deadlock.

Read in post: Databases
InterviewSeniorWhy must the retry loop sit outside the transaction?

Because a deadlock or serialization failure rolls back the whole transaction, so each attempt must be a new transaction.

Spring also marks the transaction rollback-only; re-running one statement inside loses earlier changes or ends in UnexpectedRollbackException. Use TransactionTemplate in a loop, or @Retryable around the @Transactional proxy, bounded, with randomized backoff, and no external side effects inside the transaction.

Read in post: Databases
InterviewSeniorTwo requests both "create it if it doesn't exist". How do you avoid duplicates?

Put a unique constraint on the business key and let the database reject the duplicate; checking in the application always races.

SELECT ... FOR UPDATE on a missing row doesn't help, and under RR it deadlocks, because both sides' gap locks don't conflict but block each other's inserts. Use INSERT ... ON DUPLICATE KEY UPDATE/INSERT IGNORE (MySQL) or ON CONFLICT (Postgres), or insert and catch the duplicate error to read back the existing row.

Read in post: Databases
Edge caseMidTreeSet/TreeMap decide duplicates with compareTo, not equalsTreeSet and TreeMap never call equals or hashCode. Two elements with compare(a, b) == 0 count as one: add returns false, put overwrites the value, and nothing warns you. With the same data, a HashSet keeps both (a record's equals compares every component). The fix: add a tie-breaker at the end of the comparison chain,

TreeSet and TreeMap never call equals or hashCode. Two elements with compare(a, b) == 0 count as one: add returns false, put overwrites the value, and nothing warns you.

record Member(int id, String name, int age) implements Comparable<Member> {
    public int compareTo(Member o) {                 // by age, then by name
        int c = Integer.compare(age, o.age);
        return c != 0 ? c : name.compareTo(o.name);
    }
}
Set<Member> ranking = new TreeSet<>();
ranking.add(new Member(1, "An", 20));
ranking.add(new Member(2, "An", 20));   // different id, but compareTo == 0
ranking.size();                         // 1: a member is gone

With the same data, a HashSet keeps both (a record's equals compares every component). The fix: add a tie-breaker at the end of the comparison chain, e.g. .thenComparingInt(Member::id). Similar cases: String.CASE_INSENSITIVE_ORDER merges "Java" and "JAVA", and BigDecimal treats 1.0 and 1.00 as one.

Read in post: Java Collections
Trade-offMidHashMap, LinkedHashMap or TreeMapDefault: HashMap. Stable insertion-order output (JSON, reports) or an LRU cache: LinkedHashMap. Key order or range/nearest queries: TreeMap. If you only sort once at output time, a HashMap plus sorting its entries is usually cheaper than keeping a tree for the map's whole life. Multiple threads: ConcurrentHashMap, or C
HashMap LinkedHashMap TreeMap
Iteration order Not guaranteed Insertion order (or access order) Ascending by key
get/put O(1) average O(1) average O(log n)
null key One One No (natural ordering)
Range / nearest queries No No Yes (floor, subMap...)
Memory per entry Least Two extra pointers Tree node: 3 pointers + a color
  • Default: HashMap.
  • Stable insertion-order output (JSON, reports) or an LRU cache: LinkedHashMap.
  • Key order or range/nearest queries: TreeMap. If you only sort once at output time, a HashMap plus sorting its entries is usually cheaper than keeping a tree for the map's whole life.
  • Multiple threads: ConcurrentHashMap, or ConcurrentSkipListMap when you need both ordering and concurrency.
Read in post: Java Collections
Trade-offMidFail-fast, weakly consistent or snapshot iteratorsSingle thread, removing while iterating: iterator.remove() or removeIf on a regular collection is enough. Many threads, mixed reads and writes: ConcurrentHashMap. Iteration isn't a point-in-time snapshot, so a size() or a sum taken during writes is only an estimate. Reads vastly outnumber writes (listener lists, config
Kind Examples Modified during iteration Cost
Fail-fast ArrayList, HashMap, HashSet Throws CME (best effort) Nothing extra
Weakly consistent ConcurrentHashMap, ConcurrentLinkedQueue, ConcurrentSkipListMap Never throws; may or may not reflect changes made after the iterator was created; never returns an element twice More complex concurrent structures
Snapshot (copy-on-write) CopyOnWriteArrayList, CopyOnWriteArraySet Never throws; iterates over a snapshot taken at creation; iterator.remove() throws UnsupportedOperationException Every write copies the whole array: O(n)
  • Single thread, removing while iterating: iterator.remove() or removeIf on a regular collection is enough.
  • Many threads, mixed reads and writes: ConcurrentHashMap. Iteration isn't a point-in-time snapshot, so a size() or a sum taken during writes is only an estimate.
  • Reads vastly outnumber writes (listener lists, configuration): CopyOnWriteArrayList. With frequent writes it burns CPU and produces garbage.
  • "Fail-safe" is the popular name for the last two kinds, but the Javadoc says "weakly consistent" and "snapshot".
Read in post: Java Collections
TILSeniorRemoving the second-to-last element in a for-each doesn't throw ConcurrentModificationExceptionA for-each calls hasNext() before next(), and ArrayList's iterator implements hasNext() as cursor != size. After removing "b", cursor = 2 and size = 2, so the loop ends before next() can check modCount. The element "c" is never visited; remove "a" instead and you do get a CME. The absence of an exception doesn't prove
List<String> l = new ArrayList<>(List.of("a", "b", "c"));
for (String s : l) if (s.equals("b")) l.remove(s);   // no exception, l = [a, c]

A for-each calls hasNext() before next(), and ArrayList's iterator implements hasNext() as cursor != size. After removing "b", cursor = 2 and size = 2, so the loop ends before next() can check modCount. The element "c" is never visited; remove "a" instead and you do get a CME. The absence of an exception doesn't prove the code is correct.

Read in post: Java Collections
InterviewJuniorWhat's the difference between Comparable and Comparator, and when do you use each?

Comparable is the natural ordering inside the class (one per class); Comparator is an external ordering, and you can have many.

Comparable (compareTo) is what String, Integer and LocalDate use. Comparator (compare) works for classes you can't modify. Implement Comparable for an obvious order; use Comparator.comparing(...).thenComparing(...) for orders that depend on the business rule or the screen.

Read in post: Java Collections
InterviewJuniorHow is TreeMap different from HashMap, and when do you pick TreeMap?

HashMap is an O(1) hash table with no order; TreeMap is an O(log n) red-black tree that keeps keys sorted and answers nearest-key and range queries.

HashMap allows one null key. TreeMap compares keys with compareTo/a comparator (natural ordering rejects a null key) and offers NavigableMap queries such as floorEntry, ceilingKey, subMap and headMap. Pick TreeMap when you need sorted keys or "nearest key / keys in a range", for example tiers by spending or events in a time window; otherwise use HashMap.

Read in post: Java Collections
InterviewMidYou add two different objects to a TreeSet, yet size() is 1. Why?

Because a TreeSet detects duplicates with compareTo/the Comparator and never calls equals/hashCode.

If the ordering compares only some fields (say age, then name), two objects with different ids but the same age and name compare as 0, and the second is silently dropped. Fix it with a final tie-breaker (thenComparingInt(Member::id)) so the ordering is consistent with equals.

Read in post: Java Collections
InterviewMidWhat's the difference between fail-fast and fail-safe iterators?

Fail-fast iterators throw ConcurrentModificationException when the collection is changed outside the iterator; "fail-safe" ones don't throw, but that's an informal name for two different kinds.

Fail-fast (ArrayList, HashMap) checks modCount, best effort only. Weakly consistent (ConcurrentHashMap) never throws and may or may not see newer changes. Snapshot (CopyOnWriteArrayList) iterates over a copy, and every write copies the whole array. Choose by read/write ratio and whether multiple threads are involved.

Read in post: Java Collections
InterviewSeniorRemoving the second-to-last element of an ArrayList inside a for-each doesn't throw ConcurrentModificationException. Why?

Because hasNext() returns false before next() gets to check modCount, so the loop stops early and the last element is skipped.

The ArrayList iterator's hasNext() is just cursor != size. Removing the second-to-last element shrinks size to exactly cursor. No exception, but the code is wrong. The lesson: fail-fast is best effort; use iterator.remove() or removeIf.

Read in post: Java Collections
InterviewSeniorWhat happens if you mutate an element that's inside a TreeSet, or a HashMap key?

The structure doesn't know the field changed, so the element "disappears": lookups miss it, removal fails, and no exception is thrown.

  • HashMap/HashSet: the element still sits in the bucket from the old hash, so get/contains compute the new bucket and miss it.
  • TreeSet/TreeMap: the element is in the wrong place in the tree, searches go down the wrong branch, and remove fails too.
  • Result: lost data and a memory leak. The fix is to use only immutable objects (records, String) as keys and set elements; if you must change one, remove it, change it, and add it back.
Read in post: Java Collections
Edge caseJuniorSSL is dead: enable only TLS 1.2 and TLS 1.3The slides say "SSL/TLS", but SSL has been dead for years (SSL 3.0 fell to the POODLE attack). Today you enable only TLS 1.2 and TLS 1.3; "SSL" survives only as a figure of speech.

The slides say "SSL/TLS", but SSL has been dead for years (SSL 3.0 fell to the POODLE attack). Today you enable only TLS 1.2 and TLS 1.3; "SSL" survives only as a figure of speech.

Read in post: The web and HTTP
Edge caseMidIdempotent doesn't mean the response is identicalThe first DELETE /users/34 returns 204, the second may return 404. The server state is the same (user 34 is gone), so it's still idempotent.

The first DELETE /users/34 returns 204, the second may return 404. The server state is the same (user 34 is gone), so it's still idempotent.

Read in post: The web and HTTP
Edge caseJuniorA GET with side effects gets triggered by crawlers, prefetching and cachesGET must not have side effects. Crawlers, browser prefetching and caches all assume GET is safe, so a link like GET /users/34/delete can be "clicked" by a bot and wipe real data.

GET must not have side effects. Crawlers, browser prefetching and caches all assume GET is safe, so a link like GET /users/34/delete can be "clicked" by a bot and wipe real data.

Read in post: The web and HTTP
Edge caseJuniorReturning 200 for every error breaks monitoring, retries and cachingDon't return 200 with {"success": false} for every error. Keep 4xx (the client must fix the request, don't retry) clearly apart from 5xx (may be retried with backoff).

Don't return 200 with {"success": false} for every error. Keep 4xx (the client must fix the request, don't retry) clearly apart from 5xx (may be retried with backoff).

Read in post: The web and HTTP
Edge caseMidAn HTTP client without timeouts can hang threads foreverHttpURLConnection (and SimpleClientHttpRequestFactory, the default factory behind RestTemplate) defaults to a connect timeout and a read timeout of 0, which means wait forever; the JDK HttpClient has no request timeout unless you set one either. When a downstream service hangs, every request calling it holds a Tomcat t

HttpURLConnection (and SimpleClientHttpRequestFactory, the default factory behind RestTemplate) defaults to a connect timeout and a read timeout of 0, which means wait forever; the JDK HttpClient has no request timeout unless you set one either.

When a downstream service hangs, every request calling it holds a Tomcat thread (200 by default); once they run out, the whole service stops answering. Always set a connect timeout (1–2 seconds) and a read timeout that matches each dependency's SLA, retry only idempotent calls (with backoff), and put a circuit breaker in front of flaky dependencies.

Read in post: The web and HTTP
Edge caseMidCORS does not protect your API from arbitrary clientsCORS is enforced by the browser. It protects users from a malicious page reading data with their logged-in session; it does not protect the API, so authentication and authorization still happen on the server. Two common misconfigurations: Access-Control-Allow-Origin: can't be combined with credentials, and "fixing" tha

CORS is enforced by the browser. It protects users from a malicious page reading data with their logged-in session; it does not protect the API, so authentication and authorization still happen on the server.

Two common misconfigurations: Access-Control-Allow-Origin: * can't be combined with credentials, and "fixing" that by reflecting whatever Origin comes in lets any website read the logged-in user's data.

Read in post: The web and HTTP
InterviewJuniorWhat's the difference between HTTP and HTTPS?

HTTPS is HTTP over TLS: encrypted, tamper-evident, and the server is authenticated.

TLS authenticates the server with a CA-signed certificate. Plain HTTP is sent in clear text, so anyone on the path can read or change it. By default HTTP uses port 80 and HTTPS uses 443.

Read in post: The web and HTTP
InterviewJuniorHow do PUT and PATCH differ?

PUT replaces the whole resource and is idempotent; PATCH changes only what you send and isn't guaranteed to be idempotent.

With PUT, any field left out is cleared or reset. Whether a PATCH is idempotent depends on the operation: setting a value is, incrementing isn't.

Read in post: The web and HTTP
InterviewJuniorWhat's the difference between 401 and 403?

401 means not authenticated; 403 means authenticated but not allowed.

401: the token is missing, wrong or expired, and the client should log in again. 403: the server knows who you are but you can't access the resource; logging in again won't help.

Read in post: The web and HTTP
InterviewJuniorHow do 4xx and 5xx differ, and which ones should a client retry?

4xx means the client got it wrong, so the same request fails again; 5xx means the server failed, and 502/503/504 are often transient, so they can be retried.

  • 4xx (bad request, missing authentication, no permission, state conflict): don't retry, except 429 (wait for Retry-After) and 408.
  • 502, 503, 504: retry with exponential backoff, jitter and a cap on attempts. A 500 caused by a bug rarely goes away on retry.
  • Automatic retries are only safe for idempotent methods or requests carrying an Idempotency-Key.
Read in post: The web and HTTP
InterviewJuniorWhat is the difference between a client and a server? Is a "server" the machine or the program?

The client initiates requests, the server runs continuously to wait for and answer them; "server" can mean either the machine or the process.

The machine is physical, a VM or a container; the process is a program listening on a port, like an embedded Tomcat on 8080. Client/server is a role in one conversation: a service is a server to the browser and a client when it calls the database or another service.

Read in post: The web and HTTP
InterviewMidWhat do safe and idempotent mean? Give examples.

Safe means it doesn't change server state (GET, HEAD, OPTIONS); idempotent means once or many times leaves the same final state (all safe methods plus PUT and DELETE).

POST is not idempotent. Responses may differ (a second DELETE returns 404) and the method is still idempotent, because we judge by server state.

Read in post: The web and HTTP
InterviewMidHow can a client retry a "create order" POST without creating duplicates?

Use an Idempotency-Key: the client sends a UUID per operation, and when the server sees the key again it returns the stored result.

The server stores the key and the result in the same transaction that creates the order, with a unique constraint on the key to block concurrent duplicates. Keys expire after a while (say 24 hours).

Read in post: The web and HTTP
InterviewMidWhat does HTTP/2 improve over HTTP/1.1, and what extra problem does HTTP/3 solve?

HTTP/2 multiplexes many streams over one connection and compresses headers; HTTP/3 moves to QUIC so a lost packet doesn't stall every stream.

  • HTTP/2: binary frames and multiplexing, so requests no longer queue behind each other at the HTTP layer, plus HPACK header compression. But it still runs on TCP: one lost packet stalls every stream on the connection (head-of-line blocking at the TCP layer).
  • HTTP/3: QUIC over UDP, where each stream is delivered independently, so a lost packet only delays its own stream. TLS 1.3 is built into QUIC, giving a 1-RTT handshake, 0-RTT on resumption, and connections that survive a network change (Wi-Fi to 4G).
Read in post: The web and HTTP
InterviewMidWhat is CORS? Why does Postman reach the API while the browser shows a CORS error?

CORS is how a server lets other origins read its responses, relaxing the browser's same-origin policy. Postman and curl aren't browsers, so the policy doesn't apply to them.

A script from origin A can read a response from origin B only if B returns an Access-Control-Allow-Origin header that allows A. For non-simple requests (JSON bodies, PUT/PATCH/DELETE, an Authorization header) the browser sends a preflight OPTIONS first. The proper fix is server-side CORS configuration with an explicit list of origins (and enabling CORS in Spring Security so the preflight isn't blocked), not disabling checks on the client. CORS is not a replacement for authentication.

Read in post: The web and HTTP
InterviewSeniorWhat changes for the application when TLS is terminated at the load balancer?

The app receives plain HTTP, so it relies on forwarded headers to know the original request, and the LB-to-app hop is no longer encrypted.

  • Use X-Forwarded-Proto/For/Host (or Forwarded) to learn the original scheme and client IP and to build correct redirects and links; trust those headers only from known proxies.
  • For sensitive data or compliance, re-encrypt or use mTLS in a service mesh.
  • Certificate rotation is centralised at the LB.
Read in post: The web and HTTP
InterviewSeniorA slow third-party API takes your whole service down. Why, and how do you guard against it?

Every request calling the slow dependency holds a thread; without a timeout the thread pool drains and every other endpoint dies too. Guard with timeouts, controlled retries, a circuit breaker and bulkheads.

Tomcat has 200 threads by default; one dependency's failure cascades into the whole system. Guards:

  • Connect and read timeouts on every outbound call.
  • Bounded retries with backoff, only for idempotent operations.
  • A circuit breaker (Resilience4j) to fail fast while the dependency is down.
  • A bulkhead (a dedicated pool or semaphore per dependency) so one dependency can't eat all resources.
  • A fallback or an early 503; per-dependency latency and error-rate metrics so you see the degradation coming.
Read in post: The web and HTTP
Edge caseMidWrapper ==, null unboxing and boxing cost bite in production1. == on wrappers: Integer.valueOf caches -128 to 127. Integer x = 127, y = 127; x == y is true, with 128 it's false. Always use equals. 2. Unboxing null throws NullPointerException: Integer count = map.get("x"); int c = count; blows up if the key is missing. Integer values from JPA or JSON can be null. 3. Cost: Long s
  1. == on wrappers: Integer.valueOf caches -128 to 127. Integer x = 127, y = 127; x == y is true, with 128 it's false. Always use equals.
  2. Unboxing null throws NullPointerException: Integer count = map.get("x"); int c = count; blows up if the key is missing. Integer values from JPA or JSON can be null.
  3. Cost: Long sum = 0L; for (...) sum += i; creates millions of Long objects. In hot loops, use primitives, IntStream, or a primitive-collections library.
Read in post: Object-oriented programming
Edge caseJuniorlist.remove(1) on a List<Integer> removes by index, not by valueAn overloading trap with autoboxing: list.remove(1) removes the element at index 1, while list.remove(Integer.valueOf(1)) removes the value 1.

An overloading trap with autoboxing: list.remove(1) removes the element at index 1, while list.remove(Integer.valueOf(1)) removes the value 1.

Read in post: Object-oriented programming
Edge caseMidnew Integer(...) is deprecated for removal: use Integer.valueOf or autoboxingThe slide (taken from Liang's book) treats Integer x = new Integer(2) as equivalent to Integer x = 2, and int i = new Integer(1) as equivalent to int i = 1. Two corrections: Every wrapper constructor (new Integer(..), new Long(..), new Double(..), new Boolean(..)...) has been @Deprecated since Java 9 and forRemoval = t

The slide (taken from Liang's book) treats Integer x = new Integer(2) as equivalent to Integer x = 2, and int i = new Integer(1) as equivalent to int i = 1. Two corrections:

  • Every wrapper constructor (new Integer(..), new Long(..), new Double(..), new Boolean(..)...) has been @Deprecated since Java 9 and forRemoval = true since Java 16 (JEP 390). New code uses Integer.valueOf(..) or autoboxing, which reuse cached objects for -128 to 127.
  • The two forms aren't equivalent: new Integer(2) == new Integer(2) is false (always a new object), while Integer.valueOf(2) == Integer.valueOf(2) is true (the same cached object). Either way, always compare wrappers with equals.
Read in post: Object-oriented programming
Edge caseJuniorDouble has no parseDouble(String, radix) or valueOf(String, radix)The slide's UML of Integer and Double lists Double.valueOf(String, int radix) and Double.parseDouble(String, int radix). Neither exists in the JDK: radix overloads only exist on Byte, Short, Integer and Long. Double.parseDouble accepts only decimal strings or hex floating-point strings like "0x1p4" (which is 16.0).

The slide's UML of Integer and Double lists Double.valueOf(String, int radix) and Double.parseDouble(String, int radix). Neither exists in the JDK: radix overloads only exist on Byte, Short, Integer and Long. Double.parseDouble accepts only decimal strings or hex floating-point strings like "0x1p4" (which is 16.0).

Read in post: Object-oriented programming
TILSeniorThe Integer cache can be widened with -XX:AutoBoxCacheMaxThe JLS only requires caching -128 to 127. On HotSpot, -XX:AutoBoxCacheMax=<n raises the cache's upper bound for Integer only (Long, Short and Byte stay at -128..127). One more reason never to rely on == for wrappers: the result can change with a JVM flag.

The JLS only requires caching -128 to 127. On HotSpot, -XX:AutoBoxCacheMax=<n> raises the cache's upper bound for Integer only (Long, Short and Byte stay at -128..127). One more reason never to rely on == for wrappers: the result can change with a JVM flag.

Read in post: Object-oriented programming
Edge caseMidBigInteger.remainder keeps the dividend's sign, while mod is never negativeremainder behaves like %: -7 remainder 5 is -2. mod is mathematical modulo, always in [0, m): -7 mod 5 is 3 (like Math.floorMod(-7, 5)). A negative modulus throws ArithmeticException: BigInteger: modulus not positive. When you compute a ring index or a shard number from a value that might be negative, use mod.

remainder behaves like %: -7 remainder 5 is -2. mod is mathematical modulo, always in [0, m): -7 mod 5 is 3 (like Math.floorMod(-7, 5)). A negative modulus throws ArithmeticException: BigInteger: modulus not positive.

When you compute a ring index or a shard number from a value that might be negative, use mod.

Read in post: Object-oriented programming
Edge caseSeniorBigDecimal: double constructor, equals vs compareTo, division without a scaleBuild from a String or use valueOf; never use the double constructor. Every division needs an explicit scale and RoundingMode (or a MathContext). Compare values with compareTo. A consequence: as HashMap/HashSet keys, 2.0 and 2.00 are different keys; normalize with stripTrailingZeros() first.
new BigDecimal(0.1);          // 0.1000000000000000055511151231257827021181583404541015625  (WRONG)
new BigDecimal("0.1");        // 0.1  (correct)
BigDecimal.valueOf(0.1);      // 0.1  (correct: goes through Double.toString)

new BigDecimal("2.0").equals(new BigDecimal("2.00"));          // false: equals compares scale too
new BigDecimal("2.0").compareTo(new BigDecimal("2.00")) == 0;  // true: use compareTo for value equality

BigDecimal.ONE.divide(new BigDecimal("3"));                    // ArithmeticException: non-terminating decimal
BigDecimal.ONE.divide(new BigDecimal("3"), 4, RoundingMode.HALF_UP);   // 0.3333
  • Build from a String or use valueOf; never use the double constructor.
  • Every division needs an explicit scale and RoundingMode (or a MathContext).
  • Compare values with compareTo. A consequence: as HashMap/HashSet keys, 2.0 and 2.00 are different keys; normalize with stripTrailingZeros() first.
Read in post: Object-oriented programming
Trade-offSeniorMoney: HALF_UP vs HALF_EVEN, BigDecimal vs long in the smallest unitRounding follows the business: HALFUP is everyday rounding, HALFEVEN (banker's rounding) reduces cumulative bias when aggregating many values. The database column is something like NUMERIC(19, 4), never FLOAT. BigDecimal is exact but slower and verbose. A long in the smallest unit (cents, đồng) is faster, but you handl
  • Rounding follows the business: HALF_UP is everyday rounding, HALF_EVEN (banker's rounding) reduces cumulative bias when aggregating many values. The database column is something like NUMERIC(19, 4), never FLOAT.
  • BigDecimal is exact but slower and verbose. A long in the smallest unit (cents, đồng) is faster, but you handle rounding and currency yourself.
Read in post: Object-oriented programming
Trade-offMidString vs StringBuilder vs StringBufferin a single expression is fine; the compiler already optimizes it (since Java 9 via invokedynamic and StringConcatFactory). Concatenating in a loop creates a new String and copies the old content on every iteration, which is O(n²):
String StringBuilder StringBuffer
Mutable No Yes Yes
Thread-safe Yes (immutable) No Yes (synchronized methods)
Use it for Almost everything Building strings in loops Legacy code; rarely needed

+ in a single expression is fine; the compiler already optimizes it (since Java 9 via invokedynamic and StringConcatFactory). Concatenating in a loop creates a new String and copies the old content on every iteration, which is O(n²):

String csv = "";
for (String id : ids) csv += id + ",";         // O(n²): n intermediate strings

StringBuilder sb = new StringBuilder(ids.size() * 8);
for (String id : ids) sb.append(id).append(','); // O(n)

String joined = String.join(",", ids);           // the cleanest option for this case
Read in post: Object-oriented programming
TILMidCompact strings (Java 9) and a heap-resident string poolSince Java 9, compact strings store Latin-1-only strings with one byte per character instead of two, which noticeably shrinks the heap. The string pool lives on the heap (since Java 7), so it's garbage-collected like everything else. Methods worth knowing: isBlank, strip, repeat, lines (Java 11), text blocks """ (Java

Since Java 9, compact strings store Latin-1-only strings with one byte per character instead of two, which noticeably shrinks the heap. The string pool lives on the heap (since Java 7), so it's garbage-collected like everything else. Methods worth knowing: isBlank, strip, repeat, lines (Java 11), text blocks """ (Java 15), and formatted (Java 15).

Read in post: Object-oriented programming
InterviewJuniorWhat is a wrapper class? What is autoboxing?

A wrapper is a class that wraps a primitive (Integer wraps int...); autoboxing/unboxing is the compiler converting between the two automatically.

Wrappers work where an object is required, such as generics or null values. Behind the scenes, autoboxing calls valueOf() and unboxing calls intValue().

Read in post: Object-oriented programming
InterviewJuniorWhy is String immutable?

So strings can be shared safely in the string pool, so sensitive parameters can't be tampered with, for thread safety, and so the hash can be cached.

Sensitive parameters are things like paths, URLs and class names. The cached hash makes strings great HashMap keys.

Read in post: Object-oriented programming
InterviewMidString vs StringBuilder vs StringBuffer: when do you use each?

String is immutable; StringBuilder is mutable, not thread-safe, and fast; StringBuffer is mutable and thread-safe via synchronized, so it's slower and rarely needed.

Use StringBuilder (or String.join, Collectors.joining) when building strings in loops, and plain + for one-off expressions, which the compiler already optimizes.

Read in post: Object-oriented programming
InterviewMidWhat does Integer a = 1000, b = 1000; a == b return? What about int c = mapOfInteger.get("missing");?

The first is false; the second throws a NullPointerException.

1000 is outside the -128..127 cache, so a and b are different objects. The second line unboxes null.

Read in post: Object-oriented programming
InterviewMidWhy not use double for money, and how do you use BigDecimal correctly?

double is binary and can't represent 0.1 exactly, so errors accumulate; BigDecimal is exact if you use it correctly.

  • Build from a String or valueOf.
  • Give every division an explicit scale and RoundingMode.
  • Compare with compareTo (because equals also compares scale).
  • Agree on rounding rules with the business; use NUMERIC/DECIMAL columns in the database.
Read in post: Object-oriented programming
InterviewMidHow do new Integer(5) and Integer.valueOf(5) differ? Why were the wrapper constructors deprecated?

new Integer(5) always creates a new object; Integer.valueOf(5) returns a cached instance (-128 to 127), which saves memory and makes == between two calls true.

The constructors were deprecated in Java 9 and marked for removal in Java 16. They force a fresh object every time, which defeats caching and blocks turning wrappers into value classes (Project Valhalla), where object identity no longer means anything. Use valueOf, parseInt or autoboxing.

Read in post: Object-oriented programming
InterviewMidHow do BigInteger.remainder and BigInteger.mod differ?

remainder takes the sign of the dividend (like %); mod is always non-negative, in [0, m).

-7 remainder 5 = -2, -7 mod 5 = 3. mod throws ArithmeticException if the modulus isn't positive. When you need both quotient and remainder, use divideAndRemainder, which divides only once.

Read in post: Object-oriented programming
InterviewSeniorWhat goes wrong when you use BigDecimal as a HashMap or HashSet key?

equals/hashCode include the scale, so 2.0 and 2.00 are different keys, yet compareTo treats them as equal.

A TreeMap uses compareTo and merges them; a HashMap doesn't. Normalize with stripTrailingZeros() or a fixed setScale before using values as keys, or use a TreeMap.

Read in post: Object-oriented programming
InterviewSeniorYou're building a CSV export with several million rows. What do you watch out for in terms of performance and memory?

Don't build the whole file in memory: stream rows one line at a time to a BufferedWriter or straight into the response output stream.

  • No += in loops (O(n²)). Even a single StringBuilder for the whole file can hold hundreds of MB on the heap.
  • Pre-size each row's StringBuilder.
  • Escape CSV special characters and specify UTF-8.
  • Over HTTP, use a streaming response so you neither pin memory nor hit timeouts.
Read in post: Object-oriented programming
Edge caseMidOne DELETE of millions of rows hurts the whole databaseA single DELETE that removes millions of rows (e.g. purging old INACTIVE rows in one go) will: Hold one very long transaction: locking those rows and blocking anything else that touches them. Generate a huge amount of WAL/binlog (the change log the DB writes for recovery and ships to replicas), causing replication lag

A single DELETE that removes millions of rows (e.g. purging old INACTIVE rows in one go) will:

  • Hold one very long transaction: locking those rows and blocking anything else that touches them.
  • Generate a huge amount of WAL/binlog (the change log the DB writes for recovery and ships to replicas), causing replication lag on replicas and possibly filling the disk.
  • In PostgreSQL, leave millions of dead tuples (dead row versions) for VACUUM; in MySQL InnoDB, bloat the undo log.
  • Roll back everything if it fails halfway, wasting all that time.

The fix: delete in small batches, each in its own short transaction.

Read in post: Cleanup cron jobs
Trade-offMidBacking up before a hard delete: archive table, object storage or DB backupsA hard delete can't be undone. Your options:

A hard delete can't be undone. Your options:

Approach Pros Cons
Archive table in the same DB (archive and delete in one transaction) Atomic with the delete, easy to restore with SQL Still uses space in the primary DB
Export to object storage (S3, GCS) as Parquet/CSV/JSON first, then delete Cheap, off the primary DB Not atomic: confirm the file is fully written and row counts match before deleting
Rely on DB backups/PITR (restore to a point in time) No code Restoring a handful of rows from a full backup is painful
Read in post: Cleanup cron jobs
Trade-offSeniorCleaning up old data: DROP PARTITION or batched deletesBatched deletes (one short transaction per batch) work on any table but still cost WAL, locks and dead tuples. If the table is partitioned by month (PARTITION BY RANGE (createdat)), cleaning up old data is just DETACH/DROP PARTITION: nearly instant, no dead tuples. Great for logs, events and history; less so for busine

Batched deletes (one short transaction per batch) work on any table but still cost WAL, locks and dead tuples. If the table is partitioned by month (PARTITION BY RANGE (created_at)), cleaning up old data is just DETACH/DROP PARTITION: nearly instant, no dead tuples. Great for logs, events and history; less so for business data whose INACTIVE status isn't tied to when the row was created.

Read in post: Cleanup cron jobs
Trade-offMidA once-a-year job or a nightly job with a data-driven conditionA warning about "once a year" (e.g. a job that purges INACTIVE rows at 00:00 on June 1): @Scheduled doesn't catch up on missed runs, so if the app is mid-deploy on the night of May 31, you wait another 12 months. I'd suggest running nightly (0 0 2 ) with the same "INACTIVE for over 6 months" condition: small deletes ea

A warning about "once a year" (e.g. a job that purges INACTIVE rows at 00 on June 1): @Scheduled doesn't catch up on missed runs, so if the app is mid-deploy on the night of May 31, you wait another 12 months.

I'd suggest running nightly (0 0 2 * * *) with the same "INACTIVE for over 6 months" condition: small deletes each time, steady load, and a missed night is caught up the next. If the business really needs June 1, that's a question to clarify with whoever wrote the requirement (why June 1? is there a regulation behind it?).

Read in post: Cleanup cron jobs
InterviewJuniorWhat's the difference between a soft delete and a hard delete? Why do you still need a hard-delete job?

A soft delete only marks the row; a hard delete removes it. With soft deletes alone the table grows forever, so a periodic job archives and then hard deletes rows past the retention period.

  • Soft delete (status = 'INACTIVE' or deleted_at): the data stays in the table, so you can restore it, keep history, and foreign keys don't break.
  • The cost of never cleaning up: bigger indexes, slower queries and backups, and possibly breaking personal-data regulations.
Read in post: Cleanup cron jobs
InterviewMidWhy should archiving and deleting happen in the same transaction?

So you never end up half done: either both the archive and the delete happen, or neither does.

  • Archive first, delete in a separate transaction: a job that dies in between leaves rows in both tables (and a rerun archives them twice).
  • Delete first and the archive fails: the data is gone.
  • One transaction: for example a single statement with a data-modifying CTE in PostgreSQL.
  • A backup to object storage can't be atomic: confirm the file is written and the row counts match before deleting.
Read in post: Cleanup cron jobs
InterviewMidHow does FOR UPDATE SKIP LOCKED help a batched delete job?

FOR UPDATE locks the selected rows so nobody changes them between archiving and deleting; SKIP LOCKED skips rows another transaction has locked instead of waiting for them.

  • The job never gets stuck behind a user's transaction.
  • If two runs ever overlap, each one takes a different set of rows instead of fighting over the same ones.
  • Available in PostgreSQL 9.5+ and MySQL 8.0+.
Read in post: Cleanup cron jobs
InterviewMidHow do you pick the batch size for a delete job?

Start around 500–5,000 rows depending on row width and the number of indexes, then measure and tune.

  • Goal: each batch commits in well under a few seconds, holds locks briefly, and leaves replication lag and WAL/binlog volume flat.
  • Too small: the total runtime balloons from per-transaction overhead. Too large: you're back to the problems of one giant DELETE.
  • Add a short pause between batches and a cap on the total runtime.
Read in post: Cleanup cron jobs
InterviewSeniorHow would you delete 50 million old rows from a live production table?

Not with a single DELETE: delete in small batches, each in a short transaction, archiving in the same transaction before deleting.

  • Index the filter.
  • Pause between batches and watch replication lag.
  • Run off-peak with a time budget.
  • Long term, partition by time so cleanup becomes DROP PARTITION.
Read in post: Cleanup cron jobs
InterviewSeniorHow do you find out that a cron job has silently stopped running?

Use a dead man's switch: alert when the last successful run is too old. Error logs and error alerts aren't enough, because a job that doesn't run produces no errors.

  • Every successful run records a job_last_success_timestamp metric (or pings a heartbeat service).
  • Alert when that value is older than the schedule plus a margin (25 hours for a daily job).
  • Add metrics for rows processed and run time so you also notice a job that runs but does nothing.
Read in post: Cleanup cron jobs
Edge caseMidA custom message field in an exception makes getMessage() return nullA pattern you'll see in tutorials: declaring private String message; inside the exception class and assigning to it. That field shadows Throwable's own detailMessage. Unless you also override getMessage(), it returns null and your logs have no message. Call super(message) instead.

A pattern you'll see in tutorials: declaring private String message; inside the exception class and assigning to it. That field shadows Throwable's own detailMessage. Unless you also override getMessage(), it returns null and your logs have no message. Call super(message) instead.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Trade-offMidShould custom exceptions be checked or uncheckedMake them unchecked. Business errors are usually handled in one central place (a global handler), and the layers in between do nothing with them. Checked exceptions force every layer to declare throws, adding noise with no value.

Make them unchecked. Business errors are usually handled in one central place (a global handler), and the layers in between do nothing with them. Checked exceptions force every layer to declare throws, adding noise with no value.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Edge caseMid@Transactional still commits when the method throws a checked exceptionBy default, Spring only rolls back on RuntimeException or Error. If a @Transactional method throws a checked exception, the transaction still commits. Use unchecked exceptions, or declare @Transactional(rollbackFor = Exception.class). This comes up in interviews all the time.

By default, Spring only rolls back on RuntimeException or Error. If a @Transactional method throws a checked exception, the transaction still commits. Use unchecked exceptions, or declare @Transactional(rollbackFor = Exception.class). This comes up in interviews all the time.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Edge caseMidA catch-all @ExceptionHandler(Exception.class) turns 403 into 500@PreAuthorize throws AccessDeniedException inside the controller call, so the Exception net swallows it and returns 500. Add dedicated handlers that re-throw (throw ex) AccessDeniedException and AuthenticationException so Spring Security answers 403/401. Conversely, 401/403 raised in the filter chain (missing token, UR

@PreAuthorize throws AccessDeniedException inside the controller call, so the Exception net swallows it and returns 500. Add dedicated handlers that re-throw (throw ex) AccessDeniedException and AuthenticationException so Spring Security answers 403/401. Conversely, 401/403 raised in the filter chain (missing token, URL rules) never reach @ControllerAdvice at all. The lab hit exactly this in common Spring Boot errors.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Edge caseJuniorMost Bean Validation constraints treat null as validMost constraints (@Size, @Email, @Min, @Pattern...) treat null as valid. @Size(min = 10) String password happily accepts null. Combine with @NotNull/@NotBlank when the field is required.

Most constraints (@Size, @Email, @Min, @Pattern...) treat null as valid. @Size(min = 10) String password happily accepts null. Combine with @NotNull/@NotBlank when the field is required.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Trade-offMidBindingResult in the controller vs a global exception handler for validation errorsBindingResult: per-endpoint customization, but repeated in every endpoint, the same problem as try-catch everywhere. Global handler: lean controllers, one consistent error format. This should be your default.

BindingResult: per-endpoint customization, but repeated in every endpoint, the same problem as try-catch everywhere.

Global handler: lean controllers, one consistent error format. This should be your default.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Edge caseMidDeclaring @ExceptionHandler(MethodArgumentNotValidException) while extending ResponseEntityExceptionHandler fails as ambiguousThe course material says to catch BindException. More precisely, @Valid @RequestBody makes Spring throw MethodArgumentNotValidException; since Spring 5.3 it extends BindException, so a BindException handler still catches it. But if you extend ResponseEntityExceptionHandler, the base class already handles MethodArgument

The course material says to catch BindException. More precisely, @Valid @RequestBody makes Spring throw MethodArgumentNotValidException; since Spring 5.3 it extends BindException, so a BindException handler still catches it.

But if you extend ResponseEntityExceptionHandler, the base class already handles MethodArgumentNotValidException. Declaring another @ExceptionHandler for the same type fails at startup with "Ambiguous @ExceptionHandler". Override handleMethodArgumentNotValid instead.

Read in post: Custom exceptions and centralized error handling in Spring Boot
Edge caseSeniorChecking "does it exist?" before inserting is a race conditionCheck-then-act is a race condition: two simultaneous requests both see existsByUsername = false and both insert. You need a UNIQUE constraint in the database and must map the violation (DataIntegrityViolationException) to 409. The exists check is only there to fail early with a nice message.

Check-then-act is a race condition: two simultaneous requests both see existsByUsername = false and both insert. You need a UNIQUE constraint in the database and must map the violation (DataIntegrityViolationException) to 409. The exists check is only there to fail early with a nice message.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewJuniorWhy use @RestControllerAdvice instead of try-catch in every controller?

To handle errors in one place and return one consistent format across the whole API.

Try-catch in every endpoint duplicates code, everyone returns a slightly different format, logging gets forgotten, and internal messages leak. With @RestControllerAdvice, controllers and services just throw; one class decides which exception maps to which status, what the body looks like and at what level it's logged.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewMidA @Transactional method throws a checked exception. Does it roll back?

No. By default it only rolls back on RuntimeException and Error.

Use rollbackFor = Exception.class or switch to unchecked exceptions.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewMidHow does @ControllerAdvice work, and which handler wins when several match?

ExceptionHandlerExceptionResolver looks in the controller first, then in advice classes ordered by @Order; within a class, the closest exception type wins.

The exception escapes the controller to DispatcherServlet, and that resolver takes over. "Closest" means in the inheritance hierarchy, not in declaration order.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewMidWhy shouldn't you return stack traces or system exception messages to clients?

They leak internals to attackers and mean nothing to users.

What leaks: libraries, versions, DB structure, paths. Return a safe message, an error code and a traceId; keep the details in the logs.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewMidWhat's the difference between @Valid and @Validated?

@Valid is the standard Jakarta annotation that triggers validation and cascades into nested objects; Spring's @Validated adds validation groups and method validation.

@Validated on a class enables method validation through an AOP proxy: needed for services, and for simple controller parameters before Spring 6.1.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewMidDoes an exception thrown in a servlet filter or Spring Security reach @ControllerAdvice?

No. Filters run before the DispatcherServlet, and @ControllerAdvice only handles exceptions from handlers the DispatcherServlet invokes.

  • Authentication and authorization failures: an AuthenticationEntryPoint and an AccessDeniedHandler.
  • Other filter errors: the filter writes the response itself, or it falls through to the /error page (BasicErrorController).
  • Whichever path it takes, return the same ProblemDetail format as the rest of the API.
Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewSeniorWhen would you choose a checked exception in modern code?

When the caller genuinely can and should recover, and forgetting to handle it is dangerous, e.g. in low-level libraries (I/O).

In Spring applications, business errors are usually unchecked and handled centrally, because checked exceptions clutter every layer, don't work through lambdas/streams and don't trigger rollback by default.

Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewSeniorHow would you design error responses for a system with many services?

One shared format (ProblemDetail, RFC 9457) for every service and every error path, with a stable error code and a traceId.

  • Members: type, title, status, detail, plus code for clients, traceId for distributed log lookup and errors for field-level problems.
  • Correct HTTP statuses. Filter and security errors use the same format.
  • When calling other services, map their errors to your own instead of passing them through verbatim.
Read in post: Custom exceptions and centralized error handling in Spring Boot
InterviewSeniorWhat's wrong with calling existsByUsername and then inserting?

It's a check-then-act race: two concurrent requests can both pass the check.

You need a UNIQUE constraint in the database and should catch DataIntegrityViolationException to return 409. The upfront check is only for failing early with a clear message.

Read in post: Custom exceptions and centralized error handling in Spring Boot