Java Materials
Java & Backend Engineering

Java Materials.

Study how Java and backend systems work, from class loading to distributed transactions. Follow diagrams, read code, and practice explaining your decisions.

Explore topics
Java 8 · groupingBy and counting
items.stream()
     .collect(groupingBy(
         Function.identity(),
         counting()
     ));

// {Pen=2, Eraser=1}

Explore the curriculum

10 topics · 44 lessons

Core Java

From source code and objects to concurrency and JVM diagnostics.

JDK, bytecode and class loading

  1. Java source
  2. javac
  3. Class file
  4. JVM

The JDK provides the compiler and other development tools. javac checks source code against the Java language rules and emits bytecode. At runtime a class loader locates a class definition. Linking verifies bytecode, prepares static storage and resolves symbolic references, potentially lazily. Initialization executes static field initializers and static blocks before active use, such as invoking a static method.

A class is identified by its binary name and defining class loader. Two loaders can define classes with the same name and still produce incompatible types. The JVM may interpret bytecode and compile hot methods to machine code. Use javap -c to inspect bytecode and -Xlog:class+load=info on modern JDKs to trace class loading.

Example
javac -d out Hello.java
javap -c -classpath out Hello
java -Xlog:class+load=info -cp out Hello
Why might reading a static final primitive constant skip class initialization?

A compile-time constant can be inlined into the caller. The caller then uses a literal without triggering active use of the declaring class.

Types, operators and control flow

  1. Input
  2. Type conversion
  3. Condition
  4. Result

Java has eight primitive types and reference types. A reference variable holds a reference value or null. Widening conversions can lose precision when converting an integer to a floating-point type. Narrowing conversions require a cast in many contexts and can discard information. Integer division truncates toward zero. Use parentheses when precedence could obscure intent.

Arrays have fixed length and perform bounds checks. Reference arrays are covariant and check component compatibility at runtime. Use loop invariants to reason about traversal: before iteration i, a running total should describe elements 0 through i-1. Short-circuit && evaluates the right operand only when the left operand is true.

Example
int[] prices = {90, 105, 120};
long total = 0;
for (int price : prices) {
    if (price >= 100) total += price;
}
System.out.println(total); // 225
What does 100000 * 100000 assigned to long produce?

The multiplication occurs as int and overflows before the assignment. Use a long operand such as 100000L.

Objects, constructors and parameter passing

  1. Caller reference
  2. Copied reference
  3. Shared object

Java passes every argument by value. When the value is a reference, caller and callee can use their respective copies to reach the same object. Assigning a new reference to a parameter changes the local parameter. Mutating the shared object can be observed by the caller.

A constructor establishes invariants. A final reference prevents reassignment but still permits mutation through the reference if its object is mutable. Use defensive copies when taking ownership of mutable arguments. Avoid calling overridable methods in constructors because subclass state might still be uninitialized.

Example
static void append(List<String> items) {
    items.add("Pen");
    items = new ArrayList<>();
}
// The caller observes the added Pen.
Will assigning a new list inside reset(List<String> items) replace the caller’s list?

The parameter holds a local copy of the reference. To replace the caller’s value, return a new list and assign it in the caller.

Inheritance, interfaces and polymorphism

  1. Payment interface
  2. Card implementation
  3. Runtime dispatch

Use interfaces to define behavior at a boundary and composition to assemble collaborators. Overload selection occurs at compile time using declared types. Overridden instance methods dispatch at runtime using the receiver’s actual type. Static methods are hidden and resolved using the type.

A subtype should preserve its parent contract. If an implementation throws for a required operation or weakens promised guarantees, callers lose substitutability. Default interface methods can evolve APIs. If unrelated interfaces supply conflicting defaults, the implementing class must resolve the conflict.

Example
interface Pricing { int fee(int amount); }
class FlatPricing implements Pricing {
    public int fee(int amount) { return 10; }
}
Pricing pricing = new FlatPricing();
System.out.println(pricing.fee(200)); // 10
What happens when a Parent variable holds Child and calls an overridden method?

The compiler checks that Parent exposes the method. Runtime dispatch selects the Child override.

Strings, wrappers and immutability

  1. Input text
  2. Immutable string
  3. Derived string

String instances are immutable. Compile-time string constants are interned. Use equals for content and == for reference identity. Repeated concatenation in a loop can allocate a fresh result each iteration. StringBuilder accumulates changes in a mutable buffer and is appropriate for a thread-confined construction operation.

Autoboxing converts primitives to wrapper references. Identity comparisons between wrappers can give different results depending on cached instances. Unboxing a null Integer throws NullPointerException. For decimal money arithmetic, construct BigDecimal from decimal text and choose an explicit rounding policy.

Example
String input = "Java";
String upper = input.toUpperCase(java.util.Locale.ROOT);
System.out.println(input); // Java
System.out.println(upper); // JAVA
Why do some Integer values compare true with ==?

Boxing can reuse cached objects. Use equals for non-null value comparison or Objects.equals for nullable references.

Equality, HashMap and mutable keys

  1. Key
  2. Hash bucket
  3. Equality check
  4. Entry

A hash map uses a hash to narrow the search and equals to find the matching key. Equal objects must have equal hash codes. Unequal objects may collide. HashMap accepts a null key, supplies no iteration-order guarantee, and needs external coordination for concurrent structural mutation.

If fields used by equals and hashCode change after insertion, a subsequent lookup can search the wrong bucket. Make keys immutable. When a record contains a mutable collection, its generated equality and hash may still reflect mutations of that collection.

Example
record OrderKey(String customer, long orderId) {}
var orders = new java.util.HashMap<OrderKey, String>();
orders.put(new OrderKey("C1", 42), "PAID");
System.out.println(orders.get(new OrderKey("C1", 42)));
How do you release a lookup bug caused by previously persisted mutable key objects?

Rebuild the map using immutable snapshots of the keys. Test that mutations of the original input no longer affect lookup.

Collections and complexity

  1. Access pattern
  2. Pick collection
  3. Measure cost

ArrayList offers indexed access and amortized constant-time append. LinkedList can unlink a node in constant time once the iterator is positioned, but locating an index requires traversal. ArrayDeque serves stack and queue workloads. HashSet tests membership with expected constant time given sound hash distribution, while TreeSet uses comparison order and logarithmic lookups.

Collections.unmodifiableList creates a read-only view backed by its source. List.copyOf creates an unmodifiable list representing the current elements but preserves references to those elements. Prefer the interface that expresses the contract. For order-sensitive systems specify the order explicitly and test it with duplicate or equal keys.

Example
var pending = new java.util.ArrayDeque<String>();
pending.addLast("order-1");
pending.addLast("order-2");
System.out.println(pending.removeFirst()); // order-1
Which map supports deterministic insertion-order iteration?

LinkedHashMap in its default insertion-order mode. TreeMap gives comparator order.

Generics and wildcards

  1. List of Integer
  2. Number producer
  3. Typed consumer

Generic parameters express compile-time constraints. List<Integer> is independent of List<Number> because List<Number> permits insertion of other Number subtypes. A List<? extends Number> can supply Number values. A List<? super Integer> can accept Integer values, and reads are only safely typed as Object.

Type erasure removes most generic type arguments at runtime. The compiler inserts casts where needed and can generate bridge methods to preserve polymorphism. Raw types bypass generic checks and can move type errors to runtime.

Example
static <T> void copy(java.util.List<? extends T> source,
                     java.util.List<? super T> target) {
    for (T item : source) target.add(item);
}
Why can you read Number from a list of ? extends Number but cannot insert a Double?

The actual list might be List<Integer>. The bound guarantees the type of values read while leaving the concrete element type unknown.

Exceptions and resource lifecycles

  1. Acquire
  2. Use
  3. Close
  4. Report failure

Checked exceptions must be handled or declared. Unchecked exceptions include RuntimeException and its descendants. Catch exceptions where the program can recover or translate a failure into a meaningful boundary contract. Preserve the cause when translating.

Try-with-resources closes successfully opened resources in reverse declaration order. If the body throws and close also throws, the body exception remains primary, and close failures are available as suppressed exceptions. When a method catches InterruptedException and cannot rethrow it, restoring the interrupt flag can preserve cancellation intent.

Example
static String firstLine(java.nio.file.Path path) throws java.io.IOException {
    try (var reader = java.nio.file.Files.newBufferedReader(path)) {
        return reader.readLine();
    }
}
Which exception wins if both resource use and close fail?

The exception from the body propagates, with the close failure attached as a suppressed exception.

I/O, NIO and encoding

  1. Bytes
  2. Charset decoder
  3. Characters
  4. Lines

Streams transfer bytes. Readers and writers bridge between bytes and characters using a charset. Specify UTF-8 when reading or writing a known format. Paths represent filesystem locations, and Files provides operations such as streaming lines, copying and creating temporary files.

Use buffered streaming for large inputs and close streams from Files.lines. For replacements write to a temp file in the same filesystem and consider an atomic move where supported. Atomic visibility and crash durability are separate properties. Test missing files, malformed text and partial writes at the boundary.

Example
try (var lines = java.nio.file.Files.lines(path,
        java.nio.charset.StandardCharsets.UTF_8)) {
    long errors = lines.filter(line -> line.startsWith("ERROR")).count();
    System.out.println(errors);
}
Why can readAllLines be a poor choice for a 4 GB log?

It loads all decoded lines into memory. Stream and process incrementally to bound retention.

Threads and the Java Memory Model

  1. Thread A writes
  2. Happens-before edge
  3. Thread B reads

Threads share heap objects and have separate call stacks. A data race occurs when conflicting accesses to the same location, including a write, lack a happens-before ordering. Synchronization establishes visibility and ordering through edges such as monitor unlock to a subsequent lock on the same monitor, or volatile write to a subsequent read of that field.

Volatile makes individual accesses visible under the memory model but count++ still reads, increments and writes separately. AtomicInteger provides atomic increments. Use a lock when a compound invariant spans multiple fields. Avoid holding a shared lock while waiting on a remote dependency.

Example
var counter = new java.util.concurrent.atomic.AtomicInteger();
Runnable request = () -> counter.incrementAndGet();
Does volatile int make count++ safe?

No. Two threads can read the same value and overwrite each other’s increments. Use incrementAndGet or synchronize the update.

Executors, futures and backpressure

  1. Requests
  2. Bounded queue
  3. Worker pool
  4. Dependency

An executor owns scheduling policy. Choose worker and queue bounds with the downstream service and latency budget in mind. Unbounded queues retain more work during overload and can grow even when worker count looks stable. Pick an explicit rejection policy and propagate a clear overload signal.

CompletableFuture composes asynchronous stages. thenCompose flattens a dependent asynchronous step, and thenCombine combines independent results. Provide an explicit executor for blocking work and apply timeouts at the I/O boundary. Timing out a future can leave its underlying task running.

Example
var pool = new java.util.concurrent.ThreadPoolExecutor(
    4, 4, 0L, java.util.concurrent.TimeUnit.SECONDS,
    new java.util.concurrent.ArrayBlockingQueue<>(100),
    new java.util.concurrent.ThreadPoolExecutor.AbortPolicy());
try {
    var task = pool.submit(() -> 42);
    System.out.println(task.get(1, java.util.concurrent.TimeUnit.SECONDS));
} finally {
    pool.shutdown();
}
What would you observe during a slow downstream incident?

Queue depth, rejection rate, active workers, dependency latency and request timeout rates reveal where work accumulates.

Heap, stacks, garbage collection and diagnostics

  1. GC roots
  2. Reachable objects
  3. Retained heap

Stack frames hold local variables and operand stacks. Objects and arrays generally live on the heap from the application’s perspective. Modern JVM optimizations may avoid some allocations. HotSpot stores class metadata in native metaspace. GC identifies reachable objects from roots such as live thread references and loaded-class statics.

A Java memory leak often means objects remain reachable beyond their useful lifetime. Compare class histograms over time, inspect dominators and paths to GC roots, and correlate with allocation and GC telemetry. A high allocation rate can cause latency without increasing post-GC retained heap.

Example
jcmd PID GC.class_histogram
jcmd PID JFR.start name=profile duration=60s filename=profile.jfr
A cache grows after every deployment and heap usage remains high after GC. What do you inspect?

Inspect the retaining references and cache eviction limits. If old class loaders dominate memory, inspect retained threads, static caches and ThreadLocal values.

Annotations, reflection and modules

  1. Class metadata
  2. Inspect members
  3. Check access

Annotations carry metadata. SOURCE retention is for compile-time processing, CLASS keeps metadata in bytecode, and RUNTIME exposes it to reflection. Reflection can inspect a class and invoke members dynamically, which frameworks use for component discovery and binding.

The Java module system distinguishes exports for public API access and opens for deep reflection. An accessible class can still contain private members that reflective callers cannot reach across module boundaries. Prefer a framework-compatible configuration that opens only the required package.

Example
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@interface Audited {}
@Audited class TransferService {}
// TransferService.class.isAnnotationPresent(Audited.class) is true.
What is the purpose of opens in module-info.java?

It permits deep reflective access to the specified package, optionally limited to named modules.

Enums, nested classes and object contracts

  1. Allowed states
  2. Enum value
  3. Domain operation

Enums declare a finite set of instances and can contain fields, constructors and behavior. EnumSet and EnumMap specialize collections for enum values. Use declared names or explicit stable codes when persisting a value. Ordinals change when constants are reordered.

A static nested class has no enclosing instance. An inner class can retain a reference to its enclosing object, which affects lifecycle if the inner instance is stored elsewhere. Prefer explicit dependencies when designing long-lived callbacks.

Example
enum PaymentState { PENDING, CAPTURED, REFUNDED }
var completed = java.util.EnumSet.of(PaymentState.CAPTURED, PaymentState.REFUNDED);
Why might a non-static inner listener retain an entire service?

The listener instance can reference the enclosing service. A registry that retains the listener can thereby keep the service reachable.

Java 8

Functional programming, collection pipelines and modern date/time APIs.

Lambdas and functional interfaces

  1. Input
  2. Function object
  3. Method contract
  4. Output

A lambda supplies an implementation of a functional interface’s single abstract method. The target type determines the signature, so the same lambda syntax can fit different compatible interfaces. Predicate tests a value, Function transforms one, Consumer performs an action, and Supplier creates or obtains a value.

A lambda can capture local variables that are final or effectively final. An effectively final reference can still point to mutable state, so captured mutable objects need the same concurrency discipline as any shared object. Method references are a compact form of a compatible invocation.

Example
java.util.function.Function<String, String> key = java.util.function.Function.identity();
System.out.println(key.apply("Pen")); // Pen
What does Function.identity() return?

A function equivalent to value -> value. Applying it returns the input unchanged, including the same reference for an object.

Streams, groupingBy and counting

  1. Pen, Eraser, Pen
  2. Identity classifier
  3. Group by key
  4. Pen 2, Eraser 1

A stream pipeline has a source, intermediate operations and a terminal operation. Filter and map are lazy; a terminal operation triggers traversal. For groupingBy(Function.identity(), counting()), the classifier uses each element as its own key, and the downstream collector maintains the count for that key.

The source list stays intact. A stream cannot be reused after a terminal operation. Avoid side effects in intermediate stages, and use a map supplier when the contract requires a specific map implementation. With a sequential ordered stream, LinkedHashMap keeps the first occurrence order of groups.

Example
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

class Stationery {
    public static void main(String[] args) {
        List<String> items = Arrays.asList("Pen", "Eraser", "Pen");
        Map<String, Long> counts = items.stream().collect(
            Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
        System.out.println(counts); // {Pen=2, Eraser=1}
    }
}
Why does counting() produce Long values?

Its downstream reduction counts elements and returns a boxed long per group, so the map has type Map<String, Long>.

Reduction and parallel streams

  1. Source partitions
  2. Partial reductions
  3. Combine
  4. Result

A parallel stream may divide input and combine partial results. A reduction function must be associative and its identity must act as a neutral element. Subtraction makes the grouping of intermediate operations affect the answer. A mutable shared accumulator invites races, while collect provides a framework-managed mutable reduction.

Parallelism has coordination costs. Splitting an array and performing CPU-heavy independent work can be promising. Blocking network calls or cheap operations over tiny sources often perform poorly. Benchmark with representative data and test invariants against a sequential baseline.

Example
int total = java.util.stream.IntStream.of(1, 2, 3, 4)
    .parallel().reduce(0, Integer::sum);
Why is reduce(10, Integer::sum) wrong for a parallel total plus ten?

Each partition can start at ten. Use zero to calculate the sum and add ten once after reduction.

Optional, interface defaults and date/time

  1. Nullable value
  2. Optional pipeline
  3. Value or fallback

Optional expresses a possibly missing result. map transforms a present value; flatMap composes functions returning Optional. orElse evaluates its argument before the call, while orElseGet invokes a supplier only on absence. Default interface methods provide inherited behavior and can support API evolution.

Instant denotes a point on the timeline. LocalDate describes a calendar date, while LocalDateTime lacks a zone or offset. Convert a local appointment using its ZoneId and account for daylight-saving gaps and overlaps. Inject a Clock when testing time-sensitive logic.

Example
String name = java.util.Optional.ofNullable(input)
    .map(String::trim).filter(s -> !s.isEmpty()).orElseGet(() -> "Guest");
java.time.Instant now = java.time.Instant.now(clock);
What happens if orElse calls the database for a fallback?

The database call runs even when a value is present. Put it inside the supplier passed to orElseGet for lazy fallback.

Java 17

Language changes available on 17, migration considerations and JVM features.

Records and sealed hierarchies

  1. Sealed result
  2. Success record
  3. Failure record

Records generate accessors, a canonical constructor, equals, hashCode and toString around declared components. A compact constructor validates or normalizes incoming components before assignment. Immutability is shallow, so copy mutable inputs where required. Records became final in Java 16.

Sealed types became final in Java 17. They constrain direct subtypes, which must be final, sealed or non-sealed, with records implicitly final. In a named module permitted types must be in the same module. In an unnamed module they must be in the same package.

Example
sealed interface Result permits Success, Failure {}
record Success(long orderId) implements Result {}
record Failure(String reason) implements Result {}
When might a record be a poor ORM entity?

A typical ORM entity can require a mutable lifecycle, a no-argument constructor or subclass proxies. Records work naturally as DTOs and immutable values.

Switch expressions, instanceof and text blocks

  1. Object input
  2. Pattern check
  3. Typed value
  4. Result

Switch expressions became final in Java 14. Arrow cases avoid fall-through, and yield supplies a value from a case block. Text blocks became final in Java 15 and are useful for structured multiline text. Incidental indentation processing and the placement of the closing delimiter affect the resulting string.

Pattern matching for instanceof became final in Java 16. Its binding variable is in scope only where the match is known to have succeeded, such as the right side of &&. Pattern matching for switch is a preview feature in Java 17 and requires preview flags in that release.

Example
static String label(Object input) {
    if (input instanceof String text && !text.isBlank()) {
        return switch (text.trim()) {
            case "P" -> "Pending";
            case "D" -> "Done";
            default -> "Unknown";
        };
    }
    return "Missing";
}
Which of these is final in Java 17, instanceof patterns or switch patterns?

instanceof patterns are final. The Java 17 switch pattern feature is preview.

Migration from Java 8 to 17

  1. Dependency audit
  2. Compile on 17
  3. Integration tests
  4. Observe rollout

The migration spans more than language syntax. Java 17 strongly encapsulates JDK internals, and modules such as JAXB were removed from the JDK in earlier releases. Upgrade dependencies, annotation processors, agents and build plugins. Use jdeps to find references to internal APIs and run integration tests on the real deployment runtime.

Java 17 also added the RandomGenerator API and deprecated the Security Manager for removal. Between Java 8 and 17, the standard HTTP client became available in 11 and Stream.toList became available in 16. Stream.toList returns an unmodifiable list. Record these version boundaries in interviews and build configuration.

Example
jdeps --jdk-internals app.jar
javac --release 17 Example.java
java -version
An old library reflects into java.base and fails on 17. What would you do?

Upgrade to a supported implementation and isolate the failing call in a test. A narrowly scoped --add-opens can be a temporary migration bridge.

Spring & Spring Boot

Bean lifecycles, configuration, HTTP APIs, transactions and operations.

Inversion of control and bean lifecycle

  1. Bean definition
  2. Instantiate
  3. Inject
  4. Initialize
  5. Expose bean

The Spring container creates beans from configuration and injects collaborators. Constructor injection makes required dependencies visible and enables plain unit tests. The singleton scope means one instance per container and bean definition. Keep request-specific state out of shared singleton fields.

Bean post-processors can wrap an instance in a proxy to apply cross-cutting behavior. Initialization callbacks run during lifecycle processing. Avoid depending on advice such as transaction interception from an initialization callback.

Example
@Service
class OrderService {
    private final OrderRepository repository;
    OrderService(OrderRepository repository) {
        this.repository = repository;
    }
}
Why does constructor injection expose a circular dependency?

Each constructor needs the other instance before construction can complete. Extract a shared responsibility or redesign the dependency direction.

Auto-configuration and external settings

  1. Classpath and properties
  2. Conditions
  3. Bean definitions
  4. Application context

Spring Boot starters group dependencies. Auto-configuration evaluates conditions such as classes on the classpath, property values and missing beans. A user-defined bean can cause a default to back off if its configuration checks that the bean is missing.

Bind groups of settings with configuration properties. Validate expected ranges at startup, and supply environment-specific values through external configuration. Read the condition evaluation report when a bean is missing or unexpectedly enabled. Protect runtime configuration and operational endpoints from public access.

Example
@ConfigurationProperties("orders")
public record OrderSettings(java.time.Duration timeout, int maxAttempts) {}
// Enable binding with @ConfigurationPropertiesScan or @EnableConfigurationProperties.
What would you inspect when an auto-configured client fails to appear?

Check dependency versions, the condition evaluation report, active settings and any user bean that causes the default to back off.

REST controllers, validation and tests

  1. HTTP request
  2. Binding and validation
  3. Service
  4. HTTP response

Spring MVC maps HTTP requests to controllers. Convert inbound JSON to request DTOs, validate at the boundary and enforce business invariants inside the service or domain layer. Return meaningful status codes and use a stable error response contract. Keep persistence concerns outside the controller.

Test binding, endpoint authorization and error serialization at the MVC boundary. Use integration tests for database transactions and real schema constraints. Production observability should include latency, status code, dependency timing and correlation identifiers that contain no credentials.

Example
record CreateOrder(@jakarta.validation.constraints.Positive long sku) {}

@PostMapping("/orders")
ResponseEntity<Void> create(@Valid @RequestBody CreateOrder request) {
    long id = orders.place(request.sku());
    return ResponseEntity.created(java.net.URI.create("/orders/" + id)).build();
}
Where do you test that invalid JSON is rejected with HTTP 400?

At the MVC boundary using MockMvc or an HTTP integration test. A direct Java method call skips request binding.

Transactional proxies and persistence

  1. Caller
  2. Spring proxy
  3. Transactional method
  4. Commit or rollback

With proxy-based Spring transactions, calling a transactional method through its proxy starts or joins a transaction. Self-invocation bypasses the proxy. Default rollback behavior covers unchecked exceptions and errors. Configure rollback rules for checked exceptions where the operation must roll back.

A database transaction protects participating work on its transactional resources. HTTP and broker operations have separate failure boundaries. Keep transactions short and use a transactional outbox to record events alongside committed domain state. Inspect query counts to find ORM N+1 reads and select a fetch plan that fits each endpoint.

Example
@Transactional
public void place(Order order) {
    orders.save(order);
    outbox.save(OrderPlaced.from(order));
}
A transactional method catches an exception and returns normally. What can happen?

The proxy can see a successful return and commit unless the transaction was already marked rollback-only. Test the actual persisted state.

Microservices Patterns

Reliable cross-service operations and failure containment.

Saga orchestration and choreography

  1. Order pending
  2. Reserve stock
  3. Authorize payment
  4. Confirm or compensate

A saga coordinates local commits across services. Orchestration puts progress and timeout decisions in a coordinator. Choreography uses events to trigger participants. In an order flow, failed payment can trigger a stock release and transition the order to cancelled.

Compensation is another business operation. Refunding a captured payment can incur a fee or take time. Persist saga state, define idempotent commands and record compensation outcomes. Handle ambiguous timeouts by querying provider status or retrying with the same operation key.

Example
PENDING -> STOCK_RESERVED -> PAID -> CONFIRMED
STOCK_RESERVED -> PAYMENT_FAILED -> STOCK_RELEASED -> CANCELLED
Payment timed out after the provider may have charged. What does the saga do?

Resolve the ambiguous outcome using the provider transaction key. Issue a refund only if required by the confirmed outcome and saga state.

Transactional outbox and idempotency

  1. Database transaction
  2. Outbox relay
  3. Event broker
  4. Idempotent consumer

Save domain state and its event in the same database transaction. A polling relay or CDC pipeline publishes committed outbox rows. If the relay dies after publishing and before marking completion, it can publish again.

A consumer can store an event ID with its database update in one local transaction. Use a unique constraint so concurrent deliveries cannot both apply the same effect. When the effect calls a third-party API, use its idempotency mechanism and reconcile uncertain outcomes.

Example
BEGIN;
UPDATE orders SET status = 'PAID' WHERE id = 42;
INSERT INTO outbox(event_id, aggregate_id, event_type)
VALUES ('ord-42-paid-v1', 42, 'OrderPaid');
COMMIT;
Why does an outbox consumer still need deduplication?

The producer’s database commit and broker acknowledgement are separate. The relay can retry an event the broker already received.

Timeouts, retries, circuit breakers and bulkheads

  1. Deadline
  2. Bounded attempt
  3. Failure policy
  4. Response

Start with an end-to-end deadline. Give each downstream call a smaller budget that includes connection and response time. Retry transient failures only when the operation is safe to replay, and use bounded attempts with jitter. Avoid retries at several layers because their effects multiply.

A circuit breaker can stop calls temporarily after failures cross a threshold and probe recovery later. Bulkheads reserve separate capacity for dependencies or traffic classes. Pair these techniques with metrics and load tests. A fallback must have a defined business meaning, such as showing a recent cached catalog with a freshness timestamp.

Example
Request deadline: 800 ms
Dependency attempt budget: 200 ms
Maximum attempts: 2, within the remaining deadline
Isolation: separate bounded checkout executor
Two layers each allow three total attempts. How many requests reach the dependency in the worst case?

Nine attempts. Allocate a shared budget or assign retries to one layer.

Gateway, service discovery and service data

  1. Client
  2. Gateway
  3. Service discovery
  4. Service-owned database

A gateway routes client traffic and can enforce shared policies such as authentication and rate limits. Services still enforce resource-level authorization. Service discovery resolves a logical name into reachable instances, which can change during rollout and scaling.

Database per service means each service owns its schema and write rules. Teams can sometimes share database infrastructure while retaining logical ownership. For cross-domain reads, compose service APIs for fresh data or project events into a read model when latency and availability need looser coupling.

Example
GET /orders/42/summary
Gateway -> Order read API -> Projection store
Orders and shipments publish events to maintain the projection.
How should an order dashboard combine orders and shipment data?

Choose API composition if fresh status and modest fan-out meet the budget. Use a materialized projection when read latency and independence matter, and expose data freshness.

System Design

Practice capacity estimates, request flows and consistency trade-offs.

URL shortener

  1. Create link
  2. Store by code
  3. Cache lookup
  4. Redirect

Start by separating writes that allocate short codes from reads that resolve them. For 10 million redirects per day, the average is roughly 116 requests per second. A 10 times peak assumption raises the design target to about 1,160 redirects per second before headroom.

Make code unique using a database constraint and retry collisions for randomly generated codes. Cache by code and protect the store from stampedes. If links can expire or be revoked, choose cache TTLs and purge behavior around that requirement. A temporary redirect gives the service more control over future destination changes.

Example
POST /links {"destination":"https://example.org/article"}
201 {"code":"r7KaX2"}

GET /r/r7KaX2
302 Location: https://example.org/article
What happens when a viral link expires in cache?

Many requests can load the same key simultaneously. Coalesce misses and decide whether serving stale data is acceptable under the revocation policy.

Payments and an auditable ledger

  1. Idempotent request
  2. Payment intent
  3. Provider
  4. Ledger and reconciliation

Persist a payment intent keyed by client scope and idempotency key. Track an explicit pending state while contacting the provider. Repeating a key with the same request can return the existing intent. Reject reuse with different request parameters.

Treat webhooks as potentially duplicated and delayed. Authenticate them, deduplicate events and apply permitted state transitions. A double-entry ledger records balanced postings and makes corrections auditable through new entries. Reconcile provider settlement against local records to uncover missed or ambiguous events.

Example
POST /payments
Idempotency-Key: checkout-42-v1
202 {"paymentId":"pay-42","status":"PENDING"}
GET /payments/pay-42
What should you return after a timed-out provider call?

A pending representation with a status endpoint or a retry-safe response contract. Resolve the true outcome before recording a definitive failure or sending a second charge.

Notifications and asynchronous fan-out

  1. Business event
  2. Preferences
  3. Channel queues
  4. Providers

Separate notification intent from provider delivery. Resolve consent, channel preferences and templates. Use per-channel queues and rate limits so a slow email provider cannot consume SMS capacity. Track individual delivery attempts with a stable ID.

Queue age is often more useful than queue depth because it expresses user-facing delay. Classify transient provider errors for bounded retry, and route permanently failed jobs to a reviewed queue. Suppress duplicate attempts where provider semantics allow and measure delivery outcomes independently from broker acknowledgements.

Example
Delivery key = eventId + recipientId + channel
States = SCHEDULED, SENT, RETRYABLE, FAILED, SUPPRESSED
How do you avoid sending a notification after consent was withdrawn?

Define the consent cutoff, recheck eligibility near dispatch where needed and audit the decision per delivery.

Kafka

Partitioned logs, delivery guarantees and production diagnostics.

Topics, partitions, consumer groups and offsets

  1. Producer key
  2. Topic partition
  3. Group consumer
  4. Offset commit

Kafka appends each record to a partition log and assigns its offset within that partition. Ordering is partition-scoped. Key events by an entity ID when its records must share a partition, and plan partition expansion carefully because common partitioners can remap keys when the partition count changes.

Consumers in one group share partition assignments. Different groups consume independently. A committed offset represents the next position to read on recovery. Parallel processing inside a partition must preserve required business ordering and advance commits only past completed contiguous work.

Example
orders partition 0: offset 40 -> offset 41 -> offset 42
After processing offset 41, commit 42 as the next offset.
What happens when there are six consumers and four partitions in a group?

At most four consumers receive partition assignments for that topic. Extra consumers may remain idle.

Producer durability and replication

  1. Producer
  2. Partition leader
  3. In-sync replicas
  4. Acknowledgement

A partition leader handles writes while followers replicate the log. With acks=all, the leader waits for all current in-sync replicas. min.insync.replicas sets the minimum in-sync replica count required for writes using acks=all.

Using three replicas and a minimum of two in-sync replicas allows writes with one unavailable replica if the partition still has two in sync. Under further loss, writes fail to preserve the chosen durability policy. Producer idempotence helps prevent duplicates caused by supported producer retries.

Example
// Illustrative topic and producer settings
replication.factor=3
min.insync.replicas=2
acks=all
enable.idempotence=true
What does acks=all guarantee when only one replica is in sync?

It can acknowledge with only one in-sync replica if the topic permits it. Configure min.insync.replicas to enforce the intended floor.

Consumer recovery and exactly-once boundaries

  1. Read
  2. Apply effect
  3. Commit offset
  4. Resume

Committing before processing risks skipping work after a crash. Committing after processing allows replay if the consumer crashes after the effect and before the commit. For a database effect, use a unique event ID and apply the business change in the same database transaction as the deduplication record.

Kafka transactions can make consumed offsets and produced Kafka records atomic for Kafka-to-Kafka processing. Downstream consumers use read_committed to read committed transactional records. External database writes remain outside that Kafka transaction.

Example
poll -> begin DB transaction -> insert unique event ID
     -> apply business update -> commit DB -> commit Kafka offset
How do you verify consumer recovery?

Kill the consumer after the database commit and before the offset commit. Restart, confirm replay and assert that the effect occurs once.

RabbitMQ

Routing, delivery acknowledgements and work queues.

Exchanges, queues and routing keys

  1. Publisher
  2. Exchange
  3. Binding rule
  4. Queue

A publisher sends to an exchange, which routes to queues based on bindings. A direct exchange matches the routing key exactly. A topic exchange supports dot-delimited matching where * consumes one word and # consumes zero or more. A fanout exchange routes to all bound queues.

One message routed to two queues creates independent deliveries for subscribers. Multiple workers sharing one queue compete for its deliveries. This lets a billing queue and analytics queue each receive an event while workers within either queue share load.

Example
Exchange: orders.events (topic)
Routing key: order.created.eu
Binding: order.created.* -> invoice.jobs
Binding: order.#         -> audit.jobs
Does a publisher confirm prove a message matched a queue?

A confirm can acknowledge an unroutable publication. Use mandatory publishing and handle returned messages when the application needs to detect missing routes.

Acknowledgements, prefetch and dead letters

  1. Queue
  2. Worker
  3. Ack on success
  4. Dead-letter route on terminal failure

A publisher confirm describes broker handling of a publication. A consumer acknowledgement tells RabbitMQ a delivered message can be removed. With manual acks, a connection loss before acknowledgement can result in redelivery. Persist work and deduplicate before acknowledging.

Use prefetch to limit in-flight deliveries. Immediate requeue of a poison message can create a hot loop. Classify failures and bound retry attempts, then dead-letter terminal failures where configured. Confirm retention and durability requirements and consider quorum queues for replicated workloads.

Example
Success -> basic.ack
Retryable error -> retry with delay and bounded attempts
Permanent error -> basic.reject with requeue=false -> configured DLX
A worker commits the invoice and dies before ack. What happens?

The message can be redelivered. Use a unique invoice command ID so replay finds the already-created invoice and can acknowledge safely.

SQL

Relational modeling, query design and transactional correctness.

Keys, joins, grouping and window functions

  1. Orders
  2. Join customer
  3. Group rows
  4. Filter groups

A primary key identifies a row and a foreign key protects referential integrity. Use a unique constraint for independent business identities and a check constraint for invariants such as positive quantity. Normalize facts by ownership so updates happen in one authoritative place.

INNER JOIN returns matching rows. LEFT JOIN preserves unmatched left rows with nulls on the right. Filtering right-side fields in WHERE can remove those null-extended rows. Window functions compute metrics across a partition while retaining individual rows. GROUP BY collapses rows into groups.

Example
SELECT id, customer_id, total,
       ROW_NUMBER() OVER (
           PARTITION BY customer_id ORDER BY total DESC, id
       ) AS position
FROM orders;
How do you find ranked orders while preserving order details?

Use a window function such as ROW_NUMBER partitioned by customer and ordered by total with a stable tie-breaker.

Indexes and execution plans

  1. SQL predicate
  2. Planner estimates
  3. Access path
  4. Measured work

An index trades storage and write overhead for faster access to suitable queries. A composite B-tree on customer_id and created_at can support a query filtering by customer and scanning recent orders in timestamp order.

Read plans from the inner operations outward. Compare estimated rows with actual rows and examine buffer usage. Poor estimates may come from stale statistics or correlated predicates. An index scan can be slower than a sequential scan when the query needs much of a table.

Example
CREATE INDEX orders_customer_recent
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM orders WHERE customer_id = 42
ORDER BY created_at DESC LIMIT 20;
Why can an index on created_at alone disappoint on a per-customer query?

The database may scan many other customers’ recent rows before finding enough matches. A composite index can narrow by customer and order the matching range.

Isolation, locks and concurrency

  1. Read and write
  2. Database isolation
  3. Commit or retry

ACID describes the transaction’s atomicity, consistency, isolation and durability. Isolation behavior depends on the database and level. A read-then-write balance adjustment can lose updates if two transactions compute from the same stale value.

Use an atomic conditional update for a simple invariant, a locking read for a coordinated multi-step mutation, or optimistic locking with a version column. At serializable isolation, the database can abort transactions that cannot safely fit a serial order. Retry the complete operation after a serialization failure.

Example
UPDATE inventory SET stock = stock - 1
WHERE sku = 'SKU-42' AND stock > 0;
-- Proceed only if the affected-row count is 1.
How do you prevent overselling one remaining unit?

Perform an atomic update that decrements only when stock is positive and verify exactly one row changed.

NoSQL

Model for access patterns across documents, caches and distributed tables.

Document databases and aggregate boundaries

  1. Query pattern
  2. Document shape
  3. Index
  4. Atomic update

Document stores can keep related data together for reads and updates. An order document can embed a bounded set of line items while referencing customer data that changes independently. Bound document growth and add indexes for actual filters and sorts.

MongoDB guarantees atomicity for a single-document write. Use a conditional filter when an update must depend on the current state. Multi-document transactions are available for operations requiring them, with additional coordination and operational cost.

Example
db.orders.updateOne(
  { _id: 42, status: "PENDING" },
  { $set: { status: "PAID" } }
)
Would you embed the complete order history inside a customer document?

Keep order history separately because it grows without a natural bound and is commonly paginated. Embed only bounded data with a shared lifecycle.

Redis and cache-aside

  1. Read cache
  2. Miss loads database
  3. Cache with TTL
  4. Return

Cache-aside lets an application control cache reads and fills. On a miss, fetch from the database and populate Redis with a TTL. Invalidating after commit reduces stale reads, but a concurrent miss can refill older data after invalidation.

Choose TTL bounds around the allowed staleness and add jitter to reduce synchronized expiry. Use single-flight loading to reduce duplicate database reads. Handle cache downtime with bounded database load. Decide which commands and multi-key operations remain viable in Redis Cluster.

Example
GET product:42
# On miss, fetch from the database and cache the value:
SET product:42 '{"name":"Pen"}' EX 300
What metrics expose a cache stampede?

Cache misses spike alongside duplicate backend reads, database latency and queue growth. Correlate that with expirations of hot keys.

Partition keys, consistency and hot spots

  1. Access pattern
  2. Partition key
  3. Replica set
  4. Read or write

Distributed stores route operations using partition keys. Choose a key that distributes load and supports the expected queries. A time-series workload can use device ID plus day to bound a partition. A very busy device may still need finer buckets or write sharding.

CAP describes the consistency and availability trade-off during a network partition. Some systems let clients choose consistency policies per operation. Evaluate reordering, clock assumptions and conflict resolution under replica lag, then measure the effect on latency and availability.

Example
Query: recent events for one device on one day
Partition key: (device_id, event_day)
Clustering order: event_time descending
Why can partitioning only by date overload a cluster?

Most writes land on today’s key. Combine time bucketing with a high-cardinality dimension that fits the read pattern.