BayLearnBayAreaLa8s

BayLearn Weekend Interview Sprints

Java Backend Weekend Interview Sprint

Turn Java Knowledge Into Strong Backend Interview Answers.

Practice Core Java, Spring Boot, APIs, transactions, concurrency, JVM reasoning, debugging, and production scenarios.

  • 4-Hour Live 1:1
  • Core Java + Spring Boot
  • Production Scenarios
  • Coding Practice
  • Mock Interview + Feedback

Not sure if this is the right Sprint? Start with the assessment.

Refund terms are drafted and are not a current offer. Refund policy

Live 1:1 is $349. Introductory live 1:1 is $299 — a configured price, not a countdown.

Who this is for

  • Java Developer
  • Backend Engineer
  • Senior Software Engineer
  • Tech Lead

Best fit: You write Java in production and want sharper answers on Spring, transactions, concurrency, and system behavior.

Not ideal: You are starting Java from a tutorial.

What You Leave With

  • Interview Readiness Score
  • Top Strengths and Gaps
  • Reusable Interview Framework
  • Real Scenario Practice
  • Mock Interview Score
  • Personalized Feedback
  • Question Bank
  • 7-Day Preparation Plan

Preview the 7-day plan

Four-hour agenda

  1. Hour 1

    Core concepts and interview patterns

  2. Hour 2

    Architecture / coding scenarios

  3. Hour 3

    Hands-on interview challenges

  4. Hour 4

    Mock interview and feedback

Sample interview questions

  • How do you diagnose connection-pool exhaustion in a Spring Boot service?
  • When is @Transactional the wrong default?
  • How would you explain concurrent modification of a shared cache?
  • Walk through debugging a production 500 under load.

Can you explain these confidently?

Meet Your Interview Coach

Himanshu Bhadra

Enterprise Architect | Cloud | AI | Distributed Systems | Technical Leadership

Learn by designing, building and explaining.

Availability

Private 1:1 · Book on request

Private 1:1 sessions are scheduled after you book. No public cohort dates are listed yet.

Formats: Group Sprint and Private 1:1 Sprint when scheduled.

Book a Free 15-Minute Interview Strategy Call

FAQ

Can I master the topic in four hours?
No. The Sprint is focused interview preparation for people who already have relevant fundamentals or experience.
What happens in the four hours?
Targeted review, scenario practice, hands-on or architecture exercises, and a mock interview with feedback.
Is it live 1:1?
For the premium format, yes. Other delivery modes may be offered separately.
Can I share my job description?
Yes, so preparation can be better aligned to the target role.
Do you guarantee I will pass?
No. BayLearn improves preparation and readiness but does not guarantee hiring outcomes.
What if my interview is next week?
That is the primary use case for the Weekend Interview Sprint.
What if I need more depth?
Use a BayLearn Professional Program for deeper 8–16 week training.
What is the refund policy?
Refund terms are a draft and are not a current offer. They depend on the format you buy. Read the draft at /refund-policy/ before you enroll or book.

Need more than a weekend?

Professional Programs are 8–16 week paths with labs and capstones. Use a Sprint to get interview-ready, then a program if you need deeper mastery.

Explore Professional Programs

Curriculum

Short lessons in interview order. Lab 501 is the Order API — download the zip, read the source here, then run Maven on your machine. BayLearn does not execute candidate code.

·

You will

  • See the full lesson path before you book
  • Know this is a Java/Spring interview sprint, not a textbook

Course overview5 min

Course overview

Java + Spring Boot Backend Interview Sprint

Write the code, build the service, then explain the trade-off.

A 4-hour BayLearn Interview Sprint. Java 21 and Maven. You will review high-value Java and Spring Boot interview concepts, build a production-style Order API, solve coding problems, answer architecture questions, and complete a realistic mock interview.

This is interview practice, not a short Java textbook. Interviewers fail candidates who recite Spring annotations but cannot discuss idempotency, N+1, or a broken equals/hashCode contract.

Promise

Write a real answer, build a service that looks like production, and explain the trade-offs out loud. You leave with a readiness report and a 7-day plan. The score measures rehearsal against the BayLearn rubric. It does not predict a hiring outcome.

Journey

text

ASSESS → CORE JAVA → COLLECTIONS / STREAMS / CONCURRENCY / JVM
  → SPRING BOOT + REST + JPA → PRODUCTION MICROSERVICES
  → ORDER API LAB → MOCK INTERVIEW → FEEDBACK + 7-DAY PLAN

What interviews actually test

Can you write code, explain it, reason about production behavior, and defend design choices? A typical loop looks like this:

  1. Implement POST /orders so a retry does not create two payments.
  2. Explain why you chose constructor injection and a service layer.
  3. Find the N+1 query when listing orders with line items.
  4. Discuss what happens when inventory is reserved and payment later fails.

If you cannot walk through those four, knowing the annotations is not enough.

The four-hour agenda

ModuleTimeTopic
015 minReadiness Assessment
135 minCore Java Interview Essentials
245 minCollections, Streams, Concurrency & JVM
345 minSpring Boot + REST APIs
435 minProduction Backend & Microservices
535 minLive Coding + Order API Lab
645–60 minMock Interview
710 minFeedback & Practice Plan

Who this is for

Java Developer, Backend Engineer, SWE / SWE II, Senior Backend, Tech Lead, Lead Backend, Staff Engineer, and Solutions Architects who still get a coding-plus-design loop. Tracks: ENGINEER, SENIOR_ENGINEER, LEAD_STAFF.

How to study

Say answers out loud. Ten questions spoken beat fifty skims. After each lesson, pick one order, payment, or inventory example and teach the decision as if a staff engineer is sitting across from you.

Open the course overview next, then Module 0.

Start here

Start here

Course overview — Java + Spring Boot Backend Interview Sprint

Write the code, build the service, then explain the trade-off.

In one sentence: In four hours you practice the Java and Spring Boot answers interviewers actually ask, then you build an Order API, defend it in a mock, and leave with a 7-day plan.

Why this matters

Backend interviews are not “list the Spring annotations.” They are: write a correct method, keep money and inventory consistent, and explain what breaks under retry, concurrency, and load.

People fail this loop in three predictable ways:

  1. They recite inheritance when the interviewer wanted composition.
  2. They implement equals without hashCode, then cannot explain why an order ID “disappears” from a HashMap.
  3. They ship POST /orders without an idempotency key, then cannot talk about double charges.

This sprint trains the spoken answer and the written code together.

What you will do

  1. Take a 20-question readiness assessment and see ten skill scores
  2. Review Core Java the way interviewers probe it: OOP, types, generics, PECS
  3. Make collection, stream, concurrency, and JVM decisions on order and payment examples
  4. Design REST + JPA the way a Spring Boot service is actually reviewed
  5. Walk production patterns: messaging, resilience, observability
  6. Build the Order API lab locally with Maven (./mvnw test) — BayLearn does not execute your code
  7. Practice from a 165+ question bank and 20 coding challenges
  8. Run a scored 45–60 minute mock (ENGINEER / SENIOR / LEAD tracks)
  9. Leave with a weighted report and a 7-day plan

The lessons

Work them in order. Mark a lesson complete when you can teach the decision, not when you have scrolled.

Start here — this overview.

Module 0 — How the assessment works · Readiness

Module 1 — OOP and composition · Interfaces, equals, immutability · Generics, exceptions, modern Java

Module 2 — Collections and HashMap · Streams · Concurrency · JVM

Module 3 — Spring fundamentals · REST, validation, exceptions · JPA, transactions, testing

Module 4 — Microservices and messaging · Resilience and idempotency · Observability and performance

Module 5 — Live coding + Order API lab

Module 6 — Mock interview process

Module 7 — Feedback and 7-day plan

Who this is for

Engineers with roughly 1–12+ years who interview for Java backend roles. Full-stack candidates with a Java service on the resume belong here. If you have never written a Spring controller, this sprint will feel compressed — take the assessment first and use the weak-skill list.

How to study

  • Write the method or sketch the class. Do not only nod at the sample.
  • Connect the idea to OrderService, payments, or inventory.
  • Say it out loud for 60–90 seconds, then one follow-up you expect.

Downloads live in downloads/. The player loads the same lesson text from course-ui/content/.

What this is not

Not an Oracle certification dump. Not a Spring Boot getting-started tutorial. Not a hiring prediction. The certificate is a BayLearn course-completion certificate, not an industry certification.

You will

  • Answer 20 scenario questions
  • Show weak categories to the instructor before the live session

How the assessment works5 min

How the assessment works

Module 0 — Readiness Assessment

Duration: 15 minutes · Kind: assessment

The assessment is not a gate and not a hiring prediction. It is a map. Twenty questions, ten skill scores, one band. Your instructor sees the weak categories before a live session so the four hours go to the gaps that will actually hurt Monday’s loop.

What it measures

SkillWhat a miss usually means in an interview
Core JavaYou lecture OOP and then subclass OrderService to add logging
Types / equalsAn OrderId key “vanishes” from a HashMap
GenericsYou cannot say PECS when the payment list is List<? extends Money>
CollectionsYou pick LinkedList for random access on line items
StreamsYou mutate a shared list inside forEach and call it functional
ConcurrencyYou cannot name the race on inventory decrement
JVMYou treat GC as “the JVM is slow” with no generation story
SpringField injection, circular deps, “the container just works”
REST / JPAEntity leaked to JSON, N+1 on order + lines
ProductionRetry without idempotency; double charge

How to take it

Answer from current instinct. Do not open tabs. A padded 95% hides the module you should drill. When you finish, write down the two lowest bars before you open Module 1.

Bands (rehearsal only)

  • Foundation — rebuild Core Java and one Spring path before the mock.
  • Interview ready — you can sit a mid-level loop; drill spoken follow-ups.
  • Strong — use the lab and mock to practice staff-style trade-offs, not definitions.

INTERVIEW TIP: After the score, pick one production sentence you cannot say yet: “POST /orders is idempotent because…” That sentence is what Module 4 is for.

Open how the assessment works, then the readiness lesson.

Readiness Assessment15 min

Readiness Assessment

Module 0 — Readiness Assessment

Duration: 15 minutes · Kind: assessment

The assessment is not a gate and not a hiring prediction. It is a map. Twenty questions, ten skill scores, one band. Your instructor sees the weak categories before a live session so the four hours go to the gaps that will actually hurt Monday’s loop.

What it measures

SkillWhat a miss usually means in an interview
Core JavaYou lecture OOP and then subclass OrderService to add logging
Types / equalsAn OrderId key “vanishes” from a HashMap
GenericsYou cannot say PECS when the payment list is List<? extends Money>
CollectionsYou pick LinkedList for random access on line items
StreamsYou mutate a shared list inside forEach and call it functional
ConcurrencyYou cannot name the race on inventory decrement
JVMYou treat GC as “the JVM is slow” with no generation story
SpringField injection, circular deps, “the container just works”
REST / JPAEntity leaked to JSON, N+1 on order + lines
ProductionRetry without idempotency; double charge

How to take it

Answer from current instinct. Do not open tabs. A padded 95% hides the module you should drill. When you finish, write down the two lowest bars before you open Module 1.

Bands (rehearsal only)

  • Foundation — rebuild Core Java and one Spring path before the mock.
  • Interview ready — you can sit a mid-level loop; drill spoken follow-ups.
  • Strong — use the lab and mock to practice staff-style trade-offs, not definitions.

INTERVIEW TIP: After the score, pick one production sentence you cannot say yet: “POST /orders is idempotent because…” That sentence is what Module 4 is for.

Open how the assessment works, then the readiness lesson.

20 scenario questions. Each card is tagged with the skill it scores. Open a card to read the prompt and the four choices.

  1. The lookup always succeeds because HashMap uses equals() first and only falls back to hashCode().
  2. The lookup can fail: HashMap places and finds keys by hash bucket, so unequal hashCodes send equal objects to different buckets.
  3. HashMap refuses to insert the key and throws IllegalArgumentException because the contract is broken.
  4. Java 21 HashMap automatically derives hashCode() from equals(), so the lookup succeeds.

Scored take: enroll, open Learn, then this same lesson. One question at a time. After 15 you see your band and eight skill scores.

You will

  • Prefer composition when inheritance leaks a contract
  • Defend an immutable value object

OOP and composition12 min

OOP and composition

OOP and composition

In one sentence: Reuse behavior by delegating to a collaborator; inherit only when the subtype can honor the parent’s full contract for its whole life.

Why interviewers start here

They are not grading whether you can list encapsulation, abstraction, inheritance, and polymorphism. They are grading whether you will subclass OrderService to add retries, or compose a PaymentClient you can fake in a test.

Inheritance publishes the parent’s API and couples you to its evolution. Composition keeps the reused type as an implementation detail. In production Java, most reuse is interfaces plus composition.

See it

Composition vs inheritance on an order service Composition vs inheritance on an order service Compose ports you can fake. Inherit only when the subtype can honor the full parent contract for life. Do this — compose and decorate OrderService checkout()cancel()composition root PaymentGateway charge(cmd)interface / port OrderRepository save / findinterface / port RetryingGateway implements PaymentGatewaywraps StripeGatewayadds timeout + 3 retries has-a has-a decorates Usually wrong ! ExpressCheckoutextends OrderService Inherits cancel(), refund(),every protected field.Cannot honor the contract. Fragile base class Parent adds closeDay().Child cannot support it.Callers of OrderServiceare no longer safe. has-a decorator Liskov trap
Compose PaymentGateway and OrderRepository. Do not subclass OrderService to add retry.

Read the diagram, then say: OrderService *has* a PaymentGateway. A RetryingGateway *decorates* that port. ExpressCheckoutService extends OrderService is the trap — the child inherits every method, including ones it cannot honor.

Code It

A payment retry does not need a new OrderService subtype.

java

public interface PaymentGateway {
    PaymentResult charge(ChargeCommand command);
}

public final class OrderService {
    private final PaymentGateway payments;
    private final OrderRepository orders;

    public OrderService(PaymentGateway payments, OrderRepository orders) {
        this.payments = payments;
        this.orders = orders;
    }

    public OrderId checkout(CheckoutCommand command) {
        PaymentResult result = payments.charge(command.toCharge());
        return orders.save(Order.accepted(command, result)).id();
    }
}

Add logging, metrics, or retry by wrapping PaymentGateway — decorator / strategy — not by extending OrderService and overriding checkout. The service stays a composition root. The gateway stays substitutable.

Build It

On an order platform you typically have:

TypeRelationshipWhy
Order has List<OrderLine>compositionLines do not make sense without the order
OrderService has PaymentGatewaycompositionYou will swap Stripe vs sandbox
PrepaidOrder extends Orderinheritance, usually wrongPrepaid still must honor every Order method
ExpressCheckoutService extends OrderServiceinheritance, usually wrongYou wanted a different collaboration, not an is-a

The fragile base class problem shows up the day someone adds a cancel() on the parent that the child cannot honor. Liskov substitution is the interview name: every caller of Order must be safe with the subtype. Stack extends Vector is the classic library caution — you inherited a contract you did not want.

Prefer inheritance when you are truly specializing a type you own and the subtype remains substitutable (a sealed hierarchy of payment outcomes: Captured, Declined, Pending). That is a closed model, not a reuse hack.

Explain It

“I compose PaymentGateway so I can swap implementations and test OrderService with a fake. Inheritance would leak OrderService internals and break when the parent grows a method the child cannot support. I only inherit when the subtype is an is-a and stays substitutable.”

Say what you give up: more types to name, versus a hierarchy nobody can change safely.

Encapsulation is invariants, not getters

private fields plus public setters that accept any int is not encapsulation. An Order that can be set to status=PAID without a payment reference has a broken invariant. Put state changes behind methods (markPaid(PaymentId)), not property bags.

Polymorphism is how callers depend on PaymentGateway and receive Stripe or a stub. Overloading is compile-time and is not runtime polymorphism — if they hand you print(Object) vs print(String) and pass an Object holding a string, the Object overload wins.

Whiteboard in 60 seconds

  1. Draw OrderService with two arrows out: PaymentGateway, OrderRepository.
  2. Wrap the gateway with RetryingGateway / MetricsGateway — still the same interface.
  3. Cross out extends OrderService. Write “Liskov: can a caller cancel()?”
  4. Say what you give up: more types vs a hierarchy nobody can change.

That sketch covers the OOP interview for a backend role.

Interview questions

When should you prefer composition over inheritance?

When you need reuse or extra behavior without publishing the parent’s contract. Say Liskov, fragile base class, and a concrete backend example.

What goes wrong if you inherit to share utilities?

Utility inheritance couples callers to methods they should never see. Use a static helper or a dedicated MoneyMath type.

How do sealed types change this?

Sealed hierarchies make inheritance safer when the set of subtypes is closed (permits Captured, Declined). They do not make inheritance the default reuse tool.

Follow-up they love: “Refactor a three-level AbstractOrderService into composition.” Answer: extract policies (Pricing, Tax, Payment) as interfaces; the service delegates.

COMMON MISTAKE: “Composition is always better.” Staff candidates name the case for inheritance (closed is-a, shared protected skeleton you control) and then still pick composition for OrderService.

INTERVIEW TIP: If they draw animals, steer back: “On our checkout service I would…” Interviewers remember the order example.

Interfaces, equals, immutability12 min

Interfaces, equals, immutability

Interfaces, equals, immutability

In one sentence: Depend on contracts, keep identity consistent for hash maps, and never mutate a value you used as a key.

Interface vs abstract class (modern Java)

An abstract class can hold state, constructors, and a partial implementation; a type can extend only one. An interface is a contract: abstract methods, defaults, static methods, private helpers (Java 9+). It cannot hold instance fields except constants.

Use an abstract class when you need a shared skeleton and protected state you own. Use interfaces when you want multiple capabilities (Comparable, AutoCloseable, PaymentPort). Default methods evolve an interface without breaking all implementors — they are not a substitute for a well-designed abstract base.

After Java 8, “interfaces cannot have method bodies” is an incomplete answer. After Java 21, mention that you still cannot new an interface and that diamond default methods must be resolved explicitly.

On an order service: OrderRepository is an interface (port). A JpaOrderRepository is an implementation. You do not need an AbstractRepository unless you truly share template methods and state.

The equals / hashCode contract

If two objects are equal according to equals, they must have the same hashCode. Unequal objects may still collide. HashMap and HashSet first bucket by hash, then confirm with equals.

Override both or neither. If you override only equals, two equal OrderIds can land in different buckets and lookups miss — the value is in the map, get returns null. That is the failure they will walk you through. Saying “the contract” is not the answer; show the missed lookup.

See it

equals / hashCode contract in a real map equals / hashCode contract in a real map Equal keys MUST share a hash. Unequal keys MAY collide. Override both or neither. put(orderId, order) then get(same logical id) put store in bucketchosen TODAY hashCode() must use thesame fields bucket[i] chain / tree hit equals true equals Contract reflexive · symmetric · transitive · consistent · false for nullUse the SAME fields in equals and hashCode. Prefer a final OrderId. Broken implementations ! only equals hashes differ → GET nullwhile the value is in the map ! mutated key bucket is staleentry is orphaned Interview objects + record OrderId(String v) Components generate both.Still copy mutable listsbefore they become keys. getClass vs instanceof instanceof + extra subclassstate can break symmetry.getClass() is stricter. Say at the board hashCode → index → equals.Then stop. Do not openOpenJDK source. contract orphan miss records help
hashCode chooses the bucket; equals confirms. A drifted hash orphans the entry.

Read the diagram, then say: put stores the entry in the bucket chosen by *today’s* hash. If equals says two ids are the same but hashCode does not, get walks the wrong chain and you report “not found” for a key that is sitting in the map.

equals must be reflexive, symmetric, transitive, consistent, and return false for null. Use the same fields in both methods. Prefer getClass() vs instanceof as a conscious choice: instanceof is friendlier to some hierarchies and breaks symmetry if a subclass adds state; getClass() is stricter. Records generate both correctly for their components.

java

public final class OrderId {
    private final String value;

    public OrderId(String value) {
        this.value = Objects.requireNonNull(value);
    }

    @Override
    public boolean equals(Object o) {
        return o instanceof OrderId other && value.equals(other.value);
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }
}

Never mutate fields that participate in equality after the object is used as a map key. The bucket is chosen at put. Change the bytes of value and the map will not find the entry.

Immutability

An immutable type never changes after construction: private final fields, no setters, defensive copies of mutable internals on the way in and out, class final or sealed so a subclass cannot introduce mutability.

Why interviewers care:

  • Safe to share across threads without locks
  • Safe as map keys
  • Money.plus returns a new instance; totals are easier to reason about

String is the everyday example. Records are shallowly immutable: a record OrderView(List<Line> lines) still leaks if lines is a mutable ArrayList. Copy or wrap with List.copyOf.

Do not use records as JPA entities. Entities have identity, lazy proxies, no-arg construction, and mutable state. Records shine as DTOs and value objects (Money, Sku, OrderId).

final on a reference is not immutability. final List<Line> lines can still be cleared. Mid-level candidates mix those up a lot.

Encapsulation vs public record components

Public record components are acceptable for pure values crossing a boundary (API DTO). Public mutable fields on an entity are not. The question is whether callers can break an invariant. Money with a public mutable BigDecimal field is a smell even if you “promise not to call amount.negate().”

Whiteboard in 60 seconds

  1. Box: hashCode() → index → bucket → equals().
  2. Write the contract: equal ⇒ same hash. Unequal may collide.
  3. Draw a mutated key with a red “orphan” arrow.
  4. Record vs class: records generate both for components; still copy mutable lists.

Interview questions

Explain the equals and hashCode contract. What breaks if you implement only equals?

Walk HashMap: hash selects bucket, equals confirms. Missing hashCode → missed lookups.

How do you make a class immutable?

Final type, final fields, no setters, copy mutable inputs/outputs. Mention why: threads and keys.

Why is String immutable?

Security, pooling of literals, safe keys, no races. intern() is optional and easy to abuse on request data.

When do you still write a class instead of a record?

Behavior-heavy aggregates, JPA entities, mutable workflow state, a hierarchy that is not a sealed data carrier.

Follow-up: “What happens if a key’s hashCode changes after put?” The entry is orphaned. You will not find it with get of the “same” logical key.

COMMON MISTAKE: Implementing equals with == on nested value types, or using a mutable List as part of a key.

INTERVIEW TIP: Draw one box: hashCode → bucket → equals. Thirty seconds is enough. Then stop.

Generics, exceptions, modern Java11 min

Generics, exceptions, modern Java

Generics, exceptions, modern Java

In one sentence: PECS tells you whether a payment list is a producer or a consumer; exceptions tell the caller what is recoverable; modern Java is records, sealed types, and APIs that stay honest.

Generics without the textbook fog

Generics exist so List<Order> is not a List of surprises. Type parameters are erased at runtime: you cannot do new T[] or if (value instanceof T) on a bare parameter the way you hope. That is why libraries use Class<T> tokens or factory functions.

Wildcards are the interview:

  • List<? extends Payment> — you can read Payment (or a subtype). You cannot safely add a CardPayment, because the actual list might be List<WirePayment>.
  • List<? super Payment> — you can write Payment. Reads come back as Object.

PECS: Producer Extends, Consumer Super.

If a method produces values for you (source), use extends. If it consumes values you give it (sink), use super.

java

public static void copyAccepted(
        List<? extends Payment> source,
        List<? super Payment> sink) {
    for (Payment payment : source) {
        if (payment.accepted()) {
            sink.add(payment);
        }
    }
}

source is a producer. sink is a consumer. Say PECS, then point at the two lists. That is a complete mid-level answer.

See it

PECS — producer extends, consumer super PECS — producer extends, consumer super src produces values you read. dest consumes values you write. That is the whole wildcard interview. List<? extends Money> PRODUCER — you readget() → Moneyadd(Money) ✗might be List<WireMoney> copyAccepted(src, dest) for (Money m : src) if (m.accepted()) dest.add(m) List<? super Money> CONSUMER — you writeadd(Money) ✓get() → Object read write ! add to extends Compiler refuses.The list might only holdWireMoney. A CardMoneywould corrupt it. Erasure At runtime both are List.Compiler inserted casts.Cannot overload two methodsthat erase to List. Skip wildcards when You own a List<Money>and you both read and write.PECS is for APIs thatshare collections. extends = read super = write erasure
Source is List<? extends Money> (read). Sink is List<? super Money> (write).

Read the diagram, then say: I can get a Money from the left list. I cannot add a Money there — it might really be List<WirePayment>. I *can* add a Money to the right list. Reads from the right come back as Object.

Unbounded ? is “I need a list but I will not read a useful type or write.” Raw types (List) are a compatibility leftover — do not use them in new code.

Exceptions at a service boundary

Checked exceptions (Exception minus RuntimeException) must be declared or handled. They signal recoverable, caller-visible conditions (IOException talking to a payment network).

Unchecked (RuntimeException) signal programming bugs or conditions the immediate caller cannot usefully heal (IllegalArgumentException on a blank SKU, EntityNotFoundException mapped to 404).

Decision rule for an Order API:

  • Validate input → unchecked (IllegalArgumentException or a domain InvalidOrderException)
  • Talk to a flaky SDK that throws checked → catch at the adapter, wrap in a domain unchecked (PaymentGatewayException) so OrderService stays readable
  • Never throws Exception on a public application method
  • Never use exceptions for “item not in cart” on the happy path if a Optional or Result is clearer — but Spring REST often maps domain exceptions via @ControllerAdvice, which is fine if they are exceptional

try-with-resources beats a hand-written finally. Resources implement AutoCloseable. If close() throws, the original exception is kept and the close failure is suppressed (getSuppressed()). A sloppy finally { conn.close(); } can hide the real SQL error.

Modern Java they expect you to have touched

FeatureInterview use
RecordsDTOs, Money, command objects; compact constructor for validation
Sealed typesClosed payment outcomes; exhaustive switch
Pattern matchingif (id instanceof OrderId oid)
varLocal inference only; do not put var on API boundaries
Text blocksJSON fixtures in tests, not business logic
Virtual threads (21)“I know they exist; I would not hide blocking JDBC behind unlimited fan-out without measuring.” Honest beats trendy

Records are not JPA entities. Compact constructors validate: blank currency dies at construction.

Overloading vs overriding (they sneak this in)

Overriding is runtime dispatch on the receiver. Overloading is compile-time on static argument types. @Override exists so a typo becomes a compile error instead of a silent overload. You cannot overload by return type alone. An override may narrow the return type (covariant) and must not add new checked exceptions.

Whiteboard in 60 seconds

  1. Write copy(src, dest) with ? extends on src and ? super on dest.
  2. Try src.add(new CardPayment()) — explain why the compiler refuses.
  3. One line on erasure: at runtime both lists are List; the compiler inserted casts.
  4. Boundary: wrap checked I/O at the adapter; do not throws Exception on OrderService.

Interview questions

What is PECS?

Producer Extends, Consumer Super. Give the copyAccepted signature. Mention you cannot add to List<? extends Payment>.

Checked vs unchecked — how do you choose?

Recoverable at this API vs bug / domain failure mapped at the edge. Wrapping checked I/O at the adapter is a senior move.

Why try-with-resources?

Auto close, reverse order, suppressed exceptions.

When is a record the wrong tool?

JPA entity, mutable workflow, need for a non-canonical identity.

Follow-up: “What is type erasure?” The compiler inserts casts; at runtime List<Order> and List<Payment> are both List. You cannot overload two methods that erase to the same signature.

COMMON MISTAKE: Catching Exception in OrderService and returning null. You hid the failure and often committed a transaction.

INTERVIEW TIP: If PECS goes blank, say “source vs sink” and write the two wildcards. The acronym is a memory hook, not the explanation.

You will

  • Walk key → hashCode → bucket → equals
  • Name a race and how you would fix it

Collections and HashMap12 min

Collections and HashMap

Collections and HashMap

In one sentence: Pick the collection from the access pattern; explain HashMap as hash → bucket → equals, not as a tour of OpenJDK internals.

Decision table (say it in the interview)

NeedReach forAvoid
Lookup order by IDHashMap<OrderId, Order>TreeMap unless you must sort keys
Insertion-order statementsLinkedHashMapRelying on HashMap iteration order
Access-order LRU sketchLinkedHashMap (accessOrder=true) + removeEldestEntryHand-rolled list + map until they ask
Sorted SKUsTreeMap / TreeSetHashMap plus a later sort if you query in order often
Unique line SKUs, fast containsHashSetList.contains on a large catalog
Queue of workArrayDequeStack, Vector
Frequent index accessArrayListLinkedList (almost never the interview win)
Concurrent mapConcurrentHashMapWrapping HashMap with a single lock unless the critical section is wider than the map

LinkedList is the usual wrong pick. Interviewers still hear “O(1) insert” without “except you already have the node.” Random access and memory locality make ArrayList the default list.

enum keys → EnumMap. Tiny static maps → Map.of (immutable, no nulls). Need null keys? HashMap allows one null key; ConcurrentHashMap and Hashtable do not. Prefer not needing null keys.

HashMap lookup, conceptually

See it

HashMap lookup — hash, bucket, equals, treeify HashMap lookup — hash, bucket, equals, treeify Say this: hash selects the bucket, equals confirms. Mutate the key and the entry is orphaned. Happy path for get(OrderId) Key OrderId("ord-9")value fields only 1. hashCode() mix bits0xA31F 2. index (n-1) & hashbucket 3 of 16 3. bucket walk chain, then tree if ≥ 8Java 8+ kills O(n) 4. equals() → Order same type + fieldsor miss in this bucket Why interviewers ask this hash chooses the bucket. equals confirms the key. Treeify at 8 collisions is the hostile-hash answer — not a table-size recitation. Failure interviewers expect ! equals only hashes differ → twobuckets → get() misses ! mutable key put used old hashget walks new bucket Resize load > 0.75 → new table, rehash every entryDo not recite table sizes. Do say rehash. What ConcurrentHashMap does NOT fix Map ops vs business race CHM makes put/get safe.read qty then write qty-1 is still a race. Say this I pick HashMap for a single thread.I pick CHM for the map. I pick SQL/lock for inventory. hash → index equals walk treeify @ 8 not thread-safe
Key → hashCode → bucket index → equals walk. Long collision chains treeify.

Read the diagram, then say: I never start with OpenJDK internals. I start with “hash selects a bucket, equals confirms.” Resize rehashes. If you mutate the key, the entry is orphaned.

You do not need to recite table sizes. You need this story:

  1. Call key.hashCode().
  2. Mix / mask that hash to choose a bucket (an index in the table).
  3. If the bucket is empty, miss.
  4. If occupied, walk the chain (or tree) and call equals until a key matches.
  5. Return the value or miss.

Equal keys must share a hash. If you override equals on OrderId and forget hashCode, two IDs that compare equal hash differently, land in different buckets, and get misses. That is the production bug.

If you mutate a key after put, the bucket is stale. The entry is orphaned.

Java 8+ treeifies long collision chains (under conditions) so a hostile or accidental collision does not turn lookup into a linear scan of thousands. Mention it as a tail-risk, not your opening. Capacity, load factor (default 0.75), and resize are “it grows and rehashes” unless they ask you to be more precise.

HashMap is not thread-safe. Concurrent put can loop or lose entries on old JDKs and is still undefined. ConcurrentHashMap allows concurrent map operations. It does not make “read quantity, then write quantity-1” atomic. That is a check-then-act race on inventory — you need a lock, an atomic updater, or the database.

Whiteboard in 60 seconds

  1. Decision first: lookup → HashMap; order → LinkedHashMap; sort → TreeMap; unique → HashSet.
  2. Draw the five-step lookup. Circle equals *and* hashCode.
  3. Write “not thread-safe” on HashMap. Write “not atomic check-then-act” on ConcurrentHashMap.
  4. Cross out LinkedList unless you already hold the node.

Identity vs value

IdentityHashMap uses ==. Do not use it for OrderId values. WeakHashMap is for caches keyed by objects you are willing to forget when nothing else references the key — not for “orders we must not lose.”

Build It on orders

text

GET /orders/{id}           → HashMap or, in prod, the DB primary key
Daily statement by time    → LinkedHashMap if in-memory; else ORDER BY
Top SKUs alphabetically    → TreeMap
Idempotency store          → ConcurrentHashMap in a lab; DB unique key in prod

When they ask “which collection?” answer with the operation, then the type, then the cost you accepted (TreeMap is log n and needs Comparable keys).

Interview questions

How does HashMap find a value?

Hash → bucket → equals. Then the missing-hashCode failure.

Why is LinkedHashMap a thing?

Predictable iteration: insertion order (statements) or access order (LRU).

Is HashMap thread-safe?

No. ConcurrentHashMap for concurrent map ops. Still not a substitute for a transactional reserve.

ArrayList vs LinkedList?

ArrayList default. LinkedList almost never, unless you already hold nodes and only do ends.

What is the load factor?

Resize trigger (size > capacity * loadFactor). 0.75 balances waste vs rehash. Do not tune it in an interview unless they have a measured problem.

COMMON MISTAKE: Implementing a cache with HashMap and no eviction, then wondering why the JVM OOM’d after Black Friday.

INTERVIEW TIP: If they push “draw the Node class,” sketch key/value/next and stop. They want to see if you panic into source-code trivia.

Streams and functional Java10 min

Streams and functional Java

Streams and functional Java

In one sentence: Use streams to transform collections you can name in one breath; keep side effects out of the pipeline; know when a for-loop is the senior choice.

What a stream is

A stream is a pipeline: source → zero or more intermediate ops (lazy) → one terminal op (drives the work). Intermediate ops (map, filter, flatMap, distinct, sorted, peek) do not run until you collect, reduce, forEach, findFirst, or count.

You cannot reuse a stream after a terminal operation. A second collect throws. That is a common live-coding surprise.

See it

Stream pipeline — lazy until a terminal op Stream pipeline — lazy until a terminal op filter / map / flatMap build a recipe. collect / findFirst / reduce pull data through. You cannot reuse the stream. One breath: filter paid → map id → toList orders.stream() sourcelazy filter Status.PAIDintermediate map Order::idone-to-one flatMap lines().stream()one-to-many collect / findFirst TERMINALpulls the pipeline pull ! second collect IllegalStateExceptionStream is consumed.Source the collection again. ! parallelStream default Common ForkJoinPool.Do not touch EntityManager,HttpServletRequest, or ashared ArrayList. + when a loop wins Multi-exit rules,indexed access, or apipeline you cannot sayin one breath. lazy terminal pulls no reuse
Source is lazy. filter / map / flatMap build the pipeline. collect pulls data through.

Read the diagram, then say: Nothing in filter or map runs until a terminal op. That is why findFirst after a filter can stop early. A second collect on the same stream throws.

Code It on order lines

java

Map<String, BigDecimal> totalsBySku = order.lines().stream()
    .collect(Collectors.groupingBy(
        OrderLine::sku,
        Collectors.reducing(BigDecimal.ZERO, OrderLine::lineTotal, BigDecimal::add)));

List<String> paidIds = orders.stream()
    .filter(o -> o.status() == Status.PAID)
    .map(Order::id)
    .map(OrderId::value)
    .toList();

Map<Boolean, List<Payment>> acceptedVsOther = payments.stream()
    .collect(Collectors.partitioningBy(Payment::accepted));

groupingBy is the interview collector. partitioningBy is groupingBy on a boolean. flatMap flattens nested lines: orders.stream().flatMap(o -> o.lines().stream()).

toList() (Java 16+) is unmodifiable. Collectors.toList() is a mutable ArrayList. Know which you returned before you try to add.

Optional

Optional is a return type for “this lookup might miss.” It is not a field, not a parameter, not something you new Optional() around everything.

java

public Optional<Order> findById(OrderId id) { ... }

Order order = findById(id).orElseThrow(() -> new OrderNotFoundException(id));

Do not get() without a guard. Do not orElse(expensive()) if the fallback is costly — orElseGet(this::loadDefault) is lazy. Never orElse(null) unless you enjoy defeating the type.

Side effects and parallel

forEach that adds to a shared ArrayList is just a for-loop with extra objects. If you parallelStream() that, you have a race. Parallel streams use the common ForkJoinPool. They help CPU-bound work on large, splittable sources. They hurt:

  • Small lists (setup cost)
  • Anything that touches a HttpServletRequest, a transactional EntityManager, or a non-thread-safe collector you invented
  • I/O to the payment API

Default: sequential. If you say parallel, say how you would measure and which pool you would isolate (ForkJoinPool constructor) so you do not starve Tomcat.

peek is for debugging. Do not charge cards in peek.

Primitive streams

mapToInt / IntSummaryStatistics avoid boxing when you are summing quantities. For money, stay on BigDecimal. double totals are how you lose pennies.

Functional interfaces they name

Function, Predicate, Consumer, Supplier, UnaryOperator, BiFunction. Method references (Order::id) are fine when the name is clear. A 12-line lambda inside collect is a method.

Checked exceptions do not pass through map cleanly. Wrap at the boundary or use a small helper that sneaks a domain unchecked exception. Do not invent a “sneaky throws” utility in an interview unless you can defend it.

Whiteboard in 60 seconds

  1. Write one pipeline out loud: “filter paid → map id → toList.”
  2. Mark intermediate vs terminal. Write “lazy until terminal.”
  3. map = one-to-one; flatMap = lines of lines.
  4. Cross out parallelStream() unless you can name the pool and the measurement.

When a loop is better

Multi-exit business rules, indexed access, or a pipeline you cannot read in one glance. Staff engineers pick the boring loop and say why. That reads better than a clever reduce.

Interview questions

Are intermediate operations lazy?

Yes. Nothing runs until a terminal op. That lets findFirst stop early after a filter.

map vs flatMap?

map one-to-one. flatMap one-to-many, flattens streams of lines.

Why is Optional not a field?

It is not serializable-friendly, it is not a substitute for empty collections, and it clutters domain models. Use empty List for “no lines.”

When is parallelStream wrong?

Shared mutable state, tiny data, thread-bound persistence, blocking I/O.

Follow-up: “This grouping is slow.” First ask N and whether you are doing I/O inside the lambda. Then consider a SQL GROUP BY instead of loading every order.

COMMON MISTAKE: orders.stream().forEach(repo::save) inside a conversation about functional style. That is a loop with extra objects.

INTERVIEW TIP: Read the pipeline left to right out loud: “filter paid, map to id, collect list.” If you cannot say it, rewrite it.

Concurrency13 min

Concurrency

Concurrency

In one sentence: Name the shared state, name the race, then pick the smallest Java tool that makes the critical section correct.

CompletableFuture (compose, do not block)

CompletableFuture — compose, isolate the pool, handle failure CompletableFuture — compose, isolate the pool, handle failure thenApply maps a value. thenCompose flat-maps a future. Omit an executor and you often sit on the common pool. supplyAsync load orderON your executor thenApply map to DTOsame future thenCompose chargeAsync()flatMap a Future exceptionally timeout / 5xxmap to domain thenCombine wait for tax+ inventory join / orTimeout do not block therequest thread fail Say this I pass an explicit executor sized for I/O. I never block ForkJoinPool.commonPool() on JDBC or HTTP. join() without a timeout is how a Tomcat thread dies waiting on payments. thenApply thenCompose name the pool
supplyAsync → thenApply / thenCompose → exceptionally → join. Name the executor.

thenApply maps a value. thenCompose flat-maps a future (the flatMap of async). If you omit an executor, you often land on ForkJoinPool.commonPool() — do not block that pool on HTTP or JDBC from a request thread. join() on the request thread is a timeout waiting to happen unless the work is already complete.

The inventory race (open with this)

Two threads reserve the last unit of SKU SKU-1:

text

T1 reads qty=1
T2 reads qty=1
T1 writes qty=0, creates reservation
T2 writes qty=0, creates reservation

You oversold. HashMap vs ConcurrentHashMap is not the fix. The race is check-then-act on quantity.

See it

Check-then-act inventory race Check-then-act inventory race Two threads read qty=1 and both reserve. ConcurrentHashMap does not make this atomic. Two JVMs make a process lock useless. T1 T2 — same millisecond read qty = 1 write qty = 0 creates reservation thinks success last unit mine read qty = 1 write qty = 0 creates reservation thinks success last unit mine Result: two reservations, stock lie CHM / HashMap choice is irrelevant.Need synchronized, CAS loop, @Version retry,or UPDATE inventory SET qty=qty-1 WHERE sku=? AND qty>=1 Two app instances A JVM lock is not enough.The database is the lock. oversell CAS / SQL 2 instances
T1 and T2 both read qty=1 and both reserve. The map type does not make this atomic.
ThreadPoolExecutor — core, queue, max, reject ThreadPoolExecutor — core, queue, max, reject Idle core first. Then the bounded queue. Then extra threads. Then the reject policy. newCachedThreadPool is not an API default. Submittedtask checkoutrunnable Executor ThreadPoolExecutor 1. Core workers idle threadtakes it now 2. Work queue bounded ArrayBlockingQueue 3. Max workers queue full →start extra Run do the workthen return to pool 4. RejectedExecution AbortPolicy → 503CallerRuns steals TomcatDiscard is silent data loss idle busy saturated Interview sentence I size core to CPU-bound work, queue to absorb a burst I can still finish, max as a last gasp, and I fail the request when saturated. I do not use an unbounded queue in front of checkout. core first bounded queue reject = 503
Core threads, then the queue, then max threads, then the reject policy.

Read the diagrams, then say: The first picture is a business race. The second is how an API survives load. I pick a *bounded* queue and a reject policy that fails the request — I do not use newCachedThreadPool() on checkout.

Fixes, from interview-simple to production:

  1. synchronized on the inventory service (correct, coarse, easy to say)
  2. ReentrantLock if you need tryLock / interruptibly
  3. Optimistic version on the row (@Version); retry on OptimisticLockException
  4. Single SQL UPDATE inventory SET qty = qty - 1 WHERE sku=? AND qty >= 1 and check update count
  5. Serialize reserves per SKU on a queue

Say what you give up: a process-wide lock fails when you have two app instances. That is how you get to the database.

Whiteboard in 60 seconds

  1. Two timelines, same qty=1. Two reservations.
  2. List fixes: lock → CAS loop → UPDATE … WHERE qty >= 1 → version column.
  3. Write “2 instances ⇒ process lock is not enough.”
  4. Draw the pool: core → queue → max → reject. Name AbortPolicy or a 503.

Visibility vs atomicity

volatile guarantees that a write becomes visible to later reads and forbids some reorderings. It does not make qty = qty - 1 atomic. You can see a stale value or lose an increment.

AtomicInteger makes that increment atomic. It still does not make “if qty > 0 then decrement and insert reservation” atomic. You need compareAndSet in a loop or a lock around the compound action.

synchronized gives mutual exclusion and visibility (happens-before). Do not synchronize on a public object or Boolean/Integer cache. Synchronize on a private final lock.

Thread pools

new Thread() per request will fail in production. Use ExecutorService.

PoolUse
newFixedThreadPool(n)Bounded work (payment callbacks)
newCachedThreadPool()Easy to explode; say so
newSingleThreadExecutor()Ordered side effects (outbox publisher)
ForkJoinPool.commonPool()Parallel streams; do not block it

Always shutdown / shutdownNow in tests and in DisposableBean. Name the queue + rejection policy if they ask how you survive a payment-provider outage (CallerRuns, Abort, a bounded queue).

CompletableFuture

java

CompletableFuture<Quote> tax = supplyAsync(() -> taxClient.quote(order), taxPool);
CompletableFuture<Quote> ship = supplyAsync(() -> shipClient.quote(order), shipPool);
Quote both = tax.thenCombine(ship, Quote::sum).orTimeout(200, MILLISECONDS).join();

Use your executors, not the common pool, for blocking HTTP. join() vs get(): join unchecked. Handle CompletionException. allOf waits; anyOf races. Cancel what you no longer need.

Virtual threads (Java 21) make blocking cheaper. They do not make shared mutable inventory safe. You still need the critical section.

Deadlock

Two locks, opposite order: payment lock then inventory lock vs the reverse. Interview answer: lock ordering, tryLock with timeout, or fewer locks (one DB transaction). Detect with thread dumps (jstack) — threads BLOCKED on each other’s monitors.

Happens-before they may name

Unlock / lock on the same monitor, volatile write / read, thread start / join, executor submit / task run. You do not need the JMM paper. You need: “without a happens-before, this write may never be seen.”

Interview questions

What does volatile guarantee?

Visibility and ordering, not atomic compound actions.

synchronized vs ReentrantLock?

synchronized is simpler and auto-releases. Lock adds try/timeout/fairness/multiple conditions. Prefer synchronized until you need those.

Is ConcurrentHashMap enough for a reserve?

No. Map safety ≠ business atomicity.

How do you wait for two downstream calls?

thenCombine / allOf, dedicated pools, timeout.

Follow-up: “We have two instances.” Move the critical section to the database or a shared lock (and discuss lock service cost). In-memory synchronized is a single-node story.

COMMON MISTAKE: Thread.sleep in production code to “wait for the other service.” Use a timeout, retry policy, or messaging.

INTERVIEW TIP: Draw two timelines and the lost update. Then pick a tool. Do not start at AbstractQueuedSynchronizer.

JVM essentials10 min

JVM essentials

JVM essentials

In one sentence: Know where bytes live, what a stop-the-world pause is, and how you would diagnose an OOM or a CPU spike — not how to implement G1.

Memory regions (interview map)

RegionWhat lives there
HeapObjects: Order, byte arrays, maps, entity graphs
Stack (per thread)Frames, local primitives, references to heap objects
MetaspaceClass metadata, bytecode-ish structures; native memory, not the old PermGen heap
Code cacheJIT-compiled native code
Direct / off-heapNIO buffers, some caches and Netty; can OOM outside -Xmx

A local Order order variable is a reference on the stack (or in a register) pointing at a heap object. Candidates who say “objects live on the stack” lose easy points.

See it

JVM memory — stack, heap generations, metaspace, off-heap JVM memory — stack, heap generations, metaspace, off-heap Objects live on the heap. Frames live on the stack. Metaspace is native. Not every OOM is -Xmx. Per Java thread Thread stack frames · localsrefs to heap objectsNOT the Order itself PC register current bytecode Native / direct NIO buffers, NettyOOM outside -Xmx Heap (-Xms / -Xmx) · young gen on top Eden new Order, DTOsmost die here Survivor S0 copied if live Survivor S1 age, then tenure Old generation long-lived caches, interned-ish data,entity graphs you accidentally pinned Heap dump suspects unbounded HashMap · forgotten cacheEAGER graph · session list Non-heap Metaspace class metadata-XX:MaxMetaspaceSizeloader leaks on redeploy Code cache JIT native code Say this A local Order varis a stack *reference*to a heap object. stack = refs heap = objects metaspace native
Each thread has a stack. Objects live on the heap. Metaspace holds class metadata.

Read the diagram, then say: The stack holds frames and *references*. The heap holds Order instances. Metaspace is native, not the old PermGen heap. I can OOM with heap free if direct memory or Metaspace is exhausted.

-Xmx / -Xms size the heap. Metaspace has -XX:MaxMetaspaceSize. Direct memory is a different knob. An app can die with heap free if native or metaspace is exhausted.

GC at interview depth

Young generation (Eden + survivors): most Order DTOs die here. Old generation: long-lived caches, interned or static data, entity graphs you accidentally pinned.

Stop-the-world means application threads pause so the collector can do a phase safely. All collectors have some STW; the question is how long and how often. G1 is the HotSpot default on modern LTS. ZGC / Shenandoah aim at low pause. You do not pick ZGC in an interview because a blog said “pause-less” — you pick it if pause SLOs and a measured profile say so.

Throughput vs latency is the trade-off. A batch inventory reconciliation can tolerate longer pauses. A checkout p99 of 50 ms cannot.

OOM vs StackOverflow

OutOfMemoryError: Java heap space — live set larger than the heap (leak or undersized cache). Look at a heap dump (jcmd GC.heap_dump, Eclipse MAT, VisualVM). Dominators: a HashMap of sessions, an unbounded queue, a JPA graph you loaded with EAGER everything.

OutOfMemoryError: Metaspace — class loader leak (redeploys, generated classes).

StackOverflowError — too-deep recursion or huge frames, not “the heap is full.”

Never catch Error to “keep the JVM running.” You do not know what is consistent.

JIT, in short

Interpreted first, then hot methods compile. Warm-up matters for benchmarks. final / monomorphic call sites help the JIT; this is a footnote, not your performance plan. First make the algorithm and the SQL honest.

How you diagnose (they want a path)

  1. Reproduce with a metric: p99 of POST /orders, heap after 30 minutes, GC pause time.
  2. Logs + traces (correlation ID) to see if you are in GC, SQL, or the payment HTTP call.
  3. jcmd Thread.print / thread dump for deadlock or a stuck pool.
  4. GC logs (-Xlog:gc*) if pauses match the blip.
  5. Heap dump only if live set is the suspect.

Do not “tune GC” as step one. Most checkout slowness is N+1, a missing index, or a sync call to payments with no timeout.

Whiteboard in 60 seconds

  1. Three boxes: stack / heap / metaspace. One example in each.
  2. Young vs old: DTOs die young; a static cache tenures.
  3. STW = application threads paused. Relate to checkout p99.
  4. Diagnose path: metric → trace → GC log *or* heap dump. GC tune is last.

Class loading

A class is unique per fully qualified name + class loader. Two Order classes from two loaders are not assignable. Web apps and plugins leak loaders. Static caches in libraries are per loader, which surprises people who thought “singleton” meant JVM-global.

Interview questions

Heap vs stack vs metaspace?

Objects / frames / class metadata. Give one example each.

What is a stop-the-world pause?

Application threads paused for a GC phase. Relate to p99 checkout.

How do you find a memory leak?

Heap dump, dominator tree, look for unbounded maps/queues, forgotten caches.

Why did we OOM with lots of free heap?

Direct memory, metaspace, native leak — not every OOM is -Xmx.

Follow-up: “Should we switch to ZGC?” Ask pause goals, heap size, JDK version, and whether the problem is even GC. That is the staff answer.

COMMON MISTAKE: “Garbage collection is automatic so we cannot have leaks.” GC frees unreachable objects. A static List<Order> is reachable forever.

INTERVIEW TIP: If you do not remember a flag, say you would read the current HotSpot GC docs and measure. Inventing -XX:+Magic is worse than honesty.

You will

  • Explain why constructor injection is the default
  • Name the N+1 fix you would ship

Spring fundamentals15 min

Spring fundamentals

Spring fundamentals

In one sentence: Spring is an IoC container plus an ecosystem; constructor injection makes the graph explicit; Boot auto-configures beans you would otherwise write by hand.

IoC and the container

You do not new OrderService(new StripeClient(), new JpaOrderRepository()) in a controller. You declare beans; the container wires them. Inversion of control means the framework calls you (@PostConstruct, request mapping, @EventListener), not the other way around. Dependency injection is how the graph is supplied.

See it

Spring IoC — the container owns the graph Spring IoC — the container owns the graph You declare beans. The context constructs them. Constructor injection makes dependencies required, final, and unit-testable. @Configuration+ stereotypes @Service OrderService@Repository JpaRepo@Bean DataSource ApplicationContext constructs graphsingleton by defaultrefresh fails fast OrderService final PaymentGatewayfinal OrderRepository JpaOrderRepository port implementation OrderController final OrderServiceHTTP only scan new new inject ! field @Autowired hides the graph · not finalneeds Spring or reflection in testsmissing bean fails on first request + constructor new OrderService(fakePay, fakeRepo)no Spring in the unit testcircular deps are a design smell, not a @Lazy habit ctor inject fail at startup no field @Autowired
ApplicationContext constructs OrderService and injects OrderRepository. Controller depends on the service.
Spring Boot request lifecycle Spring Boot request lifecycle Filters wrap the servlet. DispatcherServlet maps the handler. Advice and converters shape the JSON. Security lives in the filter chain. HTTPclient POST /orders Filter chain CORS · corr. IDSpring Security DispatcherServlet HandlerMappingHandlerAdapter Controller DTO in / outno transaction Service @Transactionalrules @ControllerAdvice 400 / 404 / 409Problem Details HttpMessageConverter Jackson writes JSONnever an entity 200 4xx Say this Security is a filter, not a controller annotation fantasy. The controller returns a DTO. Jackson is the converter. Open Session in View serializing an entity during this last step is how N+1 hides in production. filters first advice on error converter last
HTTP → filters → DispatcherServlet → controller → converter. Advice handles errors.
Spring proxy — why this.create() skips @Transactional Spring proxy — why this.create() skips @Transactional Annotations run on the JDK/CGLIB proxy. A raw this.method() never hits the interceptor. That is the rollback interview. Controller orderService.create() Spring proxy begin TXcommit / rollback@Async / security + create() via proxy interceptor runsTX starts ! this.create() same class callNO interceptor DB work flush + commit No TX / no rollback partial writesor AutoCommit surprises bean public API internal Fix Extract OrderWriter / OrderWorkflow and inject it — two Spring beans. Do not @Lazy self-inject as your first answer. Private @Transactional methods never get a proxy. proxy only self-call skips split the type
Annotations run on the proxy. this.create() skips @Transactional.

Read the diagrams, then say: I can draw Controller → Service → Repository in 20 seconds. Constructor injection makes that graph *required* and testable. @Transactional is a proxy — a self-call never starts a transaction.

Bean scopes you must know:

ScopeMeaningInterview example
singleton (default)One instance per containerOrderService
prototypeNew instance per lookupRare in web apps; easy to misuse
request / sessionWeb-awareBound to HTTP lifecycle

A singleton that holds request state is a bug. A singleton that holds a thread-safe PaymentClient is normal.

Constructor injection (required answer)

java

@Service
public class OrderService {
    private final PaymentGateway payments;
    private final OrderRepository orders;

    public OrderService(PaymentGateway payments, OrderRepository orders) {
        this.payments = payments;
        this.orders = orders;
    }
}

Why this is the interview default:

  • Dependencies are final — the object is fully formed
  • Missing beans fail at startup, not on the first checkout
  • Unit tests are new OrderService(fakePayments, fakeOrders) — no Spring, no reflection
  • The constructor is the API of the type

Field @Autowired hides the graph, prevents final, and needs ReflectionTestUtils or a Spring test to poke values. Setter injection is for optional deps. @Autowired on the constructor is unnecessary on a single constructor (Spring 4.3+ / Boot).

Circular dependencies (OrderService → PaymentService → OrderService) are a design smell. Boot will complain. Fix by splitting a third type (Settlement) or using events — not by @Lazy as your first answer. Mention @Lazy as a last resort.

Auto-configuration

@SpringBootApplication is @Configuration + @EnableAutoConfiguration + @ComponentScan. Auto-configuration reads the classpath and your properties, then registers beans only if you did not already define one (@ConditionalOnMissingBean, @ConditionalOnClass).

That is why adding spring-boot-starter-data-jpa gives you a DataSource and an EntityManagerFactory when a driver is present. It is also why your custom DataSource @Bean wins.

application.yaml + @ConfigurationProperties (constructor-bound, ideally immutable records) beat a soup of @Value for structured config (payments.timeout, orders.idempotency-ttl). Profiles (qa, prod) swap URLs, not business classes.

@Component / @Service / @Repository are all stereotypes. @Repository adds persistence exception translation. @RestController is @Controller + @ResponseBody. Do not invent a fourth meaning.

AOP they expect

@Transactional, @Async, @Cacheable, security annotations work through proxies. Self-invocation (this.createOrder() inside the same class) skips the proxy — the transaction interceptor never runs. That is a classic “why isn’t my transaction rolling back?” bug. Split the type or inject self via the container if you must.

By default you get a JDK proxy for interfaces and CGLIB for concrete classes. You do not need the bytecode story unless they push.

Whiteboard in 60 seconds

  1. Draw IoC: config → context → beans. Arrows are constructor params.
  2. Request path: Filter → DispatcherServlet → Controller → Advice/Converter.
  3. Circle the proxy. Draw this.method() skipping it.
  4. Pyramid: new Service(...) / @WebMvcTest / @SpringBootTest rarely.

Testing the container

  • Pure unit: new OrderService(...)
  • Slice: @WebMvcTest (MVC only), @DataJpaTest (JPA + slice)
  • Full: @SpringBootTest when you need the graph

If every test boots the whole context, the suite will be too slow for Monday. Say the pyramid.

Interview questions

Why constructor injection?

Required deps, final, fail-fast, testable. Contrast field injection.

What does auto-configuration do?

Conditional beans from classpath + properties, skip if you already defined the bean.

What is a Spring bean?

An object whose lifecycle the container manages.

Why did `@Transactional` not run?

Self-invocation, missing proxy, unchecked vs checked rollback rules, annotation on a private method.

Follow-up: “Singleton vs prototype for a stateful wizard?” Do not keep wizard state in a singleton. Use a database row or session, not a field on OrderService.

COMMON MISTAKE: SpringApplication.run knowledge without being able to draw Controller → Service → Repository and say who owns the transaction.

INTERVIEW TIP: When they ask “how does Spring work?” start with IoC + constructor injection + proxies. Do not start with BeanFactoryPostProcessor unless they are hiring a framework engineer.

REST, validation, exceptions15 min

REST, validation, exceptions

REST, validation, exceptions

In one sentence: HTTP is a contract — verbs, status codes, DTOs, and idempotency — not a JSON dump of your JPA graph.

Resource design for orders

ActionShapeNotes
Create orderPOST /orders201 + Location. Not idempotent unless you add a key
Get orderGET /orders/{id}200 or 404. Safe, cacheable if you mean it
ListGET /orders?status=PAID&page=0&size=20Pagination required in interviews
CancelPOST /orders/{id}/cancel or DELETEBe explicit about side effects
ReplacePUTFull body, idempotent
PatchPATCHPartial; say how you merge

Do not nest forever: /customers/9/orders/3/lines/2/tax. Prefer /orders/{id} as the root for checkout.

See it

Controller · Service · Repository Controller · Service · Repository HTTP stays in the controller. The unit of work and rules stay in the service. SQL stays in the repository. Entities never cross the HTTP edge. HTTP JSON bodyIdempotency-KeyX-Correlation-Id Controller validate DTOmap to commandmap status codes Service @Transactionalinvariantsports only Repository entityquery Database SQLconstraints DTO cmd entity ! return Order entity lazy lines explode after TXpassword hashes leakOSIV hides N+1 + return OrderResponse explicit fieldsfetch graph chosen for THIS use casecheckout needs lines; existence check does not DTO at edge TX on service no entity JSON
HTTP DTO in, command to the service, entity only in the repository.
Idempotent POST /orders Idempotent POST /orders Same key + same body replays the stored response. Same key + different body is 422. Persist the key in the SAME transaction as the order. Client retry timeout / 503same Idempotency-Keysame JSON body Lookup key unique store+ request hash HIT completed replay status + bodyno second order HIT in-flight 409 or waitdocument the policy HIT different hash 422 — key reusedfor another body MISS insert key + orderONE database TX new ! ConcurrentHashMap in prod dies on restartinvisible to the other instancenot in the order TX + unique (key) next to orders same commit as the rowreplay is a read of the stored responsethis is how Stripe-style keys work replay 201 conflict 422 same TX
Same Idempotency-Key replays the stored 201. Persist the key in the same DB transaction.

Read the diagrams, then say: The controller never returns a JPA entity. Create is not idempotent until I add a key. Same key + same body = replay. Same key + different body = 422.

Versioning: URL (/v1/orders) vs headers. Pick one and stay consistent. Teams fight about this; interviewers want a choice and a migration story.

Whiteboard in 60 seconds

  1. Table: GET 200/404, POST 201+Location, list with page, cancel as a verb.
  2. Draw CSR: DTO | command | entity. Cross out entity in @RequestBody.
  3. Idempotency-Key box next to the order row — same transaction.
  4. Statuses: 400 validation, 404 missing, 409 conflict, 429/503 with retry-after.

Idempotent POST

GET, PUT, and DELETE are idempotent by HTTP semantics. POST /orders is not: two retries, two orders, two charges.

Make create idempotent with a client-supplied Idempotency-Key (header) or a natural key (sourceSystem + sourceOrderId):

  1. Look up the key.
  2. If a completed response exists, return it (same status and body).
  3. If in progress, return 409 or a 202 with retry-after — pick a policy and say it.
  4. If new, persist the key and the order in the same transaction.

TTL the keys. Hash the request body so a reused key with a different payload is a 422, not a silent no-op.

DTOs, not entities

@RequestBody CreateOrderRequest with Bean Validation. @ResponseBody OrderResponse. Entities carry lazy proxies, persistence annotations, and columns you must not leak (internalRiskScore). Mapping is a mapper or a factory on the entity — not Jackson crawling a Hibernate graph (that is how you get LazyInitializationException after the session closes, or an accidental full warehouse dump).

Validation

java

public record CreateOrderRequest(
    @NotBlank String customerId,
    @NotEmpty List<@Valid LineRequest> lines,
    @Size(min = 8, max = 80) String idempotencyKey
) {}

@Valid on the controller argument. @ControllerAdvice turns MethodArgumentNotValidException into a 400 with field errors. Validate money scale and currency in the domain, not only with annotations — annotations cannot encode “lines must share a currency.”

Exceptions and status codes

SituationStatus
Validation400
Auth missing / bad token401
Authenticated but not allowed403
Order id unknown404
Idempotency conflict / in-flight409
Domain rule (cannot cancel shipped)409 or 422
Timeout talking to payments503 or 504
You crashed500 — log the id, do not leak stacks

@ControllerAdvice + @ExceptionHandler map domain exceptions to a stable error body (type, title, detail, instance, correlationId). Problem Details (RFC 7807) is worth naming if you actually use it.

Do not catch Exception in every controller method. Do not return 200 with { "error": true }.

Spring Security, interview depth

You should be able to say: authenticate at the edge (JWT / session), authorize per method or matcher (@PreAuthorize), never roll your own crypto, CSRF matters for cookie sessions and less for bearer APIs. Password encoding, SecurityFilterChain (not the old WebSecurityConfigurerAdapter). If the role is senior, mention method security vs HTTP security and that you do not fetch the order before the 401.

Interview questions

How do you design POST /orders?

201, DTO, validation, idempotency key, Location header.

PUT vs POST vs PATCH?

Create-or-replace vs non-idempotent create vs partial update.

How do you handle errors globally?

@ControllerAdvice, consistent body, correct status, correlation ID.

Why not return the entity?

Lazy load, over-exposure, persistence coupling.

Follow-up: “Client timed out and retried.” Walk the idempotency store. If you have no key, you already failed.

COMMON MISTAKE: POST /orders/create and GET /orders/delete?id= — verbs in URLs, side effects on GET.

INTERVIEW TIP: Write the status codes on the whiteboard before the fields. Interviewers want to see you think in HTTP, not only in Java.

JPA, transactions, testing15 min

JPA, transactions, testing

JPA, transactions, testing

In one sentence: The persistence context is a first-level cache and identity map; @Transactional marks the unit of work; N+1 is the bug they will make you find.

Persistence context

An EntityManager (Session in Hibernate) tracks loaded entities. Same ID → same instance inside the context. Flush happens before query and before commit (default AUTO). After the context closes, lazy associations throw LazyInitializationException if you touch them.

That is why a controller that returns Order with lazy lines fails after the service method ends — or worse, Open Session in View silently issues queries during JSON serialization. The senior answer: OSIV is convenient and hides N+1. Prefer DTO queries or an explicit fetch.

See it

JPA entity states JPA entity states Transient → managed on persist. Detached after the context closes. Removed is scheduled delete. Merge is not a free lunch. Transient new Order()no row yetno id maybe Managed in the contextdirty-checkedsame id = same inst Detached context closedlazy throws Removed delete on flush Database row after flush+ commit persist close merge flush Interview I never put a generated id into equals before persist if two news would collide. Business key (publicOrderNumber) or equals only after id is assigned. Associations do not belong in equals. transient managed detached
Transient → managed on persist. Detached after the context closes. Flush writes SQL.
JPA persistence context — identity map, dirty check, flush JPA persistence context — identity map, dirty check, flush Same id ⇒ same instance inside the context. Flush writes SQL. Commit ends the transaction. After close, you are detached. Service persistfindmutate fields EntityManager Sessionunit of work Persistence context 1st-level cacheidentity mapdirty set Flush / dirty check SQL INSERT/UPDATEbefore query + commit Database constraints@Version AUTO SQL Detached context closedlazy lines → LIEmerge() reattaches a fat graph — dangerous Open Session in View TX still open while Jackson walks gettershides N+1 in prodprefer DTO query Say this I fetch the graph this use case needs.I do not EAGER the catalog.I assert query count in a test. identity map AUTO flush detached
Service → EntityManager → persistence context → flush → database.
Transaction boundary — one unit of work Transaction boundary — one unit of work The proxy begins the TX. Runtime exceptions roll back. Checked exceptions commit unless rollbackFor. After-commit events do not belong inside the method. Controller no @Transactional Spring proxy begincommit / rollback @TransactionalOrderService reserve + saveone unit of work Repositories same EM / same TX Commit success path Rollback RuntimeException begin ok fail Checked exceptions Default: COMMIT.IOException from a sloppy adaptercan persist a half order.rollbackFor = Exception.classor wrap as unchecked. Self-invocation this.create() skips this picture.Split a second bean.Never put email/HTTP to PSPinside the same TX without a timeout story. proxy begins runtime → RB checked → commit
Controller hits the proxy; the service owns the transaction; runtime failures roll back.
N+1 — one parent query, then one query per child N+1 — one parent query, then one query per child GET /orders with lazy lines is 1 + N SQLs. Prove it with a query counter. Fix with a fetch you chose, or a DTO query — not EAGER everywhere. Wrong — lazy walk during JSON GET /orders?size=50 controller returns List<Order> 1. SELECT * FROM orders LIMIT 50 one parent query 2. for each order SELECT * FROM order_lines WHERE order_id=?× 50 → 51 statementsJackson + OSIV make this invisible How you prove it datasource-proxy / p6spy / show-sqlassertThat(queryCount).isEqualTo(1) Right — choose the graph + join fetch / EntityGraph one query, lines presentwatch cartesian producton two bags + DTO / interface projection SELECT o.id, o.statusno entity, no lazy + @BatchSize bandage IN (:ids) batchesstill N-ish, just fewer Say this Checkout needs lines.An existence check does not. 1+N = bad join fetch DTO query
One SELECT orders, then N SELECT items. Fix with join fetch, entity graph, or a DTO query.

Read the diagrams, then say: The persistence context is an identity map. After it closes, lazy lines throw. N+1 is one parent query plus one query per child. @Transactional belongs on the service, not the controller, and this.save() does not start a transaction.

@Entity has identity (@Id). Equals/hashCode on a generated ID is tricky before persist; many teams equal on a business key (publicOrderNumber) or only after the id is assigned. Do not put a mutable association in equals.

Whiteboard in 60 seconds

  1. Four states: transient / managed / detached / removed.
  2. Draw N+1, then the fix (join fetch *or* DTO — say cartesian risk on two bags).
  3. @Transactional on the service. Checked exceptions commit unless rollbackFor.
  4. Test: @DataJpaTest + query count. OSIV is a smell, not a strategy.

Lazy vs eager vs N+1

Default many-to-one is eager in older JPA examples; default one-to-many is lazy. Do not set everything EAGER. You will load the catalog on a health check.

N+1: SELECT * FROM orders then, per order, SELECT * FROM order_lines WHERE order_id=?. One list page, hundreds of queries.

How you see it: spring.jpa.show-sql, p6spy, datasource-proxy, or a test that asserts query count. How you fix it:

  • join fetch in a query you control (watch cartesian products on multiple bags)
  • @EntityGraph on the repository method
  • @BatchSize as a bandage
  • A DTO / interface projection / JdbcTemplate for the read model

Fetch the graph you need for this use case. Checkout needs lines. An order-id existence check does not.

Transactions

java

@Service
public class OrderService {
    @Transactional
    public OrderId create(CreateOrderCommand command) {
        inventory.reserve(command.lines());
        Order order = orders.save(Order.from(command));
        return order.id();
    }
}

Put @Transactional on the service method that is the unit of work. Not on every repository method. Not on the controller (you hold a connection across HTTP mapping).

Rules they probe:

  • Default rollback: unchecked exceptions. Checked exceptions do not roll back unless rollbackFor says so.
  • readOnly = true on query-only methods — hint for flush skip and some pools.
  • REQUIRES_NEW starts a nested independent transaction (audit log that must survive a rollback). Easy to overuse; say why you need it.
  • Self-invocation skips the proxy — the annotation does nothing.
  • Catching exceptions inside the method and returning null can commit. Let it throw, or setRollbackOnly().

Optimistic locking: @Version on Order or InventoryItem. Concurrent reserve → OptimisticLockException → retry or 409. Pessimistic LockModeType.PESSIMISTIC_WRITE for hot SKUs if you accept blocking. Unique constraints are not optional: they catch the race the app missed.

Dual writes vs the transaction

If create commits the order and then publishes OrderCreated over HTTP/Kafka, a crash in the middle loses the event. Outbox: write the event row in the same transaction, publish later. Module 4 deepens this; mention it when they ask about @TransactionalEventListener(phase = AFTER_COMMIT).

Testing

LayerTool
Domain / servicePlain JUnit, fakes, no Spring
Repository query@DataJpaTest + Testcontainers or H2
Controller@WebMvcTest + @MockBean / @MockitoBean
Contract of checkout@SpringBootTest + MockMvc or WebTestClient, one happy + one idempotency + one validation

Do not @SpringBootTest a getter. Assert query counts on the N+1 test. Use @Transactional on tests carefully — it rolls back, which can hide flush bugs; sometimes you want TestTransaction or a real commit.

Interview questions

What is the N+1 problem?

Define, show the SQL shape, give two fixes, reject global EAGER.

Where do you put @Transactional?

Service unit of work. Rollback rules. Proxy / self-invocation.

LazyInitializationException — why?

Association touched after the persistence context closed.

Optimistic vs pessimistic lock?

Version + retry vs row lock. Inventory is the example.

Follow-up: “We still get duplicate orders.” Talk unique constraint + idempotency key, not only @Version.

COMMON MISTAKE: Mapping bidirectional Order ↔ Line with CascadeType.ALL and orphanRemoval you cannot explain, then cascading a delete into payments.

INTERVIEW TIP: If they paste a repository, count the queries in your head before you talk about microservices.

You will

  • Design POST /orders with an Idempotency-Key
  • Investigate slowness with logs, metrics, and traces

Microservices and messaging12 min

Microservices and messaging

Microservices and messaging

In one sentence: Split a service when ownership or scale demands it; when you split, you inherit dual-write, latency, and a consistency story you must say out loud.

Start with one deployable

Interviewers still want a first drawing that a mid-level engineer could ship: one Spring Boot app, orders table, inventory in the same DB if the team is small. Then they say “Black Friday” or “two teams.” You evolve. You do not open with eight repos.

Split when:

  • A different team owns payments and deploys on a different cadence
  • Inventory reserve has a different scale or data model than order history
  • You must isolate a failure domain (a crashing recommender must not take checkout)

Do not split because a blog said “one service per noun.” Each new process is a new timeout, a new auth story, and a new on-call.

See it

Modular monolith first, then split on a reason Modular monolith first, then split on a reason Split on ownership, scale, or failure isolation — not nouns. Each new process is a timeout, an auth story, and a pager. First drawing — ship this One Spring Boot app orders module · payments module · one deploy Orders table + servicesame JVM Payments adapter + tablesame JVM After a real reason API gateway / BFF Ordersvc own DB Paymentsvc own cadence Inventorysvc own scale You now own timeouts · auth · dual-write · versioning · on-call Do not split because a blog said one service per noun A team of eight rarely needs forty repos. Write the reason on the board: deploy cadence, scale, or blast radius. start here split later not nouns
Start as a modular monolith. Split only when ownership, scale, or failure isolation demands it.
Synchronous call — you inherit their latency and outage Synchronous call — you inherit their latency and outage The caller waits. A missing timeout takes YOUR threads. Bulkheads keep payment slowness off the read pool. Order service Tomcat / virtualthread is waiting HTTP / gRPC connect + readtimeouts REQUIRED Inventory / PSP their p99 is nowyour p99 No timeout pool exhaustedwhole checkout dies Timeout + 503 fail closed on moneyfallback is a product call request slow Bulkhead Payment pool ≠ order-read pool. A dark PSP must not take every Tomcat thread. Resilience4j bulkhead / separate TaskExecutor. Retry only if the server op is idempotent. timeout first bulkhead fail closed $
Sync HTTP couples latency. A missing timeout takes *your* threads.
Asynchronous messaging — at-least-once, you make it idempotent Asynchronous messaging — at-least-once, you make it idempotent Accept and persist first. Publish after. Consumers scale alone. Exactly-once across vendors is a marketing word. Order API 201 after commitnot after consume Broker queue or pub/subpartition = orderId Inventory competingconsumers Notify email / push Analytics can lag Inbox table event_id PKbefore side effect DLQ after N failspoison message publish dedup poison Say this I ACK after persist + inbox insert, or I use the broker retry. I never assume global order — only per orderId partition. If the consumer is down, the customer already has a 201 and a poll/202 story. at-least-once inbox / dedup DLQ
Accept, persist, publish. Consumers scale independently. Assume at-least-once.
Dual-write vs transactional outbox Dual-write vs transactional outbox Publish-then-commit and commit-then-publish both lose. Write the business row and the outbox row in ONE commit. A relay publishes after. Wrong — two commits UPDATE orders SET PAID; COMMIT publish(OrderPaid) process dies here Ledger moved · fulfillment never started Right — one commit BEGIN orders row + outbox row COMMIT Outbox relay poll / CDCmark published Broker at-least-onceconsumer dedup Interview paragraph I will not 2PC the payment vendor and my database in 45 minutes. I use an outbox for OrderPaid and an inbox (event_id PK) on the consumer. Duplicates are expected. The loser I refuse is two captures or a paid order that nobody fulfills. dual-write dies same commit at-least-once
Write the order and the outbox row in one commit. A relay publishes after success.

Read the diagrams, then say: I start with one deployable. If I split, I inherit dual-write. Outbox + idempotent consumers is the spoken fix. I never hide a Kafka consumer behind a 200 that lied about payment.

Whiteboard in 60 seconds

  1. First picture: one app, one DB. Then “two teams / Black Friday.”
  2. Dual-write: commit then publish — process dies. Circle the outbox.
  3. Partition key = orderId. DLQ after N retries.
  4. Write at the top: “unacceptable: two charges / oversell.”

Sync vs async

InteractionWhenFailure mode
HTTP PaymentClient.chargeCustomer is waiting; you need the resultTimeout, retries, double charge
Event OrderPaidEmail, analytics, fulfillmentLost message, duplicate delivery
Orchestration sagaMulti-step reserve → pay → fulfillCompensating cancel

If the customer needs “paid or not” on the HTTP response, that path is synchronous or you accept 202 and poll. Do not hide a five-second Kafka consumer behind a 200 that lied.

Dual write is the core question

text

BEGIN
  UPDATE orders SET status = PAID
COMMIT
publish(OrderPaid)   // process dies

Payment ledger moved; fulfillment never started. Or the reverse if you publish first.

Outbox: insert outbox(event) in the same transaction as the order update. A publisher polls or tails the table and writes to the broker. At-least-once delivery → consumers must be idempotent (store event id).

Inbox / idempotent consumer: processed_events(event_id primary key) before side effects.

Change-data-capture is an implementation of outbox-ish publishing. Mention it; do not require Debezium by name unless they use it.

Avoid 2PC across payment vendor + your DB in a 45-minute interview unless they ask. Saga with explicit compensations (ReleaseInventory) is the usual spoken design.

Messaging patterns they name

  • Queue (competing consumers): fulfill this order once
  • Pub/sub: many readers of OrderPaid
  • DLQ: poison messages after N retries
  • Partition key: orderId so all events for one order stay ordered in Kafka
  • Request-reply over messaging: possible, usually worse than HTTP for checkout

Exactly-once across systems is a marketing phrase. In practice: at-least-once + idempotency + dedup keys.

API between services

Prefer coarse commands (ReserveStock) over chatty GET per SKU. Version contracts. A shared library of entities is how you couple deploys; share API types or an OpenAPI spec, not OrderEntity.

Interview questions

When would you split Order and Inventory?

Ownership, scale, or failure isolation — not nouns.

How do you avoid dual writes?

Outbox in the same transaction; idempotent consumers.

How do you keep order of events?

Partition by orderId; do not assume global order.

Sync call or event for payment?

If the HTTP response must include capture status, sync (or 202 + poll). Notify fulfillment with an event after commit.

Follow-up: “Inventory reserved, payment declined.” Compensating release, or reserve after payment (and discuss oversell vs extra latency). Say what you give up.

COMMON MISTAKE: Drawing Kafka in the middle of checkout without saying who owns the write or what the customer sees if the consumer is down.

INTERVIEW TIP: Write “unacceptable: two charges / oversell” at the top of the whiteboard. Every box should serve that sentence.

Resilience and idempotency12 min

Resilience and idempotency

Resilience and idempotency

In one sentence: Timeouts, bounded retries, and idempotency keys keep a flaky payment network from charging twice or hanging every Tomcat thread.

What is safe to retry

Retries are safe when the server operation is idempotent or you hold a key that makes it so. They are dangerous when POST /charges creates a new capture every time.

CallRetry?
GET /orders/{id}Yes (read)
PUT with full bodyYes if the server implements PUT correctly
POST /orders without keyNo — or only if you add a key
POST /payments with idempotency keyYes, same key
Compensating releaseInventoryYes, if release is idempotent

Timeout first. A retry without a timeout is how you pile threads. Connect timeout + read timeout on RestClient / WebClient. Circuit breaker (Resilience4j) opens when the payment provider is dark so you fail fast and shed load. Bulkhead isolates the payment pool from the order-read pool so a slow PSP does not take the whole JVM.

Backoff: exponential + jitter. Without jitter, all instances retry at once (thundering herd). Cap attempts (3 is a spoken default). After that, DLQ or a PAYMENT_PENDING state — not an infinite loop.

See it

Timeout, retry, circuit breaker, fallback Timeout, retry, circuit breaker, fallback Timeout first. Retry only idempotent calls with jitter. Open the breaker to protect YOUR pool. Fallback that lies is worse than 503. Caller checkoutthread Timeouts connect 200msread 800ms Retry ×3 exp backoff+ jitter Circuit breaker closed → open→ half-open probe Closed call dependency Open fail fast 503 Fallback cached quote orPAYMENT_PENDING Do not Retry POST /charges without a key (double capture). Retry without timeout (pile threads). Fallback charge(amount=0). Half-open that slams 100% of traffic — probe with one request. timeout 1st jitter fail fast
Retry with jitter, then a circuit breaker. Open fails fast. Fallback is a product decision.
Idempotent POST /orders Idempotent POST /orders Same key + same body replays the stored response. Same key + different body is 422. Persist the key in the SAME transaction as the order. Client retry timeout / 503same Idempotency-Keysame JSON body Lookup key unique store+ request hash HIT completed replay status + bodyno second order HIT in-flight 409 or waitdocument the policy HIT different hash 422 — key reusedfor another body MISS insert key + orderONE database TX new ! ConcurrentHashMap in prod dies on restartinvisible to the other instancenot in the order TX + unique (key) next to orders same commit as the rowreplay is a read of the stored responsethis is how Stripe-style keys work replay 201 conflict 422 same TX
Same Idempotency-Key + same body replays. Store the key with the order.

Read the diagrams, then say: Timeout first. Retry only idempotent calls. The breaker protects *my* thread pool when the PSP is dark. Fallback that lies (“charged $0”) is worse than a 503.

Whiteboard in 60 seconds

  1. Timeout numbers on the client. Then retry (3, exp + jitter). Then breaker.
  2. Table: GET yes / POST no unless key / PUT yes if implemented.
  3. Key store next to the order row. In-memory map = lab only.
  4. Fallback: cached quote or “payment unavailable” — never a silent success.

Idempotency on POST /orders

Client sends Idempotency-Key: 8f3c….

  1. Persist (key, requestHash, status, response) uniquely.
  2. Same key, same hash, completed → replay response.
  3. Same key, different hash → 422.
  4. Same key, in flight → 409 or wait, document it.

Store this next to the order in the same DB transaction. An in-memory ConcurrentHashMap is a lab stand-in; it dies on restart and does not work across instances.

Payment APIs (Stripe-style) already speak this language. Your adapter must forward the key, not invent a new random key on each retry.

Circuit breaker, retry, timeout — order them

text

timeout < retry budget < user-facing SLA
breaker wraps the client
bulkhead bounds the pool

If you retry three times with a 2s read timeout, you advertised a 6s+ failure. Say the budget.

Fallback: cached quote, or “payment unavailable, order parked.” Do not fallback to charge(amount=0) or a silent success. A fallback that lies is worse than a 503.

Graceful degradation

Read path: serve order history from a replica or cache if the primary is sick (stale is what you give up). Write path: do not take money if you cannot persist the order. Fail closed on money and inventory; fail open on recommendations.

Rate limit inbound (Bucket4j, gateway) so one client cannot exhaust the payment pool. Rate limit outbound so you do not DDoS your PSP.

Hedge and cancellation

If they go staff: hedged requests (send a second call after 100 ms) can improve p99 and double load. Cancel the slower one. Rarely your first checkout design.

Interview questions

How do you make POST /orders idempotent?

Key, unique store, replay, hash the body, same transaction as the order.

What do you retry?

Idempotent operations, with timeout, jitter, and a limit.

What does a circuit breaker add that retry does not?

Fail fast when the dependency is down; give it time to recover; protect your threads.

Why jitter?

Avoid synchronized retry storms.

Follow-up: “We retried and the customer was charged twice.” The payment call was not idempotent, or you generated a new key. Walk the logs with the same key.

COMMON MISTAKE: @Retry on a method that inserts an order and then charges, with no key. Each retry is a new world.

INTERVIEW TIP: Write the idempotency key on the sequence diagram before the arrows. Interviewers treat that as a senior habit.

Observability and performance11 min

Observability and performance

Observability and performance

In one sentence: On-call needs logs, metrics, and traces tied by a correlation ID; performance work starts with a measured bottleneck, usually SQL or a sync dependency, not GC flags.

The three questions at 3 a.m.

  1. Is checkout broken for everyone or one customer? (metrics, SLOs)
  2. Which dependency is slow or erroring? (traces)
  3. What happened to order ord_183? (logs with orderId + correlationId)

If you only have logs, you grep. If you only have metrics, you cannot explain one user. If you only have traces, you lack a pageable time series. You want all three.

See it

Logs, metrics, traces — one correlation ID Logs, metrics, traces — one correlation ID Metrics tell you everyone vs one user. Traces tell you which hop. Logs tell you order ord_183. You want all three. Request X-Correlation-Idor generate onepass downstream Spring Boot filter → MDCspan per hop Metrics RED on POST /orderslock retries Logs orderId + outcomeJSON fields Traces SQL vs PSPchild spans Dashboard / SLO 99.9% < 400ms edgeerror budget Alert customer SLOnot CPU > 80% alone 3 a.m. questions 1) Everyone or one customer? (metrics) 2) Which dependency? (trace) 3) What happened to ord_183? (logs). If you only have one pillar you cannot answer all three. corr. ID p99 SLI no secrets
One correlation ID through metrics, logs, and traces. Alert on customer-facing SLOs.
Order-processing architecture — lab vs story Order-processing architecture — lab vs story Thin sync path: accept, persist, idempotent create. Async path after commit: inventory, payment follow-up, notify. Correlation ID on every hop. Client Idempotency-Keycorr. ID LB /gateway TLS · WAF Order API LAB DTO · validateJPA · @Versionkey + order TX Orders DB ordersidempotency Outbox OrderCreated Broker + workers inventory · notifySTORY after commit write publish In scope for Lab 501 ./mvnw test green: controller, DTOs, validation, service TX, optimistic lock, idempotent create, one event, correlation filter. Out of scope for the 35 minutes Kafka cluster, Redis, multi-region, actual Stripe. You must still *say* where they would go. Unacceptable Two rows for one retry. Entity in the @RequestBody. Logging card numbers. Publishing before commit. lab = accept async after commit corr. ID
Thin sync accept path. Async workers after the outbox. Correlation ID on every hop.
Container deploy — immutable image, probes, compatible schema Container deploy — immutable image, probes, compatible schema Liveness = process is dead, restart it. Readiness = do not send traffic yet. A breaking column rename needs expand/contract across mixed versions. Source +tests CI gate Image immutabledigest Registry Orchestrator rolling replacemaxUnavailable Ready deps up · serve traffic Live dead → restart Config / secrets not baked in image CI Schema during rollout Old and new pods run together. Add a nullable column → deploy writers → backfill → constrain. Never rename a column in one step. A failed migrate + old pods = an incident, not a blog. immutable ready ≠ live expand/contract
Immutable image, readiness vs liveness, backward-compatible schema during rollout.

Read the diagrams, then say: correlationId + orderId + outcome on every log line. p99 of POST /orders is the SLI. I do not tune GC until a trace says the time is in GC.

Whiteboard in 60 seconds

  1. Three pillars, one correlationId line through all of them.
  2. RED on POST /orders. Alert on SLO, not “CPU > 80%.”
  3. Locate: metric → trace child (SQL vs payment) → fix.
  4. Cache only with invalidation. Never cache reserve without a consistency story.

Structured logs

JSON fields, not interpolated novels. Always: correlationId, orderId, customerId (careful with PII), latencyMs, outcome. One line per event. Do not log card numbers, tokens, or full payloads “just in case.”

MDC + a filter that reads X-Correlation-Id or generates one. Pass the same ID to payment HTTP headers and into events. That is how you stitch a retry to the original POST.

Log levels: INFO for accepted/rejected checkout, WARN for retries, ERROR for unhandled failures with the stack once. DEBUG is not a production strategy.

Metrics

RED: rate, errors, duration on POST /orders. USE: utilization, saturation, errors on the JVM and the pool. Custom: orders.created, payments.duplicate_key, inventory.optimistic_lock_retries.

SLI: p99 of checkout, success ratio. SLO: “99.9% of checkouts finish in 400 ms at the edge.” Error budget is how staff talk about whether you ship the next feature.

Do not alert on “CPU > 80%” alone. Alert on customer-facing SLOs and saturation that predicts them (pool exhausted, GC time, queue depth).

Traces

One span for the HTTP request, children for OrderService.create, SQL, PaymentClient.charge. Sampling: always sample errors and slow traces; sample the rest. OpenTelemetry is the name they expect. A trace without the correlation ID in logs is half a story.

Performance, interview order

  1. Define the number (p99 POST /orders, not “it feels slow”).
  2. Locate with a trace: controller, JPA, payment, serialization.
  3. Fix the obvious: N+1, missing index, unbounded findAll, no timeout, chatty chat between services.
  4. Cache only with an invalidation story (order:{id} TTL + evict on cancel).
  5. Scale out the stateless app; keep the write path honest (idempotency, locks).

Caching inventory “to go faster” without TTL/version is how you oversell. Caching order history is usually safer.

Pagination is a performance feature: never return 100k orders. Keyset pagination beats OFFSET 50000 on deep pages.

Security observability

Audit who cancelled an order. Do not log secrets. Rate-limit 401 storms. A sudden 500 spike after a deploy is a rollback candidate — say how you would confirm (version tag on the metric).

Interview questions

How do you find a slow checkout?

Metric → trace → SQL or HTTP child span → fix. Correlation ID for one order.

What do you put on every log line?

Correlation ID, order id, outcome. No secrets.

p99 vs average?

Averages hide the tail. Customers live in the tail.

Where would you cache?

Read-heavy, tolerate stale, known invalidation. Not the reserve path unless you can prove consistency.

Follow-up: “Logs are huge and useless.” Structured fields, sampling debug, drop payloads, index orderId.

COMMON MISTAKE: Adding Redis because “performance” before counting queries.

INTERVIEW TIP: Draw the three pillars and put correlationId through all of them. That sketch scores higher than a list of tool names (ELK, Prometheus, Jaeger) with no story.

Download the full lab (all code)

Spring Boot 3.3 / Java 21 Order API: controller, DTOs, JPA, idempotent create, async event, and Maven tests. Unzip, run ./mvnw test locally. BayLearn does not execute candidate code.

Download js-order-api-lab.zip

You will

  • Download js-order-api-lab.zip or read the source in this lesson
  • Run ./mvnw test locally — BayLearn does not execute your code
  • Optional: walk the three tables and one POST to SQL

Lab 501 — Order API overview10 min

Lab 501 — Order API overview

Module 5 — Live Coding + Order API Lab

Duration: 35 minutes · Kind: lab

This module is the write-and-build hour. You will write interview-sized Java, then run a Maven Order API on your machine. BayLearn does not compile or execute candidate code. If ./mvnw test is green locally, you are done with the mechanical bar.

Live coding (first 15 minutes)

Expect a prompt in the shape of the challenge bank:

  • Immutable Money with currency checks
  • equals/hashCode for an OrderId map key
  • Idempotency handler for POST /orders
  • Pagination or retry-with-backoff wrapper

Talk while you type. Name the contract, write the sad path first if it is cheap, then the happy path. Do not invent a framework.

Order API lab (20 minutes)

The lab lives in labs/order-service/. You build a production-style slice:

  • Controller + request/response DTOs (not entities)
  • Bean Validation and a consistent error body
  • JPA order + lines, optimistic locking on inventory or the order version
  • Idempotent create (Idempotency-Key header or key on the command)
  • One async event after the transaction (OrderCreated)
  • Structured logging with a correlation ID
  • Tests you can run with the Maven Wrapper

H2 is the default for local tests. A PostgreSQL profile exists for a closer-to-prod walkthrough. You do not need a remote database to finish the sprint.

What interviewers watch

They watchThey punish
DTO at the HTTP edgeEntity in the @RequestBody
Service owns @TransactionalTransaction on the controller
Idempotent createTwo rows for one retry
Version / constraint on stockBlind quantity = quantity - 1
Log orderId + correlationIdSystem.out and stack traces as product

How to demo

  1. ./mvnw test
  2. Show the idempotency test: same key, one order
  3. Show the optimistic-lock or constraint test
  4. Point at the event publication after commit (or outbox table)

Open the lab lesson. Optional: as-built tables and POST. Keep downloads/coding-challenges.md beside you.

COMMON MISTAKE: Spending the whole 35 minutes on package structure. Interviewers would rather see one correct POST and a test than empty hexagonal folders.

Lab pack README

Lab pack README

Java + Spring Boot Interview Sprint labs

The weekend lab is Lab 501 — Order API (`LAB-JS-501`).

It is a local Maven / Java 21 Spring Boot service. BayLearn does not compile or execute candidate code.

LabWhat you doSuccess
order-serviceBuild POST /orders with DTOs, validation, JPA, optimistic locking, idempotent create, one async event, and tests./mvnw test is green on your machine

Download the same tree as js-order-api-lab.zip from the sprint landing page, or clone labs/order-service/ from this repository. Tables and the POST walk are in order-service/docs/low-level-design.md (bonus).

Order API README

Order API README

Order API lab

BayLearn interview lab: a production-style Spring Boot 3.3 / Java 21 Order API.

Controllers expose DTOs only (never JPA entities). Persistence uses constructor-injected

services, optimistic locking, idempotent create, one async domain event, and a

correlation-id filter.

Prerequisites

  • JDK 21+ (java -version should report 21). If another JDK is first on PATH, set

JAVA_HOME to the JDK 21 home, for example:

export JAVA_HOME=$(/usr/libexec/java_home -v 21)

  • Network on first ./mvnw so the wrapper can download Maven 3.9.9 (and maven-wrapper.jar if it is missing)

Maven Wrapper

This lab ships mvnw, mvnw.cmd, and .mvn/wrapper/maven-wrapper.properties pointing at the

official Apache Maven Wrapper 3.3.2 and Maven 3.9.9.

The wrapper JAR is listed in the parent repo .gitignore. If

.mvn/wrapper/maven-wrapper.jar is absent, ./mvnw downloads it from:

https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar

bash

chmod +x ./mvnw
./mvnw -v

Run tests (H2, no Postgres)

bash

./mvnw test

Run the API locally (H2)

bash

./mvnw spring-boot:run
  • API: http://localhost:8080/api/v1/orders
  • Health: http://localhost:8080/actuator/health
  • H2 console (local only): http://localhost:8080/h2-console

JDBC URL jdbc:h2:mem:orders, user sa, blank password

Optional PostgreSQL profile

Tests never require Postgres. To run against Postgres locally:

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

Or the full stack:

bash

docker compose up --build

API sketch

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Replays the first response for the same key + body.
GET/api/v1/orders/{id}404 when missing
GET/api/v1/orders?page=0&size=20Newest first, max page size 100
PATCH/api/v1/orders/{id}/statusBody includes status + version for optimistic locking

Create example:

bash

curl -sS -X POST http://localhost:8080/api/v1/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: checkout-42' \
  -H 'X-Correlation-Id: demo-1' \
  -d '{
    "customerId": "11111111-1111-1111-1111-111111111111",
    "items": [
      { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
    ]
  }'

Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED from a non-terminal state.

Standard error JSON: { timestamp, status, code, message, correlationId, errors[] }.

Design notes

See docs/design-notes.md, docs/api-notes.md,

and docs/low-level-design.md (tables + one POST).

What this lab does not include

  • Resilience4j / circuit breakers
  • Secrets in source or images
  • Online compiler — run Maven on your machine

Lab walkthrough

Lab walkthrough

Order API lab

In one sentence: Build a thin, production-shaped POST /orders you can run with Maven on your laptop — DTOs, validation, JPA, optimistic locking, idempotency, one event, tests.

What you are building

The lab lives at labs/order-service/ (Java 21, Maven Wrapper). BayLearn will not compile this for you. Success is ./mvnw test on your machine.

See it

Order-processing architecture — lab vs story Order-processing architecture — lab vs story Thin sync path: accept, persist, idempotent create. Async path after commit: inventory, payment follow-up, notify. Correlation ID on every hop. Client Idempotency-Keycorr. ID LB /gateway TLS · WAF Order API LAB DTO · validateJPA · @Versionkey + order TX Orders DB ordersidempotency Outbox OrderCreated Broker + workers inventory · notifySTORY after commit write publish In scope for Lab 501 ./mvnw test green: controller, DTOs, validation, service TX, optimistic lock, idempotent create, one event, correlation filter. Out of scope for the 35 minutes Kafka cluster, Redis, multi-region, actual Stripe. You must still *say* where they would go. Unacceptable Two rows for one retry. Entity in the @RequestBody. Logging card numbers. Publishing before commit. lab = accept async after commit corr. ID
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Controller · Service · Repository Controller · Service · Repository HTTP stays in the controller. The unit of work and rules stay in the service. SQL stays in the repository. Entities never cross the HTTP edge. HTTP JSON bodyIdempotency-KeyX-Correlation-Id Controller validate DTOmap to commandmap status codes Service @Transactionalinvariantsports only Repository entityquery Database SQLconstraints DTO cmd entity ! return Order entity lazy lines explode after TXpassword hashes leakOSIV hides N+1 + return OrderResponse explicit fieldsfetch graph chosen for THIS use casecheckout needs lines; existence check does not DTO at edge TX on service no entity JSON
Controller takes DTOs. Service owns the transaction. Repository talks SQL.
Idempotent POST /orders Idempotent POST /orders Same key + same body replays the stored response. Same key + different body is 422. Persist the key in the SAME transaction as the order. Client retry timeout / 503same Idempotency-Keysame JSON body Lookup key unique store+ request hash HIT completed replay status + bodyno second order HIT in-flight 409 or waitdocument the policy HIT different hash 422 — key reusedfor another body MISS insert key + orderONE database TX new ! ConcurrentHashMap in prod dies on restartinvisible to the other instancenot in the order TX + unique (key) next to orders same commit as the rowreplay is a read of the stored responsethis is how Stripe-style keys work replay 201 conflict 422 same TX
Idempotency-Key is stored in the same transaction as the order.

Read the diagrams, then say: In 35 minutes I ship the accept path: DTO, validation, JPA, optimistic lock, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.

Minimum slice:

  1. POST /orders accepts a JSON command (customer, lines, optional currency).
  2. Bean Validation on the request; @ControllerAdvice for 400s and domain errors.
  3. OrderService is constructor-injected; it owns @Transactional.
  4. Persist Order + OrderLine. Do not return entities from the controller.
  5. Idempotent create via Idempotency-Key (or clientOrderId) stored uniquely.
  6. Reserve inventory with a @Version column or a conditional UPDATE … WHERE qty >= :need.
  7. After commit, publish OrderCreated (application event or outbox row).
  8. Log correlationId + orderId on accept and reject.
  9. Tests: validation, happy create, replayed key, inventory conflict.

H2 is enough. A postgres profile is there if you want a closer walkthrough. You do not need Kafka, Redis, or a cloud account to finish the sprint.

Whiteboard in 60 seconds

  1. CSR boxes. Entity never enters the controller.
  2. Key store + order row, one commit. Replay vs 422.
  3. @Version or UPDATE … WHERE qty >= 1 for reserve.
  4. After commit: OrderCreated. Correlation ID on the log line.

Code It (live-coding warm-up)

Before you open the lab, write one of these on a blank file, talking out loud:

  • Immutable Money (plus rejects mixed currencies)
  • OrderId equals/hashCode
  • A function that returns the cached response when the idempotency key hits

Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.

Build It (the service shape)

text

OrderController          DTO in/out, no logic
  → OrderService         unit of work, ports
      → OrderRepository
      → InventoryRepository
      → IdempotencyStore
      → OrderEvents       AFTER_COMMIT or outbox

Constructor injection only. Profiles for H2 vs PostgreSQL. application.yaml for timeouts and TTL — not hard-coded magic numbers in the service.

Event publication: @TransactionalEventListener(phase = AFTER_COMMIT) is acceptable for the lab. If you want the staff version, write an outbox table in the same transaction and a test that the row exists even if the listener is mocked.

Explain It (what you say in the mock)

“Retries with the same key return the original order. Inventory uses a version so two reserves cannot oversell in one instance; the unique key on the idempotency table saves us across retries. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”

Say what you give up: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two instances.

How to run

bash

cd labs/order-service
./mvnw test

If the wrapper is missing on a fresh checkout, use a local Maven 3.9+ with Java 21. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.

Interview questions while you demo

  • Why is the request a DTO?
  • Where is @Transactional and what rolls back?
  • What happens on a duplicate Idempotency-Key?
  • How do you prove you did not N+1 the list endpoint?
  • Why after-commit for the event?

COMMON MISTAKE: Perfect package names, zero tests. Interviewers would rather see one idempotency test than a hexagonal folder with empty ports.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column as the real correctness mechanisms, not the happy-path service method.

As-built design (bonus)

As-built design (bonus)

Lab 501 — As-built design (bonus)

Optional. Skip this if you already ran ./mvnw test and can explain replay vs 409. Use it when the interviewer asks “what’s in the database?” or “walk me through the POST.”

This page matches the code in the zip, not the longer production story. There is no inventory table and no outbox table in this lab.

See it

Lab 501 tables — as the code creates them Lab 501 tables — as the code creates them Three tables. Unique key stops a double insert. @Version stops a silent clobber. No inventory. No outbox. orders id UUID PK generated on persist customer_id indexed · not a users table status CREATED…SHIPPED / CANCELLED total_amount DECIMAL(19,2) · sum of lines version @Version starts at 0 · flush incrementsthis is the lock order_items id UUID PK order_id FK cascade + orphanRemovalowned by the order product_id no products table qty + unit_price DTO: qty ≥ 1, price ≥ 0.01EntityGraph on GET / list idempotency_keys idempotency_key PK header, 1–128 charsunique IS the primary key request_hash SHA-256 of JSON body response_status + body stored 201 + OrderResponseempty body = reservation Not in this lab no inventory rowno outbox row 3 tables version = lock key = PK
Three tables: orders (version lock), order_items, idempotency_keys (unique key). No inventory, no outbox.
POST /orders — one transaction, then after-commit POST /orders — one transaction, then after-commit Hash selects replay vs conflict. Unique insert is the reservation. Event fires after commit, in process. Inside OrderService.create · @Transactional 1. Hash body SHA-256 hexof JSON bytes 2. Lookup key hit + same hash→ replay stored JSON 3. Reserve key INSERT + flushunique loser reads 4. Insert aggregate orders + N linesversion = 0 5. Store 201 write responseonto the key row Replay same key + same hash201 + Location · no 2nd row Conflict same key + different hash409 IDEMPOTENCY_KEY_CONFLICT Missing key 400 MISSING_IDEMPOTENCY_KEYvalidation → 400 + field errors After commit — not a table OrderCreatedEvent @TransactionalEventListenerAFTER_COMMIT + @Asyncfailed listener cannot roll back Crash after COMMIT in-memory event is goneorder row is notthis is the outbox sentence PATCH …/status version in the body stale → 4092 writers at v=0 → 409legal transitions only one TX replay 201 409 ≠ 201
POST /orders: hash body → reserve key → insert order + lines → store 201 → event after commit.

Read the diagrams, then say: Three tables. The unique key stops a double insert. @Version stops a silent clobber on status. The event is after commit, in process — a crash can still lose it.

Tables (as Hibernate creates them)

orders — id UUID PK, customer_id (indexed), status, total_amount DECIMAL(19,2), created_at / updated_at, version BIGINT (@Version, starts at 0).

order_items — id UUID PK, order_id FK, product_id, quantity, unit_price. Cascade from the order. Loaded with @EntityGraph(attributePaths = "items") on findById and findAll. open-in-view=false.

idempotency_keys — idempotency_key VARCHAR(128) is the PK, request_hash SHA-256 hex of the JSON body, response_status, response_body (serialized OrderResponse), created_at.

The empty response_body row is the reservation. Two in-flight creates: saveAndFlush + unique violation → read the winner.

Full as-built spec — DDL, every header, validation, error codes, create steps, event executor, and the tests that lock it: low-level-design.md. HTTP shapes: api-notes.md.

One POST /api/v1/orders

Headers: Idempotency-Key (required, 1–128), optional X-Correlation-Id.

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{"customerId":"11111111-1111-1111-1111-111111111111","items":[{"productId":"22222222-2222-2222-2222-222222222222","quantity":2,"unitPrice":19.99}]}

One @Transactional on OrderService.create:

  1. Hash the body.
  2. Key exists + same hash → replay stored JSON (201 + Location).
  3. Key exists + different hash → 409 IDEMPOTENCY_KEY_CONFLICT.
  4. Miss → insert the key, insert orders + lines, write 201 onto the key.
  5. publishEvent(OrderCreatedEvent) inside the TX. Listener is AFTER_COMMIT + @Async.

Missing header → 400 MISSING_IDEMPOTENCY_KEY. Bean Validation → 400 VALIDATION_ERROR.

PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

Service rejects a stale version immediately. Hibernate still increments @Version on flush, so two writers who both read 0 produce 409 OPTIMISTIC_LOCK_CONFLICT (handler maps OptimisticLockingFailureException).

Legal: CREATED → CONFIRMED|CANCELLED, CONFIRMED → PROCESSING|CANCELLED, PROCESSING → SHIPPED|CANCELLED. Terminal: SHIPPED, CANCELLED.

Whiteboard in 60 seconds

  1. Three boxes: orders.version, order_items.order_id, idempotency_keys PK.
  2. POST arrow: hash → reserve key → insert aggregate → store response → after-commit event.
  3. Replay vs 409. PATCH + version vs last-write-wins.
  4. Stop. Do not draw Kafka.

What we left out on purpose

  • No inventory row. Conditional UPDATE … WHERE qty >= 1 is the next sentence, not a table here.
  • No outbox row. A crash after commit can lose OrderCreated. Outbox + inbox is the upgrade.
  • No Resilience4j, no Spring Security.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are what make the create correct. The happy-path service method is just the story that uses them.

Design notes

Design notes

Design notes (interview talking points)

Layering

  • Controller: HTTP mapping, Bean Validation, headers. No persistence, no business rules.
  • Service: @Transactional boundary, status machine, totals, idempotency, event publish.
  • Repository: Spring Data JPA only.
  • Mapper: entity ↔ DTO. Controllers never return Order / OrderItem.

Constructor injection everywhere. No field @Autowired.

Optimistic locking

Order.version is @Version. The client sends the version it last read on

PATCH …/status. Hibernate increments on each flush. A stale writer gets

ObjectOptimisticLockingFailureException, mapped to 409 OPTIMISTIC_LOCK_CONFLICT.

Why not last-write-wins? Two operators confirming vs cancelling the same order

must not silently clobber each other.

Idempotent create

Mobile clients retry POST after timeouts. The service persists

idempotency_key (unique), a SHA-256 of the request body, and the serialized

response. Replay is a read, not a second insert. A unique constraint plus a

DataIntegrityViolationException retry handles two in-flight requests with the

same key.

Same key, different body is a client bug → 409, not a second order.

The key is stored in the database, not an in-memory map, so two instances of

the service cannot both insert.

Async event

ApplicationEventPublisher publishes OrderCreatedEvent inside the create

transaction. The listener is @TransactionalEventListener(AFTER_COMMIT) +

@Async so a failed listener cannot roll back the order, and the work does not

sit on the request thread. MDC (correlationId) is copied onto the async

thread via a TaskDecorator.

This lab does not introduce a broker. In production the same event would become

an outbox row or a message.

Correlation ID

CorrelationIdFilter reads X-Correlation-Id or generates one, stores it in

MDC, and echoes the header. GlobalExceptionHandler copies it into the error

JSON so a 404 in logs, traces, and the client payload share one id.

Transactions and Open Session in View

spring.jpa.open-in-view=false. Lazy Order.items are loaded with

@EntityGraph on repository methods. Mapping happens inside the service

transaction.

@Transactional lives on the service, not the controller: the HTTP layer

should not hold a database connection while writing the response.

Column-level tables, the POST transaction, and PATCH …/status are in

low-level-design.md.

What we left out on purpose

  • Resilience4j — this lab is about API + persistence + retries of *this* service.
  • Spring Security / secrets — no credentials in images or YAML beyond local

Compose defaults overridden by env vars.

  • MapStruct / Lombok — explicit mapper and constructors are easier to talk through.

API notes

API notes

Order API notes

Base path: /api/v1. JSON in and out. Controllers never return JPA entities.

Resources

POST /api/v1/orders

Creates an order in CREATED. Requires header Idempotency-Key (1–128 chars).

Request:

json

{
  "customerId": "uuid",
  "items": [
    { "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }
  ]
}

Validation: customerId required; items not empty; each quantity >= 1;

unitPrice >= 0.01.

Response 201 with Location: /api/v1/orders/{id} and body:

json

{
  "id": "uuid",
  "customerId": "uuid",
  "status": "CREATED",
  "items": [{ "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }],
  "totalAmount": 10.00,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Idempotency: same key + same body replays the original 201 and body. Same key +

different body → 409 IDEMPOTENCY_KEY_CONFLICT. Missing key → 400

MISSING_IDEMPOTENCY_KEY.

GET /api/v1/orders/{id}

200 or 404 ORDER_NOT_FOUND.

GET /api/v1/orders

Query: page (default 0), size (default 20, max 100). Sorted by createdAt desc.

json

{
  "content": [],
  "page": 0,
  "size": 20,
  "totalElements": 0,
  "totalPages": 0,
  "first": true,
  "last": true
}
PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

version must match @Version on the row. Mismatch → 409 OPTIMISTIC_LOCK_CONFLICT.

Illegal transition → 409 ORDER_STATE_CONFLICT.

Allowed transitions:

  • CREATED → CONFIRMED, CANCELLED
  • CONFIRMED → PROCESSING, CANCELLED
  • PROCESSING → SHIPPED, CANCELLED
  • SHIPPED, CANCELLED are terminal

Errors

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 404,
  "code": "ORDER_NOT_FOUND",
  "message": "Order not found: …",
  "correlationId": "…",
  "errors": []
}

Validation failures use 400 VALIDATION_ERROR and populate errors with

{ "field", "message" }.

Send X-Correlation-Id to pin a request. The filter echoes it on the response

and puts it in MDC / error JSON. If omitted, the filter generates a UUID.

Low-level design

Low-level design

As-built design — Lab 501

This is the service as the repo ships it. Open Order.java,

IdempotencyRecord.java, OrderService.java, OrderController.java, and

GlobalExceptionHandler.java while you read.

It is not the staff story. There is no inventory table, no outbox table,

no broker, no Resilience4j, and no Spring Security.

HTTP shapes also live in api-notes.md. Interview *why* lives in

design-notes.md.

Runtime

Language / buildJava 21, Maven Wrapper 3.9.9
FrameworkSpring Boot 3.3, Spring Data JPA, Bean Validation
Default storeH2 in-memory jdbc:h2:mem:orders, MODE=PostgreSQL
Optional storePostgreSQL 16 via SPRING_PROFILES_ACTIVE=postgres
Schemaspring.jpa.hibernate.ddl-auto=update on both profiles
OSIVspring.jpa.open-in-view=false
ClockHibernate JDBC time_zone=UTC. Jackson writes ISO-8601 instants, not epoch millis
HTTPhttp://localhost:8080, base path /api/v1
Health/actuator/health (health, info; probes on; details never)
H2 console/h2-console on the default profile only (jdbc:h2:mem:orders, user sa, blank password)

Tests always use H2. They never start Postgres.

Layering

text

HTTP  OrderController     mapping, @Valid, headers. No persistence. No status rules.
  →   OrderService        @Transactional unit of work, idempotency, status machine, event publish
        → OrderRepository              Spring Data JPA + @EntityGraph("items")
        → IdempotencyRecordRepository  Spring Data JPA
        → OrderMapper                  entity ↔ DTO (explicit, no MapStruct)
        → ApplicationEventPublisher    OrderCreatedEvent
Advice  GlobalExceptionHandler         one error JSON shape
Filter  CorrelationIdFilter            X-Correlation-Id → MDC + response header

Constructor injection only. Controllers never return Order / OrderItem.

Data model

Three tables. Hibernate names them from @Table. There is no Flyway/Liquibase

script — ddl-auto=update creates them.

text

orders 1 ──< order_items
idempotency_keys   (no FK to orders — stores a serialized OrderResponse)
orders → Order

@Entity @Table(name = "orders", indexes = @Index(name = "idx_orders_customer", columnList = "customer_id"))

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKnoAssigned on persist
customer_id@Column(nullable = false)UUIDnoIndexed. No customers table
status@Enumerated(STRING) length 32VARCHAR(32)noSee status machine
total_amountprecision 19, scale 2DECIMAL(19,2)noqty * unit_price summed, HALF_UP 2 dp
created_atupdatable = falsetimestampno@PrePersist
updated_attimestampno@PrePersist and @PreUpdate
version@VersionBIGINTnoOptimistic lock. First persist → 0

@OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true) List<OrderItem> items.

Adding a line calls item.setOrder(this).

recalculateTotal() runs in the mapper before persist and in @PrePersist if

totalAmount is still null. There is no DB generated column.

There is no inventory column and no unique constraint on customer_id.

order_items → OrderItem

@Entity @Table(name = "order_items")

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKno
order_id@ManyToOne(LAZY) @JoinColumn(nullable = false)UUID FK → orders.idnoInverse of Order.items
product_id@Column(nullable = false)UUIDnoCatalog id. No products table
quantityintINTnoDTO enforces >= 1
unit_priceprecision 19, scale 2DECIMAL(19,2)noDTO enforces >= 0.01, ≤ 2 fraction digits

No unique (order_id, product_id) — two lines may share a product. No line-level

@Version.

idempotency_keys → IdempotencyRecord

@Entity @Table(name = "idempotency_keys")

ColumnMappingTypeNullNotes
idempotency_key@Id length 128VARCHAR(128) PKnoExact Idempotency-Key header. Unique is the PK
request_hashlength 64VARCHAR(64)noLowercase hex SHA-256 of the JSON request bytes
response_statusintINTnoWritten as 201
response_bodycolumnDefinition = TEXTTEXTnoJackson OrderResponse. "" means reserved, not complete
created_atupdatable = falsetimestampnoSet in the constructor

No FK to orders. Replay is a deserialize of response_body, not a second

SELECT of the order (the stored JSON already has id / version).

PK collision is the concurrency control for two in-flight creates with the same

key (saveAndFlush + DataIntegrityViolationException).

Approximate DDL (Postgres-shaped)

H2 MODE=PostgreSQL produces the same shapes. Types may differ slightly

(UUID vs BINARY vs varchar) under H2; treat this as the contract, not a

checked-in migration.

sql

CREATE TABLE orders (
  id            UUID PRIMARY KEY,
  customer_id   UUID           NOT NULL,
  status        VARCHAR(32)    NOT NULL,
  total_amount  NUMERIC(19, 2) NOT NULL,
  created_at    TIMESTAMP      NOT NULL,
  updated_at    TIMESTAMP      NOT NULL,
  version       BIGINT         NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

CREATE TABLE order_items (
  id          UUID PRIMARY KEY,
  order_id    UUID           NOT NULL REFERENCES orders (id),
  product_id  UUID           NOT NULL,
  quantity    INTEGER        NOT NULL,
  unit_price  NUMERIC(19, 2) NOT NULL
);

CREATE TABLE idempotency_keys (
  idempotency_key  VARCHAR(128) PRIMARY KEY,
  request_hash     VARCHAR(64)  NOT NULL,
  response_status  INTEGER      NOT NULL,
  response_body    TEXT         NOT NULL,
  created_at       TIMESTAMP    NOT NULL
);

Hibernate @Version UPDATE looks like:

sql

UPDATE orders
   SET status = ?, updated_at = ?, version = version + 1
 WHERE id = ? AND version = ?;
-- 0 rows → OptimisticLockingFailureException

HTTP surface

All JSON. All success bodies are DTOs. Dates are ISO-8601 UTC instants.

Headers on every request
HeaderRequiredBehavior
Content-Type: application/jsonwrite endpointsMissing/unreadable body → 400 MALFORMED_REQUEST
Idempotency-KeyPOST /orders only1–128 chars after trim. Blank/missing → 400 MISSING_IDEMPOTENCY_KEY
X-Correlation-IdnoEchoed on every response. If blank/absent, filter generates a UUID
POST /api/v1/orders → 201 Created

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{
  "customerId": "11111111-1111-1111-1111-111111111111",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ]
}

Response headers: Location: /api/v1/orders/{id}, X-Correlation-Id: …

json

{
  "id": "…",
  "customerId": "11111111-1111-1111-1111-111111111111",
  "status": "CREATED",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ],
  "totalAmount": 39.98,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Replay (same key + same body) is still 201 + the original Location and body.

It does not insert a second order. It does not publish a second OrderCreatedEvent.

GET /api/v1/orders/{id} → 200 or 404 ORDER_NOT_FOUND

Same OrderResponse as create. Items come from @EntityGraph(attributePaths = "items")

on OrderRepository.findById. Mapping runs inside @Transactional(readOnly = true).

Bad UUID in the path → 400 VALIDATION_ERROR (MethodArgumentTypeMismatch).

GET /api/v1/orders?page=0&size=20 → 200
QueryDefaultConstraint
page0@Min(0)
size20@Min(1) @Max(100)

Sort: createdAt DESC. findAll(Pageable) also uses the items entity graph, so

a page of N orders is not 1 + N line queries.

json

{
  "content": [ "OrderResponse…" ],
  "page": 0,
  "size": 20,
  "totalElements": 1,
  "totalPages": 1,
  "first": true,
  "last": true
}

There is no customerId filter in this lab.

PATCH /api/v1/orders/{id}/status → 200

json

{ "status": "CONFIRMED", "version": 0 }

Both fields required. Success body is OrderResponse with version incremented

(0 → 1 on the first confirm). No Idempotency-Key on PATCH.

Validation (request DTO)

CreateOrderRequest:

FieldRules
customerId@NotNull — "customerId is required"
items@NotEmpty @Valid — "items must not be empty"

OrderItemRequest:

FieldRules
productId@NotNull
quantity@NotNull @Min(1)
unitPrice@NotNull @DecimalMin("0.01") @Digits(integer=17, fraction=2)

UpdateOrderStatusRequest:

FieldRules
status@NotNull — must be an OrderStatus enum name
version@NotNull

Idempotency-Key header: @NotBlank @Size(max = 128).

Failures → 400 VALIDATION_ERROR, errors: [{ "field", "message" }].

Error catalog

Every error body:

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 409,
  "code": "IDEMPOTENCY_KEY_CONFLICT",
  "message": "…",
  "correlationId": "demo-1",
  "errors": []
}

correlationId is the MDC value from the filter. If MDC is empty, the handler

generates a UUID so the client still gets one.

HTTPcodeWhen
400MISSING_IDEMPOTENCY_KEYPOST without Idempotency-Key
400MISSING_HEADERany other required header missing
400VALIDATION_ERRORBean Validation, constraint violation, or bad path/query type
400MALFORMED_REQUESTunreadable JSON
404ORDER_NOT_FOUNDunknown order id
409IDEMPOTENCY_KEY_CONFLICTsame key, different SHA-256 body
409OPTIMISTIC_LOCK_CONFLICTPATCH version mismatch, or Hibernate OptimisticLockingFailureException on flush
409ORDER_STATE_CONFLICTillegal status transition
500INTERNAL_ERRORanything else (message is generic; stack goes to logs only)

Domain exceptions log warn with code. Unhandled exceptions log error.

Create algorithm (OrderService.create)

One @Transactional (default REQUIRED, read-write).

  1. Hash. ObjectMapper.writeValueAsBytes(request) then SHA-256 hex

(HexFormat). The hash is of the parsed DTO as re-serialized JSON, not

the raw request string. Extra unknown JSON fields are dropped by Jackson

before the hash. Key order in the stored DTO follows the record components.

  1. Lookup idempotency_keys by PK.

- Hit + request_hash matches → deserialize response_body → return

(replay). No new order. No new event.

- Hit + hash differs → 409 IDEMPOTENCY_KEY_CONFLICT.

  1. Reserve. saveAndFlush a row (key, hash, 201, "").

- Unique violation → findById the winner. If that row now has a body,

replay (or conflict on hash). If it is still empty, the winner is still

inserting — the loser treats a completed body on the next read.

  1. Aggregate. OrderMapper.toNewEntity: status CREATED, add lines, recalculateTotal().
  2. `orderRepository.save`. INSERT orders (version = 0) and INSERT each

order_items row in the same persistence context.

  1. Map to `OrderResponse` (needs generated id + version).
  2. `reservation.complete(201, json)` — UPDATE the key row with the serialized

response. Still the same transaction.

  1. `publishEvent(new OrderCreatedEvent(orderId, customerId))` — recorded

*inside* the transaction. Delivery is after commit (below).

  1. Log order.create.completed orderId=… totalAmount=….
  2. Controller wraps the DTO in 201 + Location.

If any step throws before commit, the reserved key row rolls back. A retry with

the same key starts clean.

Logs on the happy path: order.create.started (customerId, itemCount),

order.create.completed (orderId, totalAmount). Replay logs

order.create.replayed.

Status machine + optimistic lock (updateStatus)

text

CREATED     → CONFIRMED, CANCELLED
CONFIRMED   → PROCESSING, CANCELLED
PROCESSING  → SHIPPED, CANCELLED
SHIPPED     → (none)
CANCELLED   → (none)

OrderStatus.canTransitionTo is an EnumMap. Same-status PATCH is illegal

(CREATED → CREATED is a 409 ORDER_STATE_CONFLICT).

Locking is two layers:

  1. Service: if (!request.version().equals(order.getVersion())) →

OptimisticLockConflictException (409, message includes order id and

expected version).

  1. Hibernate: UPDATE … WHERE id=? AND version=?. Two writers who both read

version=0 and both pass step 1: the second flush throws

OptimisticLockingFailureException, mapped to the same code

OPTIMISTIC_LOCK_CONFLICT (generic message: *"The order was modified by

another request"*).

PATCH is not idempotent. A retry with the old version after a success is a

409, not a replay.

Log: order.status.updated orderId=… from=… to=… version=….

Persistence / fetch plan

CallRepositoryGraphTX
createsave(Order)cascade persist itemsread-write
getByIdfindByIditemsread-only
listfindAll(Pageable)itemsread-only
updateStatusfindById then saveitemsread-write

open-in-view=false means a lazy items touch after the service method

returns would throw. The graph + mapper-inside-the-TX is what makes GET/list

safe. That is the N+1 answer for this lab: entity graph, not EAGER on the

@OneToMany.

Events

OrderCreatedEvent(orderId, customerId, occurredAt=now) is a Java record, not a

row.

Listener OrderCreatedEventListener:

  • @TransactionalEventListener(phase = AFTER_COMMIT) — a throw in the listener

cannot roll back the order.

  • @Async("orderEventExecutor") — does not sit on the Tomcat thread.
  • Body: one info log order.event.created orderId=… customerId=… occurredAt=….

No HTTP, no second DB write.

Executor orderEventExecutor: core 2, max 4, queue 100, prefix order-event-,

MdcTaskDecorator copies correlationId onto the async thread.

Loss mode: process crash after COMMIT and before the listener runs. The

order row is durable. The in-memory event is gone. The interview upgrade is an

outbox row in the same create transaction plus a relay. That table is not

in this repo.

Correlation ID

CorrelationIdFilter at Ordered.HIGHEST_PRECEDENCE:

  1. Read X-Correlation-Id. Blank/absent → UUID.randomUUID().
  2. MDC.put("correlationId", …).
  3. response.setHeader("X-Correlation-Id", …).
  4. finally MDC.remove.

Console pattern:

text

%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} level=%-5level correlationId=%X{correlationId} logger=%logger{36} msg=%msg%n

Error JSON reuses the same id. The async listener keeps it via the task

decorator.

Transactions (rules you say out loud)

  • @Transactional is on the service, never the controller — the HTTP layer

must not hold a JDBC connection while writing the response.

  • Create, reserve-key, order insert, and key-complete are one commit.
  • The event is registered before commit and delivered after.
  • Read methods are readOnly = true.
  • OSIV is off.

Optional Postgres

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

or docker compose up --build. Credentials come from env

(SPRING_DATASOURCE_URL / USERNAME / PASSWORD). Compose defaults

orders / orders / orders are local only. Same entities, same

ddl-auto=update. H2 console is disabled on this profile.

Tests that lock this contract

TestWhat it proves
OrderApiITcreate → GET → list → PATCH confirm (version 0→1) → stale PATCH 409 OPTIMISTIC_LOCK_CONFLICT; X-Correlation-Id echoed
OrderIdempotencyITsame key + body → one order row, one key row, one OrderCreatedEvent; same key + different body → 409
OrderOptimisticLockingTest@Version increment / conflict
OrderValidationTest / OrderControllerTestmissing key, empty items, bad qty/price
OrderCreatedEventITlistener after commit
OrderStatusTestlegal / illegal transitions
GlobalExceptionHandlerTesterror JSON shape

./mvnw test is the lab bar. BayLearn does not run these.

What we left out on purpose

MissingWhyWhat you say next
inventory35-minute accept pathUPDATE inventory SET qty = qty - :n WHERE sku = :sku AND qty >= :n
outboxin-process event is enough to *talk* AFTER_COMMITsame TX as orders + relay; consumer inbox PK
customers / productsids onlythose are other services
Authn / secretsnot the labno credentials in images or YAML beyond local Compose
Resilience4jretries of *this* POST are the idempotency keytimeout + breaker on a *downstream* charge
Idempotent PATCHstatus changes are not replaysclient must send the version it last read

Say this: the unique key and the version column are the correctness. The

happy-path service method is just the story that uses them.

Lab 501 — Architecture5 min

Lab 501 — Architecture

Order API lab

In one sentence: Build a thin, production-shaped POST /orders you can run with Maven on your laptop — DTOs, validation, JPA, optimistic locking, idempotency, one event, tests.

What you are building

The lab lives at labs/order-service/ (Java 21, Maven Wrapper). BayLearn will not compile this for you. Success is ./mvnw test on your machine.

See it

Order-processing architecture — lab vs story Order-processing architecture — lab vs story Thin sync path: accept, persist, idempotent create. Async path after commit: inventory, payment follow-up, notify. Correlation ID on every hop. Client Idempotency-Keycorr. ID LB /gateway TLS · WAF Order API LAB DTO · validateJPA · @Versionkey + order TX Orders DB ordersidempotency Outbox OrderCreated Broker + workers inventory · notifySTORY after commit write publish In scope for Lab 501 ./mvnw test green: controller, DTOs, validation, service TX, optimistic lock, idempotent create, one event, correlation filter. Out of scope for the 35 minutes Kafka cluster, Redis, multi-region, actual Stripe. You must still *say* where they would go. Unacceptable Two rows for one retry. Entity in the @RequestBody. Logging card numbers. Publishing before commit. lab = accept async after commit corr. ID
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Controller · Service · Repository Controller · Service · Repository HTTP stays in the controller. The unit of work and rules stay in the service. SQL stays in the repository. Entities never cross the HTTP edge. HTTP JSON bodyIdempotency-KeyX-Correlation-Id Controller validate DTOmap to commandmap status codes Service @Transactionalinvariantsports only Repository entityquery Database SQLconstraints DTO cmd entity ! return Order entity lazy lines explode after TXpassword hashes leakOSIV hides N+1 + return OrderResponse explicit fieldsfetch graph chosen for THIS use casecheckout needs lines; existence check does not DTO at edge TX on service no entity JSON
Controller takes DTOs. Service owns the transaction. Repository talks SQL.
Idempotent POST /orders Idempotent POST /orders Same key + same body replays the stored response. Same key + different body is 422. Persist the key in the SAME transaction as the order. Client retry timeout / 503same Idempotency-Keysame JSON body Lookup key unique store+ request hash HIT completed replay status + bodyno second order HIT in-flight 409 or waitdocument the policy HIT different hash 422 — key reusedfor another body MISS insert key + orderONE database TX new ! ConcurrentHashMap in prod dies on restartinvisible to the other instancenot in the order TX + unique (key) next to orders same commit as the rowreplay is a read of the stored responsethis is how Stripe-style keys work replay 201 conflict 422 same TX
Idempotency-Key is stored in the same transaction as the order.

Read the diagrams, then say: In 35 minutes I ship the accept path: DTO, validation, JPA, optimistic lock, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.

Minimum slice:

  1. POST /orders accepts a JSON command (customer, lines, optional currency).
  2. Bean Validation on the request; @ControllerAdvice for 400s and domain errors.
  3. OrderService is constructor-injected; it owns @Transactional.
  4. Persist Order + OrderLine. Do not return entities from the controller.
  5. Idempotent create via Idempotency-Key (or clientOrderId) stored uniquely.
  6. Reserve inventory with a @Version column or a conditional UPDATE … WHERE qty >= :need.
  7. After commit, publish OrderCreated (application event or outbox row).
  8. Log correlationId + orderId on accept and reject.
  9. Tests: validation, happy create, replayed key, inventory conflict.

H2 is enough. A postgres profile is there if you want a closer walkthrough. You do not need Kafka, Redis, or a cloud account to finish the sprint.

Whiteboard in 60 seconds

  1. CSR boxes. Entity never enters the controller.
  2. Key store + order row, one commit. Replay vs 422.
  3. @Version or UPDATE … WHERE qty >= 1 for reserve.
  4. After commit: OrderCreated. Correlation ID on the log line.

Code It (live-coding warm-up)

Before you open the lab, write one of these on a blank file, talking out loud:

  • Immutable Money (plus rejects mixed currencies)
  • OrderId equals/hashCode
  • A function that returns the cached response when the idempotency key hits

Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.

Build It (the service shape)

text

OrderController          DTO in/out, no logic
  → OrderService         unit of work, ports
      → OrderRepository
      → InventoryRepository
      → IdempotencyStore
      → OrderEvents       AFTER_COMMIT or outbox

Constructor injection only. Profiles for H2 vs PostgreSQL. application.yaml for timeouts and TTL — not hard-coded magic numbers in the service.

Event publication: @TransactionalEventListener(phase = AFTER_COMMIT) is acceptable for the lab. If you want the staff version, write an outbox table in the same transaction and a test that the row exists even if the listener is mocked.

Explain It (what you say in the mock)

“Retries with the same key return the original order. Inventory uses a version so two reserves cannot oversell in one instance; the unique key on the idempotency table saves us across retries. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”

Say what you give up: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two instances.

How to run

bash

cd labs/order-service
./mvnw test

If the wrapper is missing on a fresh checkout, use a local Maven 3.9+ with Java 21. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.

Interview questions while you demo

  • Why is the request a DTO?
  • Where is @Transactional and what rolls back?
  • What happens on a duplicate Idempotency-Key?
  • How do you prove you did not N+1 the list endpoint?
  • Why after-commit for the event?

COMMON MISTAKE: Perfect package names, zero tests. Interviewers would rather see one idempotency test than a hexagonal folder with empty ports.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column as the real correctness mechanisms, not the happy-path service method.

Design notes

Design notes

Design notes (interview talking points)

Layering

  • Controller: HTTP mapping, Bean Validation, headers. No persistence, no business rules.
  • Service: @Transactional boundary, status machine, totals, idempotency, event publish.
  • Repository: Spring Data JPA only.
  • Mapper: entity ↔ DTO. Controllers never return Order / OrderItem.

Constructor injection everywhere. No field @Autowired.

Optimistic locking

Order.version is @Version. The client sends the version it last read on

PATCH …/status. Hibernate increments on each flush. A stale writer gets

ObjectOptimisticLockingFailureException, mapped to 409 OPTIMISTIC_LOCK_CONFLICT.

Why not last-write-wins? Two operators confirming vs cancelling the same order

must not silently clobber each other.

Idempotent create

Mobile clients retry POST after timeouts. The service persists

idempotency_key (unique), a SHA-256 of the request body, and the serialized

response. Replay is a read, not a second insert. A unique constraint plus a

DataIntegrityViolationException retry handles two in-flight requests with the

same key.

Same key, different body is a client bug → 409, not a second order.

The key is stored in the database, not an in-memory map, so two instances of

the service cannot both insert.

Async event

ApplicationEventPublisher publishes OrderCreatedEvent inside the create

transaction. The listener is @TransactionalEventListener(AFTER_COMMIT) +

@Async so a failed listener cannot roll back the order, and the work does not

sit on the request thread. MDC (correlationId) is copied onto the async

thread via a TaskDecorator.

This lab does not introduce a broker. In production the same event would become

an outbox row or a message.

Correlation ID

CorrelationIdFilter reads X-Correlation-Id or generates one, stores it in

MDC, and echoes the header. GlobalExceptionHandler copies it into the error

JSON so a 404 in logs, traces, and the client payload share one id.

Transactions and Open Session in View

spring.jpa.open-in-view=false. Lazy Order.items are loaded with

@EntityGraph on repository methods. Mapping happens inside the service

transaction.

@Transactional lives on the service, not the controller: the HTTP layer

should not hold a database connection while writing the response.

Column-level tables, the POST transaction, and PATCH …/status are in

low-level-design.md.

What we left out on purpose

  • Resilience4j — this lab is about API + persistence + retries of *this* service.
  • Spring Security / secrets — no credentials in images or YAML beyond local

Compose defaults overridden by env vars.

  • MapStruct / Lombok — explicit mapper and constructors are easier to talk through.

API notes

API notes

Order API notes

Base path: /api/v1. JSON in and out. Controllers never return JPA entities.

Resources

POST /api/v1/orders

Creates an order in CREATED. Requires header Idempotency-Key (1–128 chars).

Request:

json

{
  "customerId": "uuid",
  "items": [
    { "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }
  ]
}

Validation: customerId required; items not empty; each quantity >= 1;

unitPrice >= 0.01.

Response 201 with Location: /api/v1/orders/{id} and body:

json

{
  "id": "uuid",
  "customerId": "uuid",
  "status": "CREATED",
  "items": [{ "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }],
  "totalAmount": 10.00,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Idempotency: same key + same body replays the original 201 and body. Same key +

different body → 409 IDEMPOTENCY_KEY_CONFLICT. Missing key → 400

MISSING_IDEMPOTENCY_KEY.

GET /api/v1/orders/{id}

200 or 404 ORDER_NOT_FOUND.

GET /api/v1/orders

Query: page (default 0), size (default 20, max 100). Sorted by createdAt desc.

json

{
  "content": [],
  "page": 0,
  "size": 20,
  "totalElements": 0,
  "totalPages": 0,
  "first": true,
  "last": true
}
PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

version must match @Version on the row. Mismatch → 409 OPTIMISTIC_LOCK_CONFLICT.

Illegal transition → 409 ORDER_STATE_CONFLICT.

Allowed transitions:

  • CREATED → CONFIRMED, CANCELLED
  • CONFIRMED → PROCESSING, CANCELLED
  • PROCESSING → SHIPPED, CANCELLED
  • SHIPPED, CANCELLED are terminal

Errors

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 404,
  "code": "ORDER_NOT_FOUND",
  "message": "Order not found: …",
  "correlationId": "…",
  "errors": []
}

Validation failures use 400 VALIDATION_ERROR and populate errors with

{ "field", "message" }.

Send X-Correlation-Id to pin a request. The filter echoes it on the response

and puts it in MDC / error JSON. If omitted, the filter generates a UUID.

Lab 501 — Build the Order API (LAB-JS-501)20 min

Lab 501 — Build the Order API (LAB-JS-501)

Order API lab

BayLearn interview lab: a production-style Spring Boot 3.3 / Java 21 Order API.

Controllers expose DTOs only (never JPA entities). Persistence uses constructor-injected

services, optimistic locking, idempotent create, one async domain event, and a

correlation-id filter.

Prerequisites

  • JDK 21+ (java -version should report 21). If another JDK is first on PATH, set

JAVA_HOME to the JDK 21 home, for example:

export JAVA_HOME=$(/usr/libexec/java_home -v 21)

  • Network on first ./mvnw so the wrapper can download Maven 3.9.9 (and maven-wrapper.jar if it is missing)

Maven Wrapper

This lab ships mvnw, mvnw.cmd, and .mvn/wrapper/maven-wrapper.properties pointing at the

official Apache Maven Wrapper 3.3.2 and Maven 3.9.9.

The wrapper JAR is listed in the parent repo .gitignore. If

.mvn/wrapper/maven-wrapper.jar is absent, ./mvnw downloads it from:

https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar

bash

chmod +x ./mvnw
./mvnw -v

Run tests (H2, no Postgres)

bash

./mvnw test

Run the API locally (H2)

bash

./mvnw spring-boot:run
  • API: http://localhost:8080/api/v1/orders
  • Health: http://localhost:8080/actuator/health
  • H2 console (local only): http://localhost:8080/h2-console

JDBC URL jdbc:h2:mem:orders, user sa, blank password

Optional PostgreSQL profile

Tests never require Postgres. To run against Postgres locally:

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

Or the full stack:

bash

docker compose up --build

API sketch

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Replays the first response for the same key + body.
GET/api/v1/orders/{id}404 when missing
GET/api/v1/orders?page=0&size=20Newest first, max page size 100
PATCH/api/v1/orders/{id}/statusBody includes status + version for optimistic locking

Create example:

bash

curl -sS -X POST http://localhost:8080/api/v1/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: checkout-42' \
  -H 'X-Correlation-Id: demo-1' \
  -d '{
    "customerId": "11111111-1111-1111-1111-111111111111",
    "items": [
      { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
    ]
  }'

Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED from a non-terminal state.

Standard error JSON: { timestamp, status, code, message, correlationId, errors[] }.

Design notes

See docs/design-notes.md, docs/api-notes.md,

and docs/low-level-design.md (tables + one POST).

What this lab does not include

  • Resilience4j / circuit breakers
  • Secrets in source or images
  • Online compiler — run Maven on your machine

Lab pack README

Lab pack README

Java + Spring Boot Interview Sprint labs

The weekend lab is Lab 501 — Order API (`LAB-JS-501`).

It is a local Maven / Java 21 Spring Boot service. BayLearn does not compile or execute candidate code.

LabWhat you doSuccess
order-serviceBuild POST /orders with DTOs, validation, JPA, optimistic locking, idempotent create, one async event, and tests./mvnw test is green on your machine

Download the same tree as js-order-api-lab.zip from the sprint landing page, or clone labs/order-service/ from this repository. Tables and the POST walk are in order-service/docs/low-level-design.md (bonus).

Order API README

Order API README

Order API lab

BayLearn interview lab: a production-style Spring Boot 3.3 / Java 21 Order API.

Controllers expose DTOs only (never JPA entities). Persistence uses constructor-injected

services, optimistic locking, idempotent create, one async domain event, and a

correlation-id filter.

Prerequisites

  • JDK 21+ (java -version should report 21). If another JDK is first on PATH, set

JAVA_HOME to the JDK 21 home, for example:

export JAVA_HOME=$(/usr/libexec/java_home -v 21)

  • Network on first ./mvnw so the wrapper can download Maven 3.9.9 (and maven-wrapper.jar if it is missing)

Maven Wrapper

This lab ships mvnw, mvnw.cmd, and .mvn/wrapper/maven-wrapper.properties pointing at the

official Apache Maven Wrapper 3.3.2 and Maven 3.9.9.

The wrapper JAR is listed in the parent repo .gitignore. If

.mvn/wrapper/maven-wrapper.jar is absent, ./mvnw downloads it from:

https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar

bash

chmod +x ./mvnw
./mvnw -v

Run tests (H2, no Postgres)

bash

./mvnw test

Run the API locally (H2)

bash

./mvnw spring-boot:run
  • API: http://localhost:8080/api/v1/orders
  • Health: http://localhost:8080/actuator/health
  • H2 console (local only): http://localhost:8080/h2-console

JDBC URL jdbc:h2:mem:orders, user sa, blank password

Optional PostgreSQL profile

Tests never require Postgres. To run against Postgres locally:

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

Or the full stack:

bash

docker compose up --build

API sketch

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Replays the first response for the same key + body.
GET/api/v1/orders/{id}404 when missing
GET/api/v1/orders?page=0&size=20Newest first, max page size 100
PATCH/api/v1/orders/{id}/statusBody includes status + version for optimistic locking

Create example:

bash

curl -sS -X POST http://localhost:8080/api/v1/orders \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: checkout-42' \
  -H 'X-Correlation-Id: demo-1' \
  -d '{
    "customerId": "11111111-1111-1111-1111-111111111111",
    "items": [
      { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
    ]
  }'

Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED from a non-terminal state.

Standard error JSON: { timestamp, status, code, message, correlationId, errors[] }.

Design notes

See docs/design-notes.md, docs/api-notes.md,

and docs/low-level-design.md (tables + one POST).

What this lab does not include

  • Resilience4j / circuit breakers
  • Secrets in source or images
  • Online compiler — run Maven on your machine

Lab walkthrough

Lab walkthrough

Order API lab

In one sentence: Build a thin, production-shaped POST /orders you can run with Maven on your laptop — DTOs, validation, JPA, optimistic locking, idempotency, one event, tests.

What you are building

The lab lives at labs/order-service/ (Java 21, Maven Wrapper). BayLearn will not compile this for you. Success is ./mvnw test on your machine.

See it

Order-processing architecture — lab vs story Order-processing architecture — lab vs story Thin sync path: accept, persist, idempotent create. Async path after commit: inventory, payment follow-up, notify. Correlation ID on every hop. Client Idempotency-Keycorr. ID LB /gateway TLS · WAF Order API LAB DTO · validateJPA · @Versionkey + order TX Orders DB ordersidempotency Outbox OrderCreated Broker + workers inventory · notifySTORY after commit write publish In scope for Lab 501 ./mvnw test green: controller, DTOs, validation, service TX, optimistic lock, idempotent create, one event, correlation filter. Out of scope for the 35 minutes Kafka cluster, Redis, multi-region, actual Stripe. You must still *say* where they would go. Unacceptable Two rows for one retry. Entity in the @RequestBody. Logging card numbers. Publishing before commit. lab = accept async after commit corr. ID
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Controller · Service · Repository Controller · Service · Repository HTTP stays in the controller. The unit of work and rules stay in the service. SQL stays in the repository. Entities never cross the HTTP edge. HTTP JSON bodyIdempotency-KeyX-Correlation-Id Controller validate DTOmap to commandmap status codes Service @Transactionalinvariantsports only Repository entityquery Database SQLconstraints DTO cmd entity ! return Order entity lazy lines explode after TXpassword hashes leakOSIV hides N+1 + return OrderResponse explicit fieldsfetch graph chosen for THIS use casecheckout needs lines; existence check does not DTO at edge TX on service no entity JSON
Controller takes DTOs. Service owns the transaction. Repository talks SQL.
Idempotent POST /orders Idempotent POST /orders Same key + same body replays the stored response. Same key + different body is 422. Persist the key in the SAME transaction as the order. Client retry timeout / 503same Idempotency-Keysame JSON body Lookup key unique store+ request hash HIT completed replay status + bodyno second order HIT in-flight 409 or waitdocument the policy HIT different hash 422 — key reusedfor another body MISS insert key + orderONE database TX new ! ConcurrentHashMap in prod dies on restartinvisible to the other instancenot in the order TX + unique (key) next to orders same commit as the rowreplay is a read of the stored responsethis is how Stripe-style keys work replay 201 conflict 422 same TX
Idempotency-Key is stored in the same transaction as the order.

Read the diagrams, then say: In 35 minutes I ship the accept path: DTO, validation, JPA, optimistic lock, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.

Minimum slice:

  1. POST /orders accepts a JSON command (customer, lines, optional currency).
  2. Bean Validation on the request; @ControllerAdvice for 400s and domain errors.
  3. OrderService is constructor-injected; it owns @Transactional.
  4. Persist Order + OrderLine. Do not return entities from the controller.
  5. Idempotent create via Idempotency-Key (or clientOrderId) stored uniquely.
  6. Reserve inventory with a @Version column or a conditional UPDATE … WHERE qty >= :need.
  7. After commit, publish OrderCreated (application event or outbox row).
  8. Log correlationId + orderId on accept and reject.
  9. Tests: validation, happy create, replayed key, inventory conflict.

H2 is enough. A postgres profile is there if you want a closer walkthrough. You do not need Kafka, Redis, or a cloud account to finish the sprint.

Whiteboard in 60 seconds

  1. CSR boxes. Entity never enters the controller.
  2. Key store + order row, one commit. Replay vs 422.
  3. @Version or UPDATE … WHERE qty >= 1 for reserve.
  4. After commit: OrderCreated. Correlation ID on the log line.

Code It (live-coding warm-up)

Before you open the lab, write one of these on a blank file, talking out loud:

  • Immutable Money (plus rejects mixed currencies)
  • OrderId equals/hashCode
  • A function that returns the cached response when the idempotency key hits

Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.

Build It (the service shape)

text

OrderController          DTO in/out, no logic
  → OrderService         unit of work, ports
      → OrderRepository
      → InventoryRepository
      → IdempotencyStore
      → OrderEvents       AFTER_COMMIT or outbox

Constructor injection only. Profiles for H2 vs PostgreSQL. application.yaml for timeouts and TTL — not hard-coded magic numbers in the service.

Event publication: @TransactionalEventListener(phase = AFTER_COMMIT) is acceptable for the lab. If you want the staff version, write an outbox table in the same transaction and a test that the row exists even if the listener is mocked.

Explain It (what you say in the mock)

“Retries with the same key return the original order. Inventory uses a version so two reserves cannot oversell in one instance; the unique key on the idempotency table saves us across retries. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”

Say what you give up: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two instances.

How to run

bash

cd labs/order-service
./mvnw test

If the wrapper is missing on a fresh checkout, use a local Maven 3.9+ with Java 21. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.

Interview questions while you demo

  • Why is the request a DTO?
  • Where is @Transactional and what rolls back?
  • What happens on a duplicate Idempotency-Key?
  • How do you prove you did not N+1 the list endpoint?
  • Why after-commit for the event?

COMMON MISTAKE: Perfect package names, zero tests. Interviewers would rather see one idempotency test than a hexagonal folder with empty ports.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column as the real correctness mechanisms, not the happy-path service method.

As-built design (bonus)

As-built design (bonus)

Lab 501 — As-built design (bonus)

Optional. Skip this if you already ran ./mvnw test and can explain replay vs 409. Use it when the interviewer asks “what’s in the database?” or “walk me through the POST.”

This page matches the code in the zip, not the longer production story. There is no inventory table and no outbox table in this lab.

See it

Lab 501 tables — as the code creates them Lab 501 tables — as the code creates them Three tables. Unique key stops a double insert. @Version stops a silent clobber. No inventory. No outbox. orders id UUID PK generated on persist customer_id indexed · not a users table status CREATED…SHIPPED / CANCELLED total_amount DECIMAL(19,2) · sum of lines version @Version starts at 0 · flush incrementsthis is the lock order_items id UUID PK order_id FK cascade + orphanRemovalowned by the order product_id no products table qty + unit_price DTO: qty ≥ 1, price ≥ 0.01EntityGraph on GET / list idempotency_keys idempotency_key PK header, 1–128 charsunique IS the primary key request_hash SHA-256 of JSON body response_status + body stored 201 + OrderResponseempty body = reservation Not in this lab no inventory rowno outbox row 3 tables version = lock key = PK
Three tables: orders (version lock), order_items, idempotency_keys (unique key). No inventory, no outbox.
POST /orders — one transaction, then after-commit POST /orders — one transaction, then after-commit Hash selects replay vs conflict. Unique insert is the reservation. Event fires after commit, in process. Inside OrderService.create · @Transactional 1. Hash body SHA-256 hexof JSON bytes 2. Lookup key hit + same hash→ replay stored JSON 3. Reserve key INSERT + flushunique loser reads 4. Insert aggregate orders + N linesversion = 0 5. Store 201 write responseonto the key row Replay same key + same hash201 + Location · no 2nd row Conflict same key + different hash409 IDEMPOTENCY_KEY_CONFLICT Missing key 400 MISSING_IDEMPOTENCY_KEYvalidation → 400 + field errors After commit — not a table OrderCreatedEvent @TransactionalEventListenerAFTER_COMMIT + @Asyncfailed listener cannot roll back Crash after COMMIT in-memory event is goneorder row is notthis is the outbox sentence PATCH …/status version in the body stale → 4092 writers at v=0 → 409legal transitions only one TX replay 201 409 ≠ 201
POST /orders: hash body → reserve key → insert order + lines → store 201 → event after commit.

Read the diagrams, then say: Three tables. The unique key stops a double insert. @Version stops a silent clobber on status. The event is after commit, in process — a crash can still lose it.

Tables (as Hibernate creates them)

orders — id UUID PK, customer_id (indexed), status, total_amount DECIMAL(19,2), created_at / updated_at, version BIGINT (@Version, starts at 0).

order_items — id UUID PK, order_id FK, product_id, quantity, unit_price. Cascade from the order. Loaded with @EntityGraph(attributePaths = "items") on findById and findAll. open-in-view=false.

idempotency_keys — idempotency_key VARCHAR(128) is the PK, request_hash SHA-256 hex of the JSON body, response_status, response_body (serialized OrderResponse), created_at.

The empty response_body row is the reservation. Two in-flight creates: saveAndFlush + unique violation → read the winner.

Full as-built spec — DDL, every header, validation, error codes, create steps, event executor, and the tests that lock it: low-level-design.md. HTTP shapes: api-notes.md.

One POST /api/v1/orders

Headers: Idempotency-Key (required, 1–128), optional X-Correlation-Id.

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{"customerId":"11111111-1111-1111-1111-111111111111","items":[{"productId":"22222222-2222-2222-2222-222222222222","quantity":2,"unitPrice":19.99}]}

One @Transactional on OrderService.create:

  1. Hash the body.
  2. Key exists + same hash → replay stored JSON (201 + Location).
  3. Key exists + different hash → 409 IDEMPOTENCY_KEY_CONFLICT.
  4. Miss → insert the key, insert orders + lines, write 201 onto the key.
  5. publishEvent(OrderCreatedEvent) inside the TX. Listener is AFTER_COMMIT + @Async.

Missing header → 400 MISSING_IDEMPOTENCY_KEY. Bean Validation → 400 VALIDATION_ERROR.

PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

Service rejects a stale version immediately. Hibernate still increments @Version on flush, so two writers who both read 0 produce 409 OPTIMISTIC_LOCK_CONFLICT (handler maps OptimisticLockingFailureException).

Legal: CREATED → CONFIRMED|CANCELLED, CONFIRMED → PROCESSING|CANCELLED, PROCESSING → SHIPPED|CANCELLED. Terminal: SHIPPED, CANCELLED.

Whiteboard in 60 seconds

  1. Three boxes: orders.version, order_items.order_id, idempotency_keys PK.
  2. POST arrow: hash → reserve key → insert aggregate → store response → after-commit event.
  3. Replay vs 409. PATCH + version vs last-write-wins.
  4. Stop. Do not draw Kafka.

What we left out on purpose

  • No inventory row. Conditional UPDATE … WHERE qty >= 1 is the next sentence, not a table here.
  • No outbox row. A crash after commit can lose OrderCreated. Outbox + inbox is the upgrade.
  • No Resilience4j, no Spring Security.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are what make the create correct. The happy-path service method is just the story that uses them.

Design notes

Design notes

Design notes (interview talking points)

Layering

  • Controller: HTTP mapping, Bean Validation, headers. No persistence, no business rules.
  • Service: @Transactional boundary, status machine, totals, idempotency, event publish.
  • Repository: Spring Data JPA only.
  • Mapper: entity ↔ DTO. Controllers never return Order / OrderItem.

Constructor injection everywhere. No field @Autowired.

Optimistic locking

Order.version is @Version. The client sends the version it last read on

PATCH …/status. Hibernate increments on each flush. A stale writer gets

ObjectOptimisticLockingFailureException, mapped to 409 OPTIMISTIC_LOCK_CONFLICT.

Why not last-write-wins? Two operators confirming vs cancelling the same order

must not silently clobber each other.

Idempotent create

Mobile clients retry POST after timeouts. The service persists

idempotency_key (unique), a SHA-256 of the request body, and the serialized

response. Replay is a read, not a second insert. A unique constraint plus a

DataIntegrityViolationException retry handles two in-flight requests with the

same key.

Same key, different body is a client bug → 409, not a second order.

The key is stored in the database, not an in-memory map, so two instances of

the service cannot both insert.

Async event

ApplicationEventPublisher publishes OrderCreatedEvent inside the create

transaction. The listener is @TransactionalEventListener(AFTER_COMMIT) +

@Async so a failed listener cannot roll back the order, and the work does not

sit on the request thread. MDC (correlationId) is copied onto the async

thread via a TaskDecorator.

This lab does not introduce a broker. In production the same event would become

an outbox row or a message.

Correlation ID

CorrelationIdFilter reads X-Correlation-Id or generates one, stores it in

MDC, and echoes the header. GlobalExceptionHandler copies it into the error

JSON so a 404 in logs, traces, and the client payload share one id.

Transactions and Open Session in View

spring.jpa.open-in-view=false. Lazy Order.items are loaded with

@EntityGraph on repository methods. Mapping happens inside the service

transaction.

@Transactional lives on the service, not the controller: the HTTP layer

should not hold a database connection while writing the response.

Column-level tables, the POST transaction, and PATCH …/status are in

low-level-design.md.

What we left out on purpose

  • Resilience4j — this lab is about API + persistence + retries of *this* service.
  • Spring Security / secrets — no credentials in images or YAML beyond local

Compose defaults overridden by env vars.

  • MapStruct / Lombok — explicit mapper and constructors are easier to talk through.

API notes

API notes

Order API notes

Base path: /api/v1. JSON in and out. Controllers never return JPA entities.

Resources

POST /api/v1/orders

Creates an order in CREATED. Requires header Idempotency-Key (1–128 chars).

Request:

json

{
  "customerId": "uuid",
  "items": [
    { "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }
  ]
}

Validation: customerId required; items not empty; each quantity >= 1;

unitPrice >= 0.01.

Response 201 with Location: /api/v1/orders/{id} and body:

json

{
  "id": "uuid",
  "customerId": "uuid",
  "status": "CREATED",
  "items": [{ "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }],
  "totalAmount": 10.00,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Idempotency: same key + same body replays the original 201 and body. Same key +

different body → 409 IDEMPOTENCY_KEY_CONFLICT. Missing key → 400

MISSING_IDEMPOTENCY_KEY.

GET /api/v1/orders/{id}

200 or 404 ORDER_NOT_FOUND.

GET /api/v1/orders

Query: page (default 0), size (default 20, max 100). Sorted by createdAt desc.

json

{
  "content": [],
  "page": 0,
  "size": 20,
  "totalElements": 0,
  "totalPages": 0,
  "first": true,
  "last": true
}
PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

version must match @Version on the row. Mismatch → 409 OPTIMISTIC_LOCK_CONFLICT.

Illegal transition → 409 ORDER_STATE_CONFLICT.

Allowed transitions:

  • CREATED → CONFIRMED, CANCELLED
  • CONFIRMED → PROCESSING, CANCELLED
  • PROCESSING → SHIPPED, CANCELLED
  • SHIPPED, CANCELLED are terminal

Errors

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 404,
  "code": "ORDER_NOT_FOUND",
  "message": "Order not found: …",
  "correlationId": "…",
  "errors": []
}

Validation failures use 400 VALIDATION_ERROR and populate errors with

{ "field", "message" }.

Send X-Correlation-Id to pin a request. The filter echoes it on the response

and puts it in MDC / error JSON. If omitted, the filter generates a UUID.

Low-level design

Low-level design

As-built design — Lab 501

This is the service as the repo ships it. Open Order.java,

IdempotencyRecord.java, OrderService.java, OrderController.java, and

GlobalExceptionHandler.java while you read.

It is not the staff story. There is no inventory table, no outbox table,

no broker, no Resilience4j, and no Spring Security.

HTTP shapes also live in api-notes.md. Interview *why* lives in

design-notes.md.

Runtime

Language / buildJava 21, Maven Wrapper 3.9.9
FrameworkSpring Boot 3.3, Spring Data JPA, Bean Validation
Default storeH2 in-memory jdbc:h2:mem:orders, MODE=PostgreSQL
Optional storePostgreSQL 16 via SPRING_PROFILES_ACTIVE=postgres
Schemaspring.jpa.hibernate.ddl-auto=update on both profiles
OSIVspring.jpa.open-in-view=false
ClockHibernate JDBC time_zone=UTC. Jackson writes ISO-8601 instants, not epoch millis
HTTPhttp://localhost:8080, base path /api/v1
Health/actuator/health (health, info; probes on; details never)
H2 console/h2-console on the default profile only (jdbc:h2:mem:orders, user sa, blank password)

Tests always use H2. They never start Postgres.

Layering

text

HTTP  OrderController     mapping, @Valid, headers. No persistence. No status rules.
  →   OrderService        @Transactional unit of work, idempotency, status machine, event publish
        → OrderRepository              Spring Data JPA + @EntityGraph("items")
        → IdempotencyRecordRepository  Spring Data JPA
        → OrderMapper                  entity ↔ DTO (explicit, no MapStruct)
        → ApplicationEventPublisher    OrderCreatedEvent
Advice  GlobalExceptionHandler         one error JSON shape
Filter  CorrelationIdFilter            X-Correlation-Id → MDC + response header

Constructor injection only. Controllers never return Order / OrderItem.

Data model

Three tables. Hibernate names them from @Table. There is no Flyway/Liquibase

script — ddl-auto=update creates them.

text

orders 1 ──< order_items
idempotency_keys   (no FK to orders — stores a serialized OrderResponse)
orders → Order

@Entity @Table(name = "orders", indexes = @Index(name = "idx_orders_customer", columnList = "customer_id"))

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKnoAssigned on persist
customer_id@Column(nullable = false)UUIDnoIndexed. No customers table
status@Enumerated(STRING) length 32VARCHAR(32)noSee status machine
total_amountprecision 19, scale 2DECIMAL(19,2)noqty * unit_price summed, HALF_UP 2 dp
created_atupdatable = falsetimestampno@PrePersist
updated_attimestampno@PrePersist and @PreUpdate
version@VersionBIGINTnoOptimistic lock. First persist → 0

@OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true) List<OrderItem> items.

Adding a line calls item.setOrder(this).

recalculateTotal() runs in the mapper before persist and in @PrePersist if

totalAmount is still null. There is no DB generated column.

There is no inventory column and no unique constraint on customer_id.

order_items → OrderItem

@Entity @Table(name = "order_items")

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKno
order_id@ManyToOne(LAZY) @JoinColumn(nullable = false)UUID FK → orders.idnoInverse of Order.items
product_id@Column(nullable = false)UUIDnoCatalog id. No products table
quantityintINTnoDTO enforces >= 1
unit_priceprecision 19, scale 2DECIMAL(19,2)noDTO enforces >= 0.01, ≤ 2 fraction digits

No unique (order_id, product_id) — two lines may share a product. No line-level

@Version.

idempotency_keys → IdempotencyRecord

@Entity @Table(name = "idempotency_keys")

ColumnMappingTypeNullNotes
idempotency_key@Id length 128VARCHAR(128) PKnoExact Idempotency-Key header. Unique is the PK
request_hashlength 64VARCHAR(64)noLowercase hex SHA-256 of the JSON request bytes
response_statusintINTnoWritten as 201
response_bodycolumnDefinition = TEXTTEXTnoJackson OrderResponse. "" means reserved, not complete
created_atupdatable = falsetimestampnoSet in the constructor

No FK to orders. Replay is a deserialize of response_body, not a second

SELECT of the order (the stored JSON already has id / version).

PK collision is the concurrency control for two in-flight creates with the same

key (saveAndFlush + DataIntegrityViolationException).

Approximate DDL (Postgres-shaped)

H2 MODE=PostgreSQL produces the same shapes. Types may differ slightly

(UUID vs BINARY vs varchar) under H2; treat this as the contract, not a

checked-in migration.

sql

CREATE TABLE orders (
  id            UUID PRIMARY KEY,
  customer_id   UUID           NOT NULL,
  status        VARCHAR(32)    NOT NULL,
  total_amount  NUMERIC(19, 2) NOT NULL,
  created_at    TIMESTAMP      NOT NULL,
  updated_at    TIMESTAMP      NOT NULL,
  version       BIGINT         NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

CREATE TABLE order_items (
  id          UUID PRIMARY KEY,
  order_id    UUID           NOT NULL REFERENCES orders (id),
  product_id  UUID           NOT NULL,
  quantity    INTEGER        NOT NULL,
  unit_price  NUMERIC(19, 2) NOT NULL
);

CREATE TABLE idempotency_keys (
  idempotency_key  VARCHAR(128) PRIMARY KEY,
  request_hash     VARCHAR(64)  NOT NULL,
  response_status  INTEGER      NOT NULL,
  response_body    TEXT         NOT NULL,
  created_at       TIMESTAMP    NOT NULL
);

Hibernate @Version UPDATE looks like:

sql

UPDATE orders
   SET status = ?, updated_at = ?, version = version + 1
 WHERE id = ? AND version = ?;
-- 0 rows → OptimisticLockingFailureException

HTTP surface

All JSON. All success bodies are DTOs. Dates are ISO-8601 UTC instants.

Headers on every request
HeaderRequiredBehavior
Content-Type: application/jsonwrite endpointsMissing/unreadable body → 400 MALFORMED_REQUEST
Idempotency-KeyPOST /orders only1–128 chars after trim. Blank/missing → 400 MISSING_IDEMPOTENCY_KEY
X-Correlation-IdnoEchoed on every response. If blank/absent, filter generates a UUID
POST /api/v1/orders → 201 Created

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{
  "customerId": "11111111-1111-1111-1111-111111111111",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ]
}

Response headers: Location: /api/v1/orders/{id}, X-Correlation-Id: …

json

{
  "id": "…",
  "customerId": "11111111-1111-1111-1111-111111111111",
  "status": "CREATED",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ],
  "totalAmount": 39.98,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Replay (same key + same body) is still 201 + the original Location and body.

It does not insert a second order. It does not publish a second OrderCreatedEvent.

GET /api/v1/orders/{id} → 200 or 404 ORDER_NOT_FOUND

Same OrderResponse as create. Items come from @EntityGraph(attributePaths = "items")

on OrderRepository.findById. Mapping runs inside @Transactional(readOnly = true).

Bad UUID in the path → 400 VALIDATION_ERROR (MethodArgumentTypeMismatch).

GET /api/v1/orders?page=0&size=20 → 200
QueryDefaultConstraint
page0@Min(0)
size20@Min(1) @Max(100)

Sort: createdAt DESC. findAll(Pageable) also uses the items entity graph, so

a page of N orders is not 1 + N line queries.

json

{
  "content": [ "OrderResponse…" ],
  "page": 0,
  "size": 20,
  "totalElements": 1,
  "totalPages": 1,
  "first": true,
  "last": true
}

There is no customerId filter in this lab.

PATCH /api/v1/orders/{id}/status → 200

json

{ "status": "CONFIRMED", "version": 0 }

Both fields required. Success body is OrderResponse with version incremented

(0 → 1 on the first confirm). No Idempotency-Key on PATCH.

Validation (request DTO)

CreateOrderRequest:

FieldRules
customerId@NotNull — "customerId is required"
items@NotEmpty @Valid — "items must not be empty"

OrderItemRequest:

FieldRules
productId@NotNull
quantity@NotNull @Min(1)
unitPrice@NotNull @DecimalMin("0.01") @Digits(integer=17, fraction=2)

UpdateOrderStatusRequest:

FieldRules
status@NotNull — must be an OrderStatus enum name
version@NotNull

Idempotency-Key header: @NotBlank @Size(max = 128).

Failures → 400 VALIDATION_ERROR, errors: [{ "field", "message" }].

Error catalog

Every error body:

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 409,
  "code": "IDEMPOTENCY_KEY_CONFLICT",
  "message": "…",
  "correlationId": "demo-1",
  "errors": []
}

correlationId is the MDC value from the filter. If MDC is empty, the handler

generates a UUID so the client still gets one.

HTTPcodeWhen
400MISSING_IDEMPOTENCY_KEYPOST without Idempotency-Key
400MISSING_HEADERany other required header missing
400VALIDATION_ERRORBean Validation, constraint violation, or bad path/query type
400MALFORMED_REQUESTunreadable JSON
404ORDER_NOT_FOUNDunknown order id
409IDEMPOTENCY_KEY_CONFLICTsame key, different SHA-256 body
409OPTIMISTIC_LOCK_CONFLICTPATCH version mismatch, or Hibernate OptimisticLockingFailureException on flush
409ORDER_STATE_CONFLICTillegal status transition
500INTERNAL_ERRORanything else (message is generic; stack goes to logs only)

Domain exceptions log warn with code. Unhandled exceptions log error.

Create algorithm (OrderService.create)

One @Transactional (default REQUIRED, read-write).

  1. Hash. ObjectMapper.writeValueAsBytes(request) then SHA-256 hex

(HexFormat). The hash is of the parsed DTO as re-serialized JSON, not

the raw request string. Extra unknown JSON fields are dropped by Jackson

before the hash. Key order in the stored DTO follows the record components.

  1. Lookup idempotency_keys by PK.

- Hit + request_hash matches → deserialize response_body → return

(replay). No new order. No new event.

- Hit + hash differs → 409 IDEMPOTENCY_KEY_CONFLICT.

  1. Reserve. saveAndFlush a row (key, hash, 201, "").

- Unique violation → findById the winner. If that row now has a body,

replay (or conflict on hash). If it is still empty, the winner is still

inserting — the loser treats a completed body on the next read.

  1. Aggregate. OrderMapper.toNewEntity: status CREATED, add lines, recalculateTotal().
  2. `orderRepository.save`. INSERT orders (version = 0) and INSERT each

order_items row in the same persistence context.

  1. Map to `OrderResponse` (needs generated id + version).
  2. `reservation.complete(201, json)` — UPDATE the key row with the serialized

response. Still the same transaction.

  1. `publishEvent(new OrderCreatedEvent(orderId, customerId))` — recorded

*inside* the transaction. Delivery is after commit (below).

  1. Log order.create.completed orderId=… totalAmount=….
  2. Controller wraps the DTO in 201 + Location.

If any step throws before commit, the reserved key row rolls back. A retry with

the same key starts clean.

Logs on the happy path: order.create.started (customerId, itemCount),

order.create.completed (orderId, totalAmount). Replay logs

order.create.replayed.

Status machine + optimistic lock (updateStatus)

text

CREATED     → CONFIRMED, CANCELLED
CONFIRMED   → PROCESSING, CANCELLED
PROCESSING  → SHIPPED, CANCELLED
SHIPPED     → (none)
CANCELLED   → (none)

OrderStatus.canTransitionTo is an EnumMap. Same-status PATCH is illegal

(CREATED → CREATED is a 409 ORDER_STATE_CONFLICT).

Locking is two layers:

  1. Service: if (!request.version().equals(order.getVersion())) →

OptimisticLockConflictException (409, message includes order id and

expected version).

  1. Hibernate: UPDATE … WHERE id=? AND version=?. Two writers who both read

version=0 and both pass step 1: the second flush throws

OptimisticLockingFailureException, mapped to the same code

OPTIMISTIC_LOCK_CONFLICT (generic message: *"The order was modified by

another request"*).

PATCH is not idempotent. A retry with the old version after a success is a

409, not a replay.

Log: order.status.updated orderId=… from=… to=… version=….

Persistence / fetch plan

CallRepositoryGraphTX
createsave(Order)cascade persist itemsread-write
getByIdfindByIditemsread-only
listfindAll(Pageable)itemsread-only
updateStatusfindById then saveitemsread-write

open-in-view=false means a lazy items touch after the service method

returns would throw. The graph + mapper-inside-the-TX is what makes GET/list

safe. That is the N+1 answer for this lab: entity graph, not EAGER on the

@OneToMany.

Events

OrderCreatedEvent(orderId, customerId, occurredAt=now) is a Java record, not a

row.

Listener OrderCreatedEventListener:

  • @TransactionalEventListener(phase = AFTER_COMMIT) — a throw in the listener

cannot roll back the order.

  • @Async("orderEventExecutor") — does not sit on the Tomcat thread.
  • Body: one info log order.event.created orderId=… customerId=… occurredAt=….

No HTTP, no second DB write.

Executor orderEventExecutor: core 2, max 4, queue 100, prefix order-event-,

MdcTaskDecorator copies correlationId onto the async thread.

Loss mode: process crash after COMMIT and before the listener runs. The

order row is durable. The in-memory event is gone. The interview upgrade is an

outbox row in the same create transaction plus a relay. That table is not

in this repo.

Correlation ID

CorrelationIdFilter at Ordered.HIGHEST_PRECEDENCE:

  1. Read X-Correlation-Id. Blank/absent → UUID.randomUUID().
  2. MDC.put("correlationId", …).
  3. response.setHeader("X-Correlation-Id", …).
  4. finally MDC.remove.

Console pattern:

text

%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} level=%-5level correlationId=%X{correlationId} logger=%logger{36} msg=%msg%n

Error JSON reuses the same id. The async listener keeps it via the task

decorator.

Transactions (rules you say out loud)

  • @Transactional is on the service, never the controller — the HTTP layer

must not hold a JDBC connection while writing the response.

  • Create, reserve-key, order insert, and key-complete are one commit.
  • The event is registered before commit and delivered after.
  • Read methods are readOnly = true.
  • OSIV is off.

Optional Postgres

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

or docker compose up --build. Credentials come from env

(SPRING_DATASOURCE_URL / USERNAME / PASSWORD). Compose defaults

orders / orders / orders are local only. Same entities, same

ddl-auto=update. H2 console is disabled on this profile.

Tests that lock this contract

TestWhat it proves
OrderApiITcreate → GET → list → PATCH confirm (version 0→1) → stale PATCH 409 OPTIMISTIC_LOCK_CONFLICT; X-Correlation-Id echoed
OrderIdempotencyITsame key + body → one order row, one key row, one OrderCreatedEvent; same key + different body → 409
OrderOptimisticLockingTest@Version increment / conflict
OrderValidationTest / OrderControllerTestmissing key, empty items, bad qty/price
OrderCreatedEventITlistener after commit
OrderStatusTestlegal / illegal transitions
GlobalExceptionHandlerTesterror JSON shape

./mvnw test is the lab bar. BayLearn does not run these.

What we left out on purpose

MissingWhyWhat you say next
inventory35-minute accept pathUPDATE inventory SET qty = qty - :n WHERE sku = :sku AND qty >= :n
outboxin-process event is enough to *talk* AFTER_COMMITsame TX as orders + relay; consumer inbox PK
customers / productsids onlythose are other services
Authn / secretsnot the labno credentials in images or YAML beyond local Compose
Resilience4jretries of *this* POST are the idempotency keytimeout + breaker on a *downstream* charge
Idempotent PATCHstatus changes are not replaysclient must send the version it last read

Say this: the unique key and the version column are the correctness. The

happy-path service method is just the story that uses them.

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

pom.xml

xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.5</version>
        <relativePath/>
    </parent>

    <groupId>com.baylearn</groupId>
    <artifactId>order-service</artifactId>
    <version>1.0.0</version>
    <name>order-service</name>
    <description>BayLearn interview lab — production-style Order API</description>

    <properties>
        <java.version>21</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Lab 501 — As-built design (bonus)10 min

Lab 501 — As-built design (bonus)

Lab 501 — As-built design (bonus)

Optional. Skip this if you already ran ./mvnw test and can explain replay vs 409. Use it when the interviewer asks “what’s in the database?” or “walk me through the POST.”

This page matches the code in the zip, not the longer production story. There is no inventory table and no outbox table in this lab.

See it

Lab 501 tables — as the code creates them Lab 501 tables — as the code creates them Three tables. Unique key stops a double insert. @Version stops a silent clobber. No inventory. No outbox. orders id UUID PK generated on persist customer_id indexed · not a users table status CREATED…SHIPPED / CANCELLED total_amount DECIMAL(19,2) · sum of lines version @Version starts at 0 · flush incrementsthis is the lock order_items id UUID PK order_id FK cascade + orphanRemovalowned by the order product_id no products table qty + unit_price DTO: qty ≥ 1, price ≥ 0.01EntityGraph on GET / list idempotency_keys idempotency_key PK header, 1–128 charsunique IS the primary key request_hash SHA-256 of JSON body response_status + body stored 201 + OrderResponseempty body = reservation Not in this lab no inventory rowno outbox row 3 tables version = lock key = PK
Three tables: orders (version lock), order_items, idempotency_keys (unique key). No inventory, no outbox.
POST /orders — one transaction, then after-commit POST /orders — one transaction, then after-commit Hash selects replay vs conflict. Unique insert is the reservation. Event fires after commit, in process. Inside OrderService.create · @Transactional 1. Hash body SHA-256 hexof JSON bytes 2. Lookup key hit + same hash→ replay stored JSON 3. Reserve key INSERT + flushunique loser reads 4. Insert aggregate orders + N linesversion = 0 5. Store 201 write responseonto the key row Replay same key + same hash201 + Location · no 2nd row Conflict same key + different hash409 IDEMPOTENCY_KEY_CONFLICT Missing key 400 MISSING_IDEMPOTENCY_KEYvalidation → 400 + field errors After commit — not a table OrderCreatedEvent @TransactionalEventListenerAFTER_COMMIT + @Asyncfailed listener cannot roll back Crash after COMMIT in-memory event is goneorder row is notthis is the outbox sentence PATCH …/status version in the body stale → 4092 writers at v=0 → 409legal transitions only one TX replay 201 409 ≠ 201
POST /orders: hash body → reserve key → insert order + lines → store 201 → event after commit.

Read the diagrams, then say: Three tables. The unique key stops a double insert. @Version stops a silent clobber on status. The event is after commit, in process — a crash can still lose it.

Tables (as Hibernate creates them)

orders — id UUID PK, customer_id (indexed), status, total_amount DECIMAL(19,2), created_at / updated_at, version BIGINT (@Version, starts at 0).

order_items — id UUID PK, order_id FK, product_id, quantity, unit_price. Cascade from the order. Loaded with @EntityGraph(attributePaths = "items") on findById and findAll. open-in-view=false.

idempotency_keys — idempotency_key VARCHAR(128) is the PK, request_hash SHA-256 hex of the JSON body, response_status, response_body (serialized OrderResponse), created_at.

The empty response_body row is the reservation. Two in-flight creates: saveAndFlush + unique violation → read the winner.

Full as-built spec — DDL, every header, validation, error codes, create steps, event executor, and the tests that lock it: low-level-design.md. HTTP shapes: api-notes.md.

One POST /api/v1/orders

Headers: Idempotency-Key (required, 1–128), optional X-Correlation-Id.

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{"customerId":"11111111-1111-1111-1111-111111111111","items":[{"productId":"22222222-2222-2222-2222-222222222222","quantity":2,"unitPrice":19.99}]}

One @Transactional on OrderService.create:

  1. Hash the body.
  2. Key exists + same hash → replay stored JSON (201 + Location).
  3. Key exists + different hash → 409 IDEMPOTENCY_KEY_CONFLICT.
  4. Miss → insert the key, insert orders + lines, write 201 onto the key.
  5. publishEvent(OrderCreatedEvent) inside the TX. Listener is AFTER_COMMIT + @Async.

Missing header → 400 MISSING_IDEMPOTENCY_KEY. Bean Validation → 400 VALIDATION_ERROR.

PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

Service rejects a stale version immediately. Hibernate still increments @Version on flush, so two writers who both read 0 produce 409 OPTIMISTIC_LOCK_CONFLICT (handler maps OptimisticLockingFailureException).

Legal: CREATED → CONFIRMED|CANCELLED, CONFIRMED → PROCESSING|CANCELLED, PROCESSING → SHIPPED|CANCELLED. Terminal: SHIPPED, CANCELLED.

Whiteboard in 60 seconds

  1. Three boxes: orders.version, order_items.order_id, idempotency_keys PK.
  2. POST arrow: hash → reserve key → insert aggregate → store response → after-commit event.
  3. Replay vs 409. PATCH + version vs last-write-wins.
  4. Stop. Do not draw Kafka.

What we left out on purpose

  • No inventory row. Conditional UPDATE … WHERE qty >= 1 is the next sentence, not a table here.
  • No outbox row. A crash after commit can lose OrderCreated. Outbox + inbox is the upgrade.
  • No Resilience4j, no Spring Security.

STAFF-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are what make the create correct. The happy-path service method is just the story that uses them.

Low-level design

Low-level design

As-built design — Lab 501

This is the service as the repo ships it. Open Order.java,

IdempotencyRecord.java, OrderService.java, OrderController.java, and

GlobalExceptionHandler.java while you read.

It is not the staff story. There is no inventory table, no outbox table,

no broker, no Resilience4j, and no Spring Security.

HTTP shapes also live in api-notes.md. Interview *why* lives in

design-notes.md.

Runtime

Language / buildJava 21, Maven Wrapper 3.9.9
FrameworkSpring Boot 3.3, Spring Data JPA, Bean Validation
Default storeH2 in-memory jdbc:h2:mem:orders, MODE=PostgreSQL
Optional storePostgreSQL 16 via SPRING_PROFILES_ACTIVE=postgres
Schemaspring.jpa.hibernate.ddl-auto=update on both profiles
OSIVspring.jpa.open-in-view=false
ClockHibernate JDBC time_zone=UTC. Jackson writes ISO-8601 instants, not epoch millis
HTTPhttp://localhost:8080, base path /api/v1
Health/actuator/health (health, info; probes on; details never)
H2 console/h2-console on the default profile only (jdbc:h2:mem:orders, user sa, blank password)

Tests always use H2. They never start Postgres.

Layering

text

HTTP  OrderController     mapping, @Valid, headers. No persistence. No status rules.
  →   OrderService        @Transactional unit of work, idempotency, status machine, event publish
        → OrderRepository              Spring Data JPA + @EntityGraph("items")
        → IdempotencyRecordRepository  Spring Data JPA
        → OrderMapper                  entity ↔ DTO (explicit, no MapStruct)
        → ApplicationEventPublisher    OrderCreatedEvent
Advice  GlobalExceptionHandler         one error JSON shape
Filter  CorrelationIdFilter            X-Correlation-Id → MDC + response header

Constructor injection only. Controllers never return Order / OrderItem.

Data model

Three tables. Hibernate names them from @Table. There is no Flyway/Liquibase

script — ddl-auto=update creates them.

text

orders 1 ──< order_items
idempotency_keys   (no FK to orders — stores a serialized OrderResponse)
orders → Order

@Entity @Table(name = "orders", indexes = @Index(name = "idx_orders_customer", columnList = "customer_id"))

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKnoAssigned on persist
customer_id@Column(nullable = false)UUIDnoIndexed. No customers table
status@Enumerated(STRING) length 32VARCHAR(32)noSee status machine
total_amountprecision 19, scale 2DECIMAL(19,2)noqty * unit_price summed, HALF_UP 2 dp
created_atupdatable = falsetimestampno@PrePersist
updated_attimestampno@PrePersist and @PreUpdate
version@VersionBIGINTnoOptimistic lock. First persist → 0

@OneToMany(mappedBy = "order", cascade = ALL, orphanRemoval = true) List<OrderItem> items.

Adding a line calls item.setOrder(this).

recalculateTotal() runs in the mapper before persist and in @PrePersist if

totalAmount is still null. There is no DB generated column.

There is no inventory column and no unique constraint on customer_id.

order_items → OrderItem

@Entity @Table(name = "order_items")

ColumnMappingTypeNullNotes
id@Id @GeneratedValue(UUID)UUID PKno
order_id@ManyToOne(LAZY) @JoinColumn(nullable = false)UUID FK → orders.idnoInverse of Order.items
product_id@Column(nullable = false)UUIDnoCatalog id. No products table
quantityintINTnoDTO enforces >= 1
unit_priceprecision 19, scale 2DECIMAL(19,2)noDTO enforces >= 0.01, ≤ 2 fraction digits

No unique (order_id, product_id) — two lines may share a product. No line-level

@Version.

idempotency_keys → IdempotencyRecord

@Entity @Table(name = "idempotency_keys")

ColumnMappingTypeNullNotes
idempotency_key@Id length 128VARCHAR(128) PKnoExact Idempotency-Key header. Unique is the PK
request_hashlength 64VARCHAR(64)noLowercase hex SHA-256 of the JSON request bytes
response_statusintINTnoWritten as 201
response_bodycolumnDefinition = TEXTTEXTnoJackson OrderResponse. "" means reserved, not complete
created_atupdatable = falsetimestampnoSet in the constructor

No FK to orders. Replay is a deserialize of response_body, not a second

SELECT of the order (the stored JSON already has id / version).

PK collision is the concurrency control for two in-flight creates with the same

key (saveAndFlush + DataIntegrityViolationException).

Approximate DDL (Postgres-shaped)

H2 MODE=PostgreSQL produces the same shapes. Types may differ slightly

(UUID vs BINARY vs varchar) under H2; treat this as the contract, not a

checked-in migration.

sql

CREATE TABLE orders (
  id            UUID PRIMARY KEY,
  customer_id   UUID           NOT NULL,
  status        VARCHAR(32)    NOT NULL,
  total_amount  NUMERIC(19, 2) NOT NULL,
  created_at    TIMESTAMP      NOT NULL,
  updated_at    TIMESTAMP      NOT NULL,
  version       BIGINT         NOT NULL
);
CREATE INDEX idx_orders_customer ON orders (customer_id);

CREATE TABLE order_items (
  id          UUID PRIMARY KEY,
  order_id    UUID           NOT NULL REFERENCES orders (id),
  product_id  UUID           NOT NULL,
  quantity    INTEGER        NOT NULL,
  unit_price  NUMERIC(19, 2) NOT NULL
);

CREATE TABLE idempotency_keys (
  idempotency_key  VARCHAR(128) PRIMARY KEY,
  request_hash     VARCHAR(64)  NOT NULL,
  response_status  INTEGER      NOT NULL,
  response_body    TEXT         NOT NULL,
  created_at       TIMESTAMP    NOT NULL
);

Hibernate @Version UPDATE looks like:

sql

UPDATE orders
   SET status = ?, updated_at = ?, version = version + 1
 WHERE id = ? AND version = ?;
-- 0 rows → OptimisticLockingFailureException

HTTP surface

All JSON. All success bodies are DTOs. Dates are ISO-8601 UTC instants.

Headers on every request
HeaderRequiredBehavior
Content-Type: application/jsonwrite endpointsMissing/unreadable body → 400 MALFORMED_REQUEST
Idempotency-KeyPOST /orders only1–128 chars after trim. Blank/missing → 400 MISSING_IDEMPOTENCY_KEY
X-Correlation-IdnoEchoed on every response. If blank/absent, filter generates a UUID
POST /api/v1/orders → 201 Created

http

POST /api/v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: checkout-42
X-Correlation-Id: demo-1

{
  "customerId": "11111111-1111-1111-1111-111111111111",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ]
}

Response headers: Location: /api/v1/orders/{id}, X-Correlation-Id: …

json

{
  "id": "…",
  "customerId": "11111111-1111-1111-1111-111111111111",
  "status": "CREATED",
  "items": [
    { "productId": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unitPrice": 19.99 }
  ],
  "totalAmount": 39.98,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Replay (same key + same body) is still 201 + the original Location and body.

It does not insert a second order. It does not publish a second OrderCreatedEvent.

GET /api/v1/orders/{id} → 200 or 404 ORDER_NOT_FOUND

Same OrderResponse as create. Items come from @EntityGraph(attributePaths = "items")

on OrderRepository.findById. Mapping runs inside @Transactional(readOnly = true).

Bad UUID in the path → 400 VALIDATION_ERROR (MethodArgumentTypeMismatch).

GET /api/v1/orders?page=0&size=20 → 200
QueryDefaultConstraint
page0@Min(0)
size20@Min(1) @Max(100)

Sort: createdAt DESC. findAll(Pageable) also uses the items entity graph, so

a page of N orders is not 1 + N line queries.

json

{
  "content": [ "OrderResponse…" ],
  "page": 0,
  "size": 20,
  "totalElements": 1,
  "totalPages": 1,
  "first": true,
  "last": true
}

There is no customerId filter in this lab.

PATCH /api/v1/orders/{id}/status → 200

json

{ "status": "CONFIRMED", "version": 0 }

Both fields required. Success body is OrderResponse with version incremented

(0 → 1 on the first confirm). No Idempotency-Key on PATCH.

Validation (request DTO)

CreateOrderRequest:

FieldRules
customerId@NotNull — "customerId is required"
items@NotEmpty @Valid — "items must not be empty"

OrderItemRequest:

FieldRules
productId@NotNull
quantity@NotNull @Min(1)
unitPrice@NotNull @DecimalMin("0.01") @Digits(integer=17, fraction=2)

UpdateOrderStatusRequest:

FieldRules
status@NotNull — must be an OrderStatus enum name
version@NotNull

Idempotency-Key header: @NotBlank @Size(max = 128).

Failures → 400 VALIDATION_ERROR, errors: [{ "field", "message" }].

Error catalog

Every error body:

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 409,
  "code": "IDEMPOTENCY_KEY_CONFLICT",
  "message": "…",
  "correlationId": "demo-1",
  "errors": []
}

correlationId is the MDC value from the filter. If MDC is empty, the handler

generates a UUID so the client still gets one.

HTTPcodeWhen
400MISSING_IDEMPOTENCY_KEYPOST without Idempotency-Key
400MISSING_HEADERany other required header missing
400VALIDATION_ERRORBean Validation, constraint violation, or bad path/query type
400MALFORMED_REQUESTunreadable JSON
404ORDER_NOT_FOUNDunknown order id
409IDEMPOTENCY_KEY_CONFLICTsame key, different SHA-256 body
409OPTIMISTIC_LOCK_CONFLICTPATCH version mismatch, or Hibernate OptimisticLockingFailureException on flush
409ORDER_STATE_CONFLICTillegal status transition
500INTERNAL_ERRORanything else (message is generic; stack goes to logs only)

Domain exceptions log warn with code. Unhandled exceptions log error.

Create algorithm (OrderService.create)

One @Transactional (default REQUIRED, read-write).

  1. Hash. ObjectMapper.writeValueAsBytes(request) then SHA-256 hex

(HexFormat). The hash is of the parsed DTO as re-serialized JSON, not

the raw request string. Extra unknown JSON fields are dropped by Jackson

before the hash. Key order in the stored DTO follows the record components.

  1. Lookup idempotency_keys by PK.

- Hit + request_hash matches → deserialize response_body → return

(replay). No new order. No new event.

- Hit + hash differs → 409 IDEMPOTENCY_KEY_CONFLICT.

  1. Reserve. saveAndFlush a row (key, hash, 201, "").

- Unique violation → findById the winner. If that row now has a body,

replay (or conflict on hash). If it is still empty, the winner is still

inserting — the loser treats a completed body on the next read.

  1. Aggregate. OrderMapper.toNewEntity: status CREATED, add lines, recalculateTotal().
  2. `orderRepository.save`. INSERT orders (version = 0) and INSERT each

order_items row in the same persistence context.

  1. Map to `OrderResponse` (needs generated id + version).
  2. `reservation.complete(201, json)` — UPDATE the key row with the serialized

response. Still the same transaction.

  1. `publishEvent(new OrderCreatedEvent(orderId, customerId))` — recorded

*inside* the transaction. Delivery is after commit (below).

  1. Log order.create.completed orderId=… totalAmount=….
  2. Controller wraps the DTO in 201 + Location.

If any step throws before commit, the reserved key row rolls back. A retry with

the same key starts clean.

Logs on the happy path: order.create.started (customerId, itemCount),

order.create.completed (orderId, totalAmount). Replay logs

order.create.replayed.

Status machine + optimistic lock (updateStatus)

text

CREATED     → CONFIRMED, CANCELLED
CONFIRMED   → PROCESSING, CANCELLED
PROCESSING  → SHIPPED, CANCELLED
SHIPPED     → (none)
CANCELLED   → (none)

OrderStatus.canTransitionTo is an EnumMap. Same-status PATCH is illegal

(CREATED → CREATED is a 409 ORDER_STATE_CONFLICT).

Locking is two layers:

  1. Service: if (!request.version().equals(order.getVersion())) →

OptimisticLockConflictException (409, message includes order id and

expected version).

  1. Hibernate: UPDATE … WHERE id=? AND version=?. Two writers who both read

version=0 and both pass step 1: the second flush throws

OptimisticLockingFailureException, mapped to the same code

OPTIMISTIC_LOCK_CONFLICT (generic message: *"The order was modified by

another request"*).

PATCH is not idempotent. A retry with the old version after a success is a

409, not a replay.

Log: order.status.updated orderId=… from=… to=… version=….

Persistence / fetch plan

CallRepositoryGraphTX
createsave(Order)cascade persist itemsread-write
getByIdfindByIditemsread-only
listfindAll(Pageable)itemsread-only
updateStatusfindById then saveitemsread-write

open-in-view=false means a lazy items touch after the service method

returns would throw. The graph + mapper-inside-the-TX is what makes GET/list

safe. That is the N+1 answer for this lab: entity graph, not EAGER on the

@OneToMany.

Events

OrderCreatedEvent(orderId, customerId, occurredAt=now) is a Java record, not a

row.

Listener OrderCreatedEventListener:

  • @TransactionalEventListener(phase = AFTER_COMMIT) — a throw in the listener

cannot roll back the order.

  • @Async("orderEventExecutor") — does not sit on the Tomcat thread.
  • Body: one info log order.event.created orderId=… customerId=… occurredAt=….

No HTTP, no second DB write.

Executor orderEventExecutor: core 2, max 4, queue 100, prefix order-event-,

MdcTaskDecorator copies correlationId onto the async thread.

Loss mode: process crash after COMMIT and before the listener runs. The

order row is durable. The in-memory event is gone. The interview upgrade is an

outbox row in the same create transaction plus a relay. That table is not

in this repo.

Correlation ID

CorrelationIdFilter at Ordered.HIGHEST_PRECEDENCE:

  1. Read X-Correlation-Id. Blank/absent → UUID.randomUUID().
  2. MDC.put("correlationId", …).
  3. response.setHeader("X-Correlation-Id", …).
  4. finally MDC.remove.

Console pattern:

text

%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} level=%-5level correlationId=%X{correlationId} logger=%logger{36} msg=%msg%n

Error JSON reuses the same id. The async listener keeps it via the task

decorator.

Transactions (rules you say out loud)

  • @Transactional is on the service, never the controller — the HTTP layer

must not hold a JDBC connection while writing the response.

  • Create, reserve-key, order insert, and key-complete are one commit.
  • The event is registered before commit and delivered after.
  • Read methods are readOnly = true.
  • OSIV is off.

Optional Postgres

bash

docker compose up postgres
SPRING_PROFILES_ACTIVE=postgres ./mvnw spring-boot:run

or docker compose up --build. Credentials come from env

(SPRING_DATASOURCE_URL / USERNAME / PASSWORD). Compose defaults

orders / orders / orders are local only. Same entities, same

ddl-auto=update. H2 console is disabled on this profile.

Tests that lock this contract

TestWhat it proves
OrderApiITcreate → GET → list → PATCH confirm (version 0→1) → stale PATCH 409 OPTIMISTIC_LOCK_CONFLICT; X-Correlation-Id echoed
OrderIdempotencyITsame key + body → one order row, one key row, one OrderCreatedEvent; same key + different body → 409
OrderOptimisticLockingTest@Version increment / conflict
OrderValidationTest / OrderControllerTestmissing key, empty items, bad qty/price
OrderCreatedEventITlistener after commit
OrderStatusTestlegal / illegal transitions
GlobalExceptionHandlerTesterror JSON shape

./mvnw test is the lab bar. BayLearn does not run these.

What we left out on purpose

MissingWhyWhat you say next
inventory35-minute accept pathUPDATE inventory SET qty = qty - :n WHERE sku = :sku AND qty >= :n
outboxin-process event is enough to *talk* AFTER_COMMITsame TX as orders + relay; consumer inbox PK
customers / productsids onlythose are other services
Authn / secretsnot the labno credentials in images or YAML beyond local Compose
Resilience4jretries of *this* POST are the idempotency keytimeout + breaker on a *downstream* charge
Idempotent PATCHstatus changes are not replaysclient must send the version it last read

Say this: the unique key and the version column are the correctness. The

happy-path service method is just the story that uses them.

API notes

API notes

Order API notes

Base path: /api/v1. JSON in and out. Controllers never return JPA entities.

Resources

POST /api/v1/orders

Creates an order in CREATED. Requires header Idempotency-Key (1–128 chars).

Request:

json

{
  "customerId": "uuid",
  "items": [
    { "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }
  ]
}

Validation: customerId required; items not empty; each quantity >= 1;

unitPrice >= 0.01.

Response 201 with Location: /api/v1/orders/{id} and body:

json

{
  "id": "uuid",
  "customerId": "uuid",
  "status": "CREATED",
  "items": [{ "productId": "uuid", "quantity": 1, "unitPrice": 10.00 }],
  "totalAmount": 10.00,
  "createdAt": "2026-09-11T21:00:00Z",
  "updatedAt": "2026-09-11T21:00:00Z",
  "version": 0
}

Idempotency: same key + same body replays the original 201 and body. Same key +

different body → 409 IDEMPOTENCY_KEY_CONFLICT. Missing key → 400

MISSING_IDEMPOTENCY_KEY.

GET /api/v1/orders/{id}

200 or 404 ORDER_NOT_FOUND.

GET /api/v1/orders

Query: page (default 0), size (default 20, max 100). Sorted by createdAt desc.

json

{
  "content": [],
  "page": 0,
  "size": 20,
  "totalElements": 0,
  "totalPages": 0,
  "first": true,
  "last": true
}
PATCH /api/v1/orders/{id}/status

json

{ "status": "CONFIRMED", "version": 0 }

version must match @Version on the row. Mismatch → 409 OPTIMISTIC_LOCK_CONFLICT.

Illegal transition → 409 ORDER_STATE_CONFLICT.

Allowed transitions:

  • CREATED → CONFIRMED, CANCELLED
  • CONFIRMED → PROCESSING, CANCELLED
  • PROCESSING → SHIPPED, CANCELLED
  • SHIPPED, CANCELLED are terminal

Errors

json

{
  "timestamp": "2026-09-11T21:00:00Z",
  "status": 404,
  "code": "ORDER_NOT_FOUND",
  "message": "Order not found: …",
  "correlationId": "…",
  "errors": []
}

Validation failures use 400 VALIDATION_ERROR and populate errors with

{ "field", "message" }.

Send X-Correlation-Id to pin a request. The filter echoes it on the response

and puts it in MDC / error JSON. If omitted, the filter generates a UUID.

Design notes

Design notes

Design notes (interview talking points)

Layering

  • Controller: HTTP mapping, Bean Validation, headers. No persistence, no business rules.
  • Service: @Transactional boundary, status machine, totals, idempotency, event publish.
  • Repository: Spring Data JPA only.
  • Mapper: entity ↔ DTO. Controllers never return Order / OrderItem.

Constructor injection everywhere. No field @Autowired.

Optimistic locking

Order.version is @Version. The client sends the version it last read on

PATCH …/status. Hibernate increments on each flush. A stale writer gets

ObjectOptimisticLockingFailureException, mapped to 409 OPTIMISTIC_LOCK_CONFLICT.

Why not last-write-wins? Two operators confirming vs cancelling the same order

must not silently clobber each other.

Idempotent create

Mobile clients retry POST after timeouts. The service persists

idempotency_key (unique), a SHA-256 of the request body, and the serialized

response. Replay is a read, not a second insert. A unique constraint plus a

DataIntegrityViolationException retry handles two in-flight requests with the

same key.

Same key, different body is a client bug → 409, not a second order.

The key is stored in the database, not an in-memory map, so two instances of

the service cannot both insert.

Async event

ApplicationEventPublisher publishes OrderCreatedEvent inside the create

transaction. The listener is @TransactionalEventListener(AFTER_COMMIT) +

@Async so a failed listener cannot roll back the order, and the work does not

sit on the request thread. MDC (correlationId) is copied onto the async

thread via a TaskDecorator.

This lab does not introduce a broker. In production the same event would become

an outbox row or a message.

Correlation ID

CorrelationIdFilter reads X-Correlation-Id or generates one, stores it in

MDC, and echoes the header. GlobalExceptionHandler copies it into the error

JSON so a 404 in logs, traces, and the client payload share one id.

Transactions and Open Session in View

spring.jpa.open-in-view=false. Lazy Order.items are loaded with

@EntityGraph on repository methods. Mapping happens inside the service

transaction.

@Transactional lives on the service, not the controller: the HTTP layer

should not hold a database connection while writing the response.

Column-level tables, the POST transaction, and PATCH …/status are in

low-level-design.md.

What we left out on purpose

  • Resilience4j — this lab is about API + persistence + retries of *this* service.
  • Spring Security / secrets — no credentials in images or YAML beyond local

Compose defaults overridden by env vars.

  • MapStruct / Lombok — explicit mapper and constructors are easier to talk through.

You will

  • Walk the timed sections
  • Leave with a score that does not predict hiring

Mock interview brief5 min

Mock interview brief

Mock interview process

In one sentence: Treat the mock like a real loop — clarify, code a small correct slice, place it in an Order service, and defend the production risk.

Before the timer

Read your Module 0 weak skills. Tell the interviewer (or the player) your target mode: JAVA_BACKEND_ENGINEER, SENIOR_JAVA_ENGINEER, or LEAD_JAVA_ENGINEER. If you stay quiet, they will probe the default for your enrollment profile.

Have a blank editor, not your notes. You may ask for the same things you would Monday: “Is the payment API idempotent? What must not happen twice?”

Opening script (use it)

“I’ll clarify the unit of work and the unacceptable failure, then I’ll write a small correct version, then I’ll show where it lives in an Order service and what we do on retry.”

That is write it, build it, explain it. Silence is not mysterious; it is empty.

During the coding block

  1. Repeat the prompt in one sentence (POST /orders must not double-create).
  2. Write types and the sad path (null key, empty lines, currency mismatch).
  3. Implement the happy path.
  4. Narrate the test you would add.
  5. Stop and invite questions — do not gold-plate a mapper framework.

If you are stuck, say what you are deciding. “I’m choosing a unique constraint over a lock because we have two instances” is senior. Staring is not.

Spoken probes (expect these)

  • Composition vs inheritance on OrderService
  • equals/hashCode for a map key
  • PECS in one sentence
  • HashMap lookup conceptually
  • Constructor injection
  • N+1 on order + lines
  • Where @Transactional lives and what rolls back
  • Idempotency key + outbox

Answer in 60–90 seconds, then stop. If they want depth, they will ask.

Production follow-up

They will change one fact: “the client retried,” “inventory is a separate service,” “p99 doubled after a deploy.” Evolve one box. Do not redraw the system. Say what you give up.

Lead/staff: they may ask you to coach a junior who field-injected everything and returned entities. Teach in the room.

Scoring

The rubric is weighted (see downloads/mock-interview-scorecard.md):

DimensionWeight
Core Java15%
Collections / functional10%
Concurrency / JVM12%
Spring Boot15%
API / persistence10%
Coding quality12%
Production engineering10%
Architecture / trade-offs8%
Communication8%

The number is a rehearsal score. It does not predict a hiring outcome. Say that to yourself so you do not negotiate the rubric instead of learning.

After the mock

Write three lines before you leave the chair:

  1. What you would keep
  2. The first follow-up that hurt
  3. The sentence you will memorize tonight

Then go to Module 7 and turn those lines into a 7-day plan.

COMMON MISTAKE: Arguing that Kafka was required after they asked for a single-service design. You can evolve later. You cannot unhear a candidate who would not start simple.

INTERVIEW TIP: If you finish early, add the test names and the failure case, not a new microservice.

Mock interview50 min

Mock interview

Module 6 — Mock Interview

Duration: 45–60 minutes · Kind: interview

The mock is a rehearsal, not a verdict. It uses the same shape as a Java backend loop: a short coding or API design prompt, spoken Core Java / Spring probes, and one production follow-up (retry, N+1, or inventory race).

Modes

ProfileMock modeWhat gets heavier
ENGINEERJAVA_BACKEND_ENGINEERCorrect code, collections, basic Spring
SENIOR_ENGINEERSENIOR_JAVA_ENGINEERTransactions, N+1, idempotency, testing
LEAD_STAFFLEAD_JAVA_ENGINEEROwnership, dual write, failure budget, coaching the room

Difficulty is selected from your enrollment profile. You can still practice a harder mode; say so at the start so the interviewer does not waste probes.

Shape of the hour

text

5 min   — prompt + clarifying questions
20 min  — code or API sketch (Order create / payment / inventory)
15 min  — spoken probes (HashMap, PECS, constructor injection, JPA)
10 min  — production (idempotency, outbox, traces)
5 min   — you recap trade-offs

Open with the write-build-explain sentence: small correct version, then where it lives, then the risk.

Rubric (weighted)

Core Java 15% · Collections / functional 10% · Concurrency / JVM 12% · Spring Boot 15% · API / persistence 10% · Coding quality 12% · Production 10% · Architecture / trade-offs 8% · Communication 8%

The player scorecard matches downloads/mock-interview-scorecard.md. The disclaimer is mandatory: this measures rehearsal against the BayLearn rubric. It does not predict a hiring outcome.

How to fail the mock (avoid these)

  • Silent typing for ten minutes
  • HashMap is “an array of lists” and then you stop — no equals contract
  • Field injection “because everyone does it”
  • “I’d add Kafka” with no owner for the write
  • Arguing the interviewer instead of saying what you give up

How to pass the room

Ask what must not happen twice. Write the sad path. When they change the scale, evolve one box, do not redraw the universe.

Open the mock process lesson before you start the timer.

You will

  • Leave with practice, not a hiring prediction

Feedback and interview plan10 min

Feedback and interview plan

Feedback and 7-day plan

In one sentence: Turn the mock into three drills and a week of spoken practice — the certificate is optional, the plan is what you take home.

How to read the report

Do not average the bars. Interviews fail closed on the dimension the loop cares about. A 90 in Core Java and a 40 in Production means you will write a clean Money type and then double-charge.

Compare Module 0 to the mock:

If Module 0 was low in…And the mock still wobbled…The plan is…
Types / equalsLost map key storyRewrite OrderId daily from memory
CollectionsWrong structureTeach the decision table out loud
ConcurrencyInventory raceDraw two threads, then the SQL fix
SpringField injectionRebuild OrderService with finals
JPAN+1Count queries on a list endpoint
ProductionRetry / outboxWrite the paragraph until it is boring

If a bar went up, keep a light review (one question) so it does not decay. Spend the hours on the bar that did not move.

Three artifacts to keep

  1. First sentences — write the opening line of your five weakest answers. Example: “I compose a PaymentGateway so I can swap fakes and avoid a fragile OrderService hierarchy.”
  2. One coding kata — Money, idempotency handler, or stream groupingBy. Timebox 15 minutes.
  3. One production paragraph — idempotency + outbox + correlation ID. This is what separates staff answers.

7-day plan (45–70 minutes a day)

Day 1 — Core Java. Composition vs inheritance. equals/hashCode. Immutable Money. Speak each answer once without notes.

Day 2 — Collections & streams. Decision guide. HashMap sketch. Group payments by status. Explain why you would not parallelStream a JPA repository.

Day 3 — Concurrency & JVM. Inventory lost update. volatile vs atomic vs lock. Heap vs stack vs metaspace. One thread-dump story.

Day 4 — Spring & REST. Constructor injection. @ControllerAdvice. Status codes for create/retry/not found. DTO vs entity.

Day 5 — JPA & production. N+1 fix. @Transactional rollback rules. Idempotency store. Outbox vs after-commit listener. Re-run ./mvnw test in the lab.

Day 6 — Bank & review. Ten questions from the 165+ bank out loud. One code-review exercise. One debugging scenario. Do not skim.

Day 7 — Dress rehearsal. 45-minute self-mock. Use the scorecard honestly. Run downloads/final-interview-checklist.md the night before the real loop.

What not to do

  • Rebuild a side project instead of speaking answers.
  • Collect more annotations.
  • Retake the readiness test until the number is pretty.
  • Add Kafka to the lab to feel senior.

Certificate

When the sprint path is complete, BayLearn can issue a course-completion certificate. It is not an industry certification and it is not a hiring recommendation. Put the 7-day plan on your calendar; put the certificate in a folder.

Interview questions to leave on a sticky note

  • Composition or inheritance for OrderService?
  • What breaks if you skip hashCode?
  • PECS in one example?
  • How does HashMap look up a key?
  • Why constructor injection?
  • How do you see and fix N+1?
  • How is POST /orders idempotent?
  • What happens if you publish then crash?

If you can teach those eight to a colleague, you used the sprint.

COMMON MISTAKE: A 14-day list of blog posts. Seven focused days beat a syllabus you will not touch.

INTERVIEW TIP: Book the spoken practice like a meeting. Interviews are oral exams with a compiler.

Pricing

Choose a delivery mode. BayAreaLa8s invoices after you request a session.

This text is a draft. It is not a current BayLearn offer and it does not change existing bookings. Read the draft refund policy

Self-paced

$49

Small group

$119

Live 1:1

$349

Introductory $299

Book Your Interview Sprint

Request a slot. Invoicing is handled by BayAreaLa8s after the request — no Stripe checkout.

Log in or enroll to request a live session time.