Practice

Answer out loud, then open the model answer. Filters stay in the address so you can share a view.

Flashcards Mock interview

Tracks

520 questions

  1. What is the difference between a class and an object in Java?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Concept

    Show answer

    A class is a blueprint: it declares fields and methods once. An object is one instance of that class, created with new on the heap, with its own copy of the instance fields. Variables do not hold objects; they hold references that point at them. Static members belong to the class and are shared by every object.

    • A class defines state and behavior; an object is a runtime instance with its own field values.
    • new allocates the object on the heap, sets default values, runs the constructor and returns a reference.
    • A variable of a class type holds a reference, so two variables can point at the same object.
    • Static members belong to the class; instance members belong to each object.
    Car a = new Car("red");   // class Car, object on the heap
    Car b = a;                // second reference, same object

    Go to the module

  2. What happens, step by step, when you write new Car("red")?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Concept

    Show answer

    The JVM loads the Car class if it is not loaded yet, allocates heap memory for the object, sets every field to its default value, runs the constructor, and returns a reference to the new object.

    • Class loading happens once, on first use of the class.
    • Fields hold default values before the constructor body runs.
    • new returns a reference, which the variable stores.

    Go to the module

  3. What is the difference between static and instance members?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Comparison

    Show answer

    An instance member belongs to each object: every object has its own copy of an instance field, and instance methods run on one object through this. A static member belongs to the class: one copy of a static field is shared by all objects, and static methods run without any object.

    • Instance field: one copy per object.
    • Static field: one copy per class, shared by every object.
    • Static methods have no this, so they cannot read instance fields directly.

    Go to the module

  4. After Car b = a; and b.color = "blue";, what is a.color, and why?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Code

    Show answer

    It is "blue". Car b = a copies the reference, not the object, so a and b point at the same Car. A change made through b is visible through a.

    • Assignment copies the reference, never the object.
    • Both variables now reach one object.
    • Create a new object explicitly when you need an independent copy.
    Car a = new Car("red");
    Car b = a;
    b.color = "blue";
    System.out.println(a.color); // blue

    Go to the module

  5. Does calling a static method through a null reference throw a NullPointerException?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Code

    Show answer

    No. The compiler binds a static call to the variable's declared type, so c.total() with c null runs as Counter.total(). An instance method called through the same null reference throws NullPointerException. Call static methods through the class name to avoid the confusion.

    • Static calls use the variable's declared type, not the object.
    • Instance calls need an object and throw on null.
    • Write Counter.total(), not c.total().
    Counter c = null;
    c.total(); // runs: compiled as Counter.total()
    c.value(); // NullPointerException

    Go to the module

  6. Why can't a static method read an instance field directly?

    Object-Oriented Programming (OOP) Classes, objects and references Junior Concept

    Show answer

    A static method runs without an object, so there is no this to say whose field to read. Three Counter objects have three count fields; the static method must be handed one of the objects, for example as a parameter.

    • Static methods have no this.
    • Instance fields exist once per object, so the method must name the object.
    • Pass the object in, or make the method an instance method.

    Go to the module

  7. Can you explain encapsulation, abstraction, inheritance and polymorphism with one example?

    Object-Oriented Programming (OOP) The four pillars Junior Concept

    Show answer

    Take a Shape hierarchy. Encapsulation: Shape keeps its color private and exposes methods. Abstraction: Shape declares area() and callers use only that. Inheritance: Circle extends Shape and reuses it. Polymorphism: a loop over a List of Shape calls area() on each element, and the JVM (Java Virtual Machine) runs Circle's or Square's version depending on the object.

    • Encapsulation hides state behind methods, so the class controls every change to it.
    • Abstraction exposes what an object does and hides how it does it.
    • Inheritance lets a subclass reuse and specialize a parent: a Circle is a Shape.
    • Polymorphism runs the override of the actual object behind a parent-type reference.
    • Use one running example for all four; it shows how they work together.
    List<Shape> shapes = List.of(new Circle(1), new Square(2));
    for (Shape s : shapes) total += s.area();

    Go to the module

  8. What is the difference between encapsulation and abstraction?

    Object-Oriented Programming (OOP) The four pillars Junior Comparison

    Show answer

    Abstraction is the outside view: a type exposes what it does, like area(), and hides how. Encapsulation is the inside: the class hides its state and controls access to it. Abstraction designs the contract; encapsulation protects the implementation behind it.

    • Abstraction: what callers see and depend on.
    • Encapsulation: how the class protects its own data.
    • Both shrink what callers need to know.

    Go to the module

  9. Why make fields private instead of public?

    Object-Oriented Programming (OOP) The four pillars Junior Concept

    Show answer

    A private field changes only through the class's own methods, so the class can validate every change, keep its rules true and later change how it stores the data without breaking callers. A public field lets any class in the program break it.

    • Methods can validate input and keep the object valid.
    • The internal representation can change without breaking callers.
    • When a value is wrong, there are fewer places to look.

    Go to the module

  10. What is the difference between private, package-private, protected and public?

    Object-Oriented Programming (OOP) The four pillars Junior Comparison

    Show answer

    Each one widens the one before. private: only the declaring class. Package-private, the default with no keyword: any class in the same package. protected: the same package plus subclasses in other packages. public: every class.

    • No keyword means package-private, not public.
    • protected also opens the member to the whole package, not only to subclasses.
    • Start with the narrowest access that works.

    Go to the module

  11. How does polymorphism show up in a loop over a list of shapes?

    Object-Oriented Programming (OOP) The four pillars Junior Code

    Show answer

    The loop calls area() through a Shape reference. Each element is really a Circle or a Square, and the JVM runs that class's area(). Adding a Triangle means writing a new class, not changing the loop.

    • The reference type is Shape; the object decides which method runs.
    • New shapes extend the program without editing the loop.
    List<Shape> shapes = List.of(new Circle(1), new Square(2));
    for (Shape s : shapes) {
        System.out.println(s.area()); // Circle's, then Square's
    }

    Go to the module

  12. When is inheritance the wrong way to reuse code?

    Object-Oriented Programming (OOP) The four pillars Mid-level Design

    Show answer

    When the subclass is not truly a kind of the parent, or only wants some of its methods. Extending a class to borrow code ties the subclass to the parent's internals, so a change in the parent can break it. Holding the other object as a field, composition, reuses the code without that tie.

    • Inherit for an is-a relationship, not for code reuse alone.
    • A subclass depends on how its parent is implemented.
    • Prefer composition when only the behavior is needed.

    Go to the module

  13. What is the difference between overloading and overriding?

    Object-Oriented Programming (OOP) Overloading vs overriding Junior Comparison

    Show answer

    Overloading is several methods with the same name and different parameters; the compiler picks one from the declared types it sees. Overriding is a subclass redefining an inherited method with the same signature; the JVM (Java Virtual Machine) picks the version from the object's class at runtime. Overloading is compile-time polymorphism, overriding is runtime polymorphism.

    • Overloading: same name, different parameter lists, chosen by the compiler from declared types.
    • Overriding: same signature in a subclass, chosen at runtime from the actual object.
    • A different return type alone does not make an overload.
    • Static, private and final methods cannot be overridden.
    • Add @Override so the compiler catches a signature typo.
    Animal a = new Dog();
    greet(a); // greet(Animal) by type, then Dog's speak() by object

    Go to the module

  14. What is the difference between compile-time and runtime polymorphism?

    Object-Oriented Programming (OOP) Overloading vs overriding Junior Comparison

    Show answer

    Compile-time polymorphism is overloading: javac picks a method from the declared types of the arguments, and that choice is fixed in the bytecode. Runtime polymorphism is overriding: the JVM picks the method from the object's class every time the call runs.

    • Compile time: overloads, chosen by declared types.
    • Runtime: overrides, chosen by the object's class.
    • One call can use both, as greet(a) with an Animal variable holding a Dog shows.

    Go to the module

  15. How does the JVM pick which overridden method to run?

    Object-Oriented Programming (OOP) Overloading vs overriding Mid-level Concept

    Show answer

    The bytecode names the method of the declared type, like Animal's speak(). At runtime the JVM takes the actual object, follows its header to its class and runs that class's version, the most specific override. HotSpot makes this fast with a per-class method table, the vtable, but Java only specifies the behavior.

    • The call site names a method; the object picks the implementation.
    • The lookup starts at the object's class and walks up through its parents.
    • vtables are a HotSpot implementation detail, not a language rule.

    Go to the module

  16. With overloads f(Object) and f(String), which one does f(null) call?

    Object-Oriented Programming (OOP) Overloading vs overriding Junior Code

    Show answer

    f(String). null fits both, and the compiler picks the most specific overload, and String is a subtype of Object. With f(String) and f(Integer) instead, f(null) does not compile, because neither is more specific.

    • The compiler picks the most specific applicable overload.
    • Two unrelated candidates make the call ambiguous.
    static void f(Object o) { System.out.println("Object"); }
    static void f(String s) { System.out.println("String"); }
    f(null); // String

    Go to the module

  17. If Animal and Dog both declare static String kind(), what does a.kind() run for Animal a = new Dog()?

    Object-Oriented Programming (OOP) Overloading vs overriding Junior Code

    Show answer

    Animal's kind(). Static methods are not overridden; the one in Dog only hides Animal's. The call is bound at compile time to the declared type, Animal, so the object does not matter.

    • Static methods are hidden, not overridden.
    • The declared type decides, as it does for overloads.
    • Call static methods through the class name.
    Animal a = new Dog();
    a.kind();   // Animal's kind(): static, chosen by type
    Dog.kind(); // Dog's kind()

    Go to the module

  18. What rules must an overriding method follow?

    Object-Oriented Programming (OOP) Overloading vs overriding Junior Concept

    Show answer

    The same name and parameter types, and a return type that is the same or a subtype. It cannot narrow visibility, so a public method stays public, and it cannot throw broader checked exceptions. Final, static and private methods cannot be overridden.

    • Same signature; a covariant return type is allowed.
    • Visibility can widen, never narrow.
    • Checked exceptions can narrow, never widen.
    • Add @Override so mistakes fail to compile.

    Go to the module

  19. When would you use an abstract class instead of an interface?

    Object-Oriented Programming (OOP) Abstract class vs interface Junior Comparison

    Show answer

    Use an interface for a capability or contract that unrelated classes can implement, several at once. Use an abstract class when closely related classes share state, constructor logic or a fixed sequence of steps with parts to fill in. Many designs use both: an interface for callers, and an abstract class implementing it for reuse.

    • Interface: a contract with no instance state; a class can implement many.
    • Abstract class: shared fields, constructors and protected helpers; a class extends only one.
    • Default methods let an interface grow without breaking its implementers.
    • Callers depend on the interface; the abstract class is an implementation aid.
    interface PaymentGateway { Receipt charge(Money amount); }
    abstract class AbstractGateway implements PaymentGateway { /* shared retry */ }

    Go to the module

  20. Why were default methods added to interfaces in Java 8?

    Object-Oriented Programming (OOP) Abstract class vs interface Junior Concept

    Show answer

    To grow interfaces without breaking every class that implements them. Java 8 added forEach to Iterable and stream to Collection; as default methods with a body, existing implementations inherited them instead of failing to compile.

    • Adding an abstract method to an interface breaks every implementer.
    • A default method supplies a body that implementers may override.
    • Default methods carry behavior, never instance state.

    Go to the module

  21. What happens if a class implements two interfaces that declare the same default method?

    Object-Oriented Programming (OOP) Abstract class vs interface Junior Code

    Show answer

    The class does not compile until it overrides the method. Inside the override it can call one parent's version explicitly with Walker.super.move().

    • Two inherited defaults with one signature are a compile error.
    • The class must override the method and may delegate with Interface.super.method().
    interface Walker  { default String move() { return "walk"; } }
    interface Swimmer { default String move() { return "swim"; } }
    class Duck implements Walker, Swimmer {
        @Override public String move() { return Walker.super.move(); }
    }

    Go to the module

  22. What does multiple inheritance of type mean in Java?

    Object-Oriented Programming (OOP) Abstract class vs interface Junior Concept

    Show answer

    A class can implement many interfaces, so its objects can be used as each of those types: a Duck can be passed wherever a Walker or a Swimmer is expected. It still extends only one class, so it inherits fields and constructors from a single parent.

    • Many types, through interfaces.
    • One superclass, so state comes from one parent.
    • Default methods add inheritance of behavior, with explicit conflict rules.

    Go to the module

  23. Why does an abstract class have a constructor if you cannot instantiate it?

    Object-Oriented Programming (OOP) Abstract class vs interface Junior Concept

    Show answer

    Subclass constructors call it through super(...). It initializes and validates the fields the abstract class declares, so every subclass object starts in a valid state.

    • new on an abstract class does not compile.
    • Every subclass constructor runs its parent's constructor first.
    • It is the one place to validate the shared fields.

    Go to the module

  24. How would you design payment providers that share retry logic but stay pluggable?

    Object-Oriented Programming (OOP) Abstract class vs interface Mid-level Design

    Show answer

    Define a PaymentGateway interface that callers depend on. Add an AbstractGateway that implements it, holds the shared retry and logging code and leaves one protected method, doCharge(), to each provider. Providers extend the abstract class; one that cannot extend it can still implement the interface directly.

    • Callers see only the interface.
    • The abstract class shares the code as a template.
    • The interface stays open to providers that already have another parent.

    Go to the module

  25. Why should you favor composition over inheritance?

    Object-Oriented Programming (OOP) Composition vs inheritance Mid-level Concept

    Show answer

    Inheritance ties a subclass to how its parent is implemented, not just to what it promises. If the parent's methods call each other, an override can change behavior the parent relies on, and a parent update can break the subclass. Composition holds the other object as a field and uses only its public contract, so either side can change.

    • Inheritance is an is-a relationship and exposes the parent's whole API.
    • A subclass depends on its parent's internals: the fragile base class problem.
    • Composition is has-a: hold an object and forward to its public methods.
    • Composition lets you swap the part at runtime and replace it with a fake in tests.
    class CountingSet<E> {          // has a Set, is not one
        private final Set<E> inner;
    }

    Go to the module

  26. What is the difference between an is-a and a has-a relationship?

    Object-Oriented Programming (OOP) Composition vs inheritance Mid-level Comparison

    Show answer

    Is-a is inheritance: a Circle is a Shape and can be used wherever a Shape is expected. Has-a is composition: a Car has an Engine as a field and uses it. Test is-a by substitution; if the subclass cannot stand in for the parent everywhere, the relationship is has-a.

    • Is-a: extends or implements, and substitutable.
    • Has-a: a field, used through its public methods.
    • Failing substitution means has-a, not is-a.

    Go to the module

  27. What is the fragile base class problem?

    Object-Oriented Programming (OOP) Composition vs inheritance Mid-level Scenario

    Show answer

    A subclass that relies on how its parent works can break when the parent changes, or behave wrongly already. A HashSet subclass that counts in both add() and addAll() counts 3 elements as 6, because HashSet's addAll() calls add().

    • The parent's own methods can call your overrides.
    • Those internal calls are rarely part of the documented contract.
    • Composition avoids it, because the inner object never calls the wrapper.
    class CountingSet<E> extends HashSet<E> {
        int count;
        @Override public boolean add(E e) { count++; return super.add(e); }
        @Override public boolean addAll(Collection<? extends E> c) {
            count += c.size();
            return super.addAll(c);
        }
    }
    // addAll(List.of("a", "b", "c")) leaves count at 6

    Go to the module

  28. When is inheritance the right choice?

    Object-Oriented Programming (OOP) Composition vs inheritance Mid-level Design

    Show answer

    When the subclass truly is a kind of the parent and can replace it everywhere, and the parent was designed for extension: it documents which methods call which, and marks the rest final. Template methods and small sealed hierarchies of domain types are good fits.

    • A true is-a relationship that passes substitution.
    • A parent designed and documented for extension.
    • Otherwise, make classes final and compose them.

    Go to the module

  29. Can you explain the SOLID principles, with a violation and a fix for each?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Concept

    Show answer

    S: one reason to change; split a class that prices, saves and emails. O: extend by adding code; replace a discount switch with Discount classes. L: subtypes keep the parent's promises; no refund() that throws. I: small interfaces; a printer should not implement fax(). D: depend on abstractions; inject an OrderRepository instead of calling new MySqlOrderDao().

    • Single responsibility: a class has one reason to change.
    • Open/closed: add behavior with new code, not by editing working code.
    • Liskov substitution: a subtype must work anywhere its parent is expected.
    • Interface segregation: clients depend only on the methods they use.
    • Dependency inversion: high-level code depends on abstractions, and details are injected.
    • Give a concrete violation and its fix for each letter.
    OrderService(OrderRepository repository, Notifier notifier) { ... }
    order.setTotal(discount.apply(order.subtotal())); // no switch

    Go to the module

  30. How do you spot a class that breaks the single responsibility principle?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Scenario

    Show answer

    Ask who would request a change. If pricing rules, the database and email templates all lead to edits in one class, it has three reasons to change. Other signs are many unrelated dependencies, a vague name like OrderManager, and tests that must mock everything.

    • Count the reasons to change, not the methods.
    • Many unrelated fields and imports are a warning sign.
    • Split along the reasons, then let one class coordinate.

    Go to the module

  31. How would you remove a switch on discount type to follow the open/closed principle?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Code

    Show answer

    Turn each case into a class implementing a Discount interface, and let the caller hold a Discount. A new discount type becomes a new class; the code that applies discounts never changes.

    • Each case becomes a class behind one interface.
    • New behavior is added, not edited in.
    • A map or a factory chooses the class in one place.
    interface Discount { Money apply(Money price); }
    class Seasonal implements Discount {
        public Money apply(Money price) { return price.times(0.9); }
    }
    Money total = discount.apply(price); // no switch

    Go to the module

  32. Why is Square extending Rectangle a classic Liskov substitution violation?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Concept

    Show answer

    Rectangle promises that setWidth leaves the height alone. A Square must keep its sides equal, so its setWidth changes the height too. Code written for Rectangle that sets width 5 and height 4 and expects area 20 gets 16 from a Square.

    • Liskov is about behavior, not about whether "is a" sounds right.
    • A subtype cannot weaken the promises of its parent.
    • Fix: do not inherit, or use immutable shapes without setters.

    Go to the module

  33. What is the difference between interface segregation and single responsibility?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Comparison

    Show answer

    Single responsibility is about a class: it should have one reason to change. Interface segregation is about what clients see: an interface should not force a client to depend on methods it does not use. A class can implement several small interfaces and still have one responsibility.

    • Single responsibility looks at the implementation.
    • Interface segregation looks at each client's needs.
    • Split fat interfaces by client.

    Go to the module

  34. Is dependency inversion the same as dependency injection?

    Object-Oriented Programming (OOP) SOLID principles Mid-level Comparison

    Show answer

    No. Dependency inversion is a design rule: high-level code depends on an abstraction it owns, like OrderRepository, and the low-level detail implements it. Dependency injection is a technique: dependencies are passed in instead of created with new. Injection is the usual way to wire inverted dependencies.

    • Inversion decides who owns the interface.
    • Injection decides how an object receives its dependencies.
    • Injecting a concrete class is injection without inversion.

    Go to the module

  35. What do high cohesion and low coupling mean, and why do they matter?

    Object-Oriented Programming (OOP) DRY, KISS, YAGNI, cohesion and coupling Mid-level Concept

    Show answer

    Cohesion is how closely the parts of one class belong together; coupling is how much a class depends on others. Aim for classes whose methods all serve one purpose, connected through small, stable interfaces. Then a change stays inside one class instead of rippling through every class that depends on it.

    • High cohesion: everything in a class serves one purpose.
    • Low coupling: classes depend on few, stable abstractions.
    • A change to a class with many dependents can break all of them.
    • Interfaces, events and narrow method signatures lower coupling.

    Go to the module

  36. What is the Law of Demeter?

    Object-Oriented Programming (OOP) DRY, KISS, YAGNI, cohesion and coupling Mid-level Code

    Show answer

    A method should talk only to its close friends: its own fields, its parameters and objects it creates, not to objects returned by them. order.getCustomer().getAddress().getCity() couples the caller to three classes; asking order.shippingCity() couples it to one.

    • Talk to fields, parameters and objects you create.
    • Chained getters expose another class's internal structure.
    • Chains on one fluent API, such as a builder or a stream, are fine.
    String before = order.getCustomer().getAddress().getCity(); // knows 3 classes
    String after = order.shippingCity();                         // knows 1

    Go to the module

  37. What do DRY, KISS and YAGNI mean?

    Object-Oriented Programming (OOP) DRY, KISS, YAGNI, cohesion and coupling Mid-level Comparison

    Show answer

    DRY, Don't Repeat Yourself: each piece of knowledge has one place in the code. KISS, Keep It Simple, Stupid: choose the simplest design that works. YAGNI, You Aren't Gonna Need It: do not build features or extension points before they are needed. Together they push toward small, direct code that is easy to change.

    • DRY is about knowledge, not about lines that look the same.
    • KISS favors plain code over clever code.
    • YAGNI avoids paying now for needs that may never come.

    Go to the module

  38. A small change to the Pricing class broke five other classes. What would you change?

    Object-Oriented Programming (OOP) DRY, KISS, YAGNI, cohesion and coupling Mid-level Scenario

    Show answer

    Find what those classes actually use from Pricing and put it behind a small interface that they depend on. Pricing implements it, so its internals can change freely. Then ask why five classes call pricing directly; perhaps one service should own that call.

    • Depend on a narrow interface, not on the concrete class.
    • Keep the internals behind that interface.
    • Reduce the number of direct callers.

    Go to the module

  39. What is the difference between the JDK, the JRE and the JVM?

    Java JDK, JRE, JVM and bytecode Junior Comparison

    Show answer

    The JVM is the virtual machine that loads, verifies and runs bytecode and manages memory. The JRE is the JVM plus the standard class library: everything needed to run a program. The JDK is the JRE plus the development tools, such as javac, jar and javap: everything needed to build one. Since Java 11 Oracle ships only the JDK; jlink builds a trimmed runtime instead.

    • JVM: loads, verifies and runs bytecode, interpreting it or JIT-compiling it, and manages memory with garbage collection.
    • JRE = JVM + class library (java.base and the other runtime modules): what you need to run a program.
    • JDK = JRE + tools (javac, jar, javap, jlink, jshell): what you need to build one.
    • The bytecode is portable; each JVM is a native program built for one operating system and CPU.

    Go to the module

  40. What is bytecode?

    Java JDK, JRE, JVM and bytecode Junior Concept

    Show answer

    Bytecode is the instruction set of the JVM, stored in .class files. javac compiles each class to it. The instructions work on an operand stack rather than CPU registers, so return a + b in a static method becomes iload_0, iload_1, iadd, ireturn. Any JVM can run the same class file, interpreting it or compiling it to native code.

    • It is the output of javac and the input of the JVM, not machine code for any real CPU.
    • Instructions push and pop values on an operand stack.
    • javap -c prints a class's bytecode.
    static int add(int a, int b) {
        return a + b;
    }
    // javap -c Hello:
    //   0: iload_0
    //   1: iload_1
    //   2: iadd
    //   3: ireturn

    Go to the module

  41. What does the JIT compiler do?

    Java JDK, JRE, JVM and bytecode Junior Concept

    Show answer

    The just-in-time compiler turns frequently run bytecode into native machine code while the program runs. HotSpot interprets first and counts calls and loop iterations; hot methods are compiled quickly by C1, then again by C2 with heavier optimizations such as inlining, guided by the profile collected so far. If an assumption later breaks, the JVM deoptimizes back to the interpreter.

    • Only hot code is compiled, so startup stays fast and compile time goes where it pays off.
    • Tiered compilation, on by default since Java 8, uses C1 first and C2 for the hottest code.
    • Runtime profiles allow optimizations a compiler cannot prove ahead of time, such as inlining a virtual call.
    • -XX:+PrintCompilation lists each method as it is compiled.

    Go to the module

  42. How does class loading work in Java?

    Java JDK, JRE, JVM and bytecode Junior Concept

    Show answer

    A class is loaded the first time it is used, not at startup. Loading reads the .class bytes; linking verifies them, prepares static fields with default values and resolves references; initialization runs the static initializers. Loaders ask their parent first, from application to platform to bootstrap, so core classes such as String always come from the bootstrap loader.

    • Three steps in order, loading, linking and initialization, each done once per class and loader.
    • Parent-first delegation stops an application from replacing a core class such as String.
    • String.class.getClassLoader() returns null: the bootstrap loader has no Java object.
    • The same class loaded by two loaders is two different runtime classes.
    System.out.println(Hello.class.getClassLoader());
    // jdk.internal.loader.ClassLoaders$AppClassLoader@...
    System.out.println(String.class.getClassLoader());
    // null: the bootstrap loader

    Go to the module

  43. What does "write once, run anywhere" mean, and where does it stop being true?

    Java JDK, JRE, JVM and bytecode Junior Concept

    Show answer

    javac produces bytecode for the JVM, not for a CPU, so the same .class or JAR (Java archive) file runs on any operating system with a compatible JVM. It stops at native code reached through JNI (Java Native Interface), at OS-specific details such as file paths, and at older runtimes: a class compiled for Java 21 fails on Java 17 with UnsupportedClassVersionError.

    • Portability comes from the bytecode and the JVM specification, not from the JVM itself.
    • Each class file records a version; a JVM refuses class files newer than it supports.
    • javac --release N builds class files and API checks for an older Java release.

    Go to the module

  44. What is the trade-off between JIT compilation and ahead-of-time compilation?

    Java JDK, JRE, JVM and bytecode Mid-level Comparison

    Show answer

    A JIT compiles while the program runs, using a profile of how the code actually behaves, so peak throughput is high, but startup is slower, warm-up takes time and the compiler uses memory. Ahead-of-time compilation, as in GraalVM Native Image, compiles before the program runs: it starts in milliseconds with a small footprint, but assumes a closed world, so reflection and dynamic class loading need configuration.

    • JIT: slow start, best peak throughput for long-running services.
    • AOT: instant start and low memory, a good fit for serverless functions and CLI (command-line interface) tools.
    • AOT needs to see all reachable code at build time, so reflection must be declared.

    Go to the module

  45. Where do objects and local variables live in Java, and how do the stack and the heap differ?

    Java Memory: stack vs heap Junior Concept

    Show answer

    Each thread has its own stack. Every method call pushes a frame holding its parameters and local variables: primitives as values, objects as references. Returning pops the frame. Objects and arrays live on the heap, which all threads share, and the garbage collector frees them once nothing references them. So a local Point p sits in a frame, and the Point it points at sits on the heap.

    • A call pushes a frame with its parameters and locals; returning pops it.
    • A primitive local holds its value in the frame; a reference local holds only a reference.
    • Objects, arrays and their fields live on the heap, including a primitive field such as int x.
    • Each thread has its own stack; all threads share one heap.
    • A frame's memory is freed when it pops; an object is reclaimed by garbage collection once it is unreachable.
    static void move(Point q, int x) { q.x = x; }
    
    int n = 99;                // the value 99 sits in main's frame
    Point p = new Point(1, 2); // p in the frame, the Point on the heap
    move(p, n);                // a new frame with copies of p and n

    Go to the module

  46. Is Java pass-by-value or pass-by-reference?

    Java Memory: stack vs heap Junior Concept

    Show answer

    Always pass-by-value. A method receives a copy of each argument. For an object the copied value is a reference, so the method can change the object both variables point at, but reassigning its parameter never changes the caller's variable. That is why swap(p, q) cannot swap the caller's points, while q.x = 99 inside a method is visible to the caller.

    • Every argument is copied into the new frame, primitives and references alike.
    • Through a copied reference, a method can change the shared object's fields.
    • Reassigning a parameter changes only the copy; the caller's variable still points at the same object.
    static void swap(Point a, Point b) { Point t = a; a = b; b = t; }
    static void move(Point q) { q.x = 99; }
    
    Point p = new Point(1, 2), q = new Point(2, 2);
    swap(p, q); // p.x is still 1, q.x still 2
    move(p);    // p.x is now 99

    Go to the module

  47. What is the difference between a StackOverflowError and an OutOfMemoryError?

    Java Memory: stack vs heap Junior Comparison

    Show answer

    A StackOverflowError means one thread's stack has no room for another frame, almost always from recursion that never stops or goes too deep. An OutOfMemoryError such as "Java heap space" means the heap cannot fit a new object even after garbage collection, because live objects fill it. Both extend VirtualMachineError, an Error, and are not meant to be caught and ignored.

    • StackOverflowError: one thread ran out of stack, typically from runaway recursion.
    • OutOfMemoryError: Java heap space: reachable objects fill the heap and garbage collection cannot free enough.
    • Fix the first with a base case or a loop; find the cause of the second in a heap dump.
    • -Xss sets the stack size per thread; -Xmx sets the maximum heap size.
    static void down() { down(); }  // no base case
    down();                         // java.lang.StackOverflowError
    
    List<long[]> keep = new ArrayList<>();
    while (true) keep.add(new long[1_000_000]);
    // with -Xmx32m: java.lang.OutOfMemoryError: Java heap space

    Go to the module

  48. Are local variables thread-safe?

    Java Memory: stack vs heap Junior Concept

    Show answer

    A local variable lives in its own thread's stack frame, so no other thread can read or change it. But a local reference can point at a heap object that other threads also reach, and that object gets no protection from being referenced by a local. Locals are confined to their thread; the objects they point at are safe only if they never escape, are immutable, or are synchronized.

    • Each thread has its own stack, so its locals and parameters are never shared.
    • The heap is shared, so an object two threads reach needs synchronization or immutability.
    • A lambda captures a copy of a local's value, which is why the local must be effectively final.
    int count = 0;
    Runnable r = () -> System.out.println(count);
    count++; // compile error: count must be final or effectively final

    Go to the module

  49. Where do static variables live?

    Java Memory: stack vs heap Junior Concept

    Show answer

    A static field belongs to the class, not to a frame or an object, so there is one copy per loaded class, shared by every thread. HotSpot stores its value with the class's java.lang.Class object on the heap; class metadata sits in Metaspace, outside the heap, since Java 8. An object a static field references stays reachable while the class is loaded.

    • One copy per class, shared by all threads, so writes need synchronization.
    • HotSpot keeps static values with the Class object on the heap and class metadata in Metaspace.
    • An object held by a static field stays reachable, a common cause of memory leaks in caches.

    Go to the module

  50. Does every object created with new end up on the heap?

    Java Memory: stack vs heap Senior Concept

    Show answer

    In the language model, yes. But HotSpot's C2 JIT (just-in-time) compiler runs escape analysis on hot code: an object that never leaves the compiled method, after inlining, can be scalar-replaced, its fields kept in registers or stack slots, so no heap allocation happens at all. It is an optimization of performance, never of behavior, and you see it only in allocation profiles.

    • Escape analysis checks whether an object can be seen outside the method or thread that created it.
    • A non-escaping object can be scalar-replaced, so it is never allocated on the heap.
    • It applies only to JIT-compiled hot code, and the program's results stay the same.
    static int sum(int i) {
        Point p = new Point(i, i + 1); // never leaves sum()
        return p.x + p.y;
    }
    // Once sum() is hot, C2 can remove this allocation.

    Go to the module

  51. How does the garbage collector decide what to collect?

    Java Garbage collection Mid-level Concept

    Show answer

    It traces reachability, not age or usefulness. Starting from the GC roots, such as thread stacks and static fields, it follows references and marks every object it reaches. Anything unmarked can never be used again, so its memory can be reclaimed. That is why an unreachable cycle is freed, and why an unused object that is still referenced is not.

    • GC roots include local variables on thread stacks and the static fields of loaded classes.
    • An object is live if a chain of references leads to it from a root.
    • A cycle with no path from a root is garbage, because tracing never counts references.
    • Reachable does not mean needed: a forgotten reference keeps an object alive.
    • The JVM (Java Virtual Machine) chooses when to collect, so you cannot predict when an object is freed.

    Go to the module

  52. What are the generations of the Java heap, and why do they exist?

    Java Garbage collection Mid-level Concept

    Show answer

    Most objects die young, so the heap is split by age. New objects start in Eden, in the young generation. A minor GC copies the few survivors to a survivor space, which is cheap because dead objects are never copied. Objects that survive long enough are promoted to the old generation, which a major GC collects less often.

    • The classic young generation is Eden plus two survivor spaces, one of them empty between collections.
    • Each minor GC an object survives adds 1 to its age.
    • At the tenuring threshold, at most 15 by default in HotSpot, the object is promoted.
    • G1 and generational ZGC keep the generations but organize them as regions.

    Go to the module

  53. How do G1 and ZGC differ, and when would you choose each?

    Java Garbage collection Senior Comparison

    Show answer

    G1, the default since Java 9 on server-class machines, collects regions in stop-the-world pauses aimed at a target, 200 ms by default. ZGC does nearly all its work concurrently, so pauses typically stay under a millisecond even on large heaps, at the cost of extra CPU and memory. Start with G1; choose ZGC when latency matters most.

    • MaxGCPauseMillis defaults to 200 in G1, and it is a goal, not a guarantee.
    • ZGC relocates objects while the application keeps running.
    • Generational ZGC arrived in Java 21 behind -XX:+ZGenerational, became the default mode in 23 and the only mode in 24.
    • Select ZGC with -XX:+UseZGC, and measure on your own workload before switching.

    Go to the module

  54. Can a Java program leak memory even with garbage collection?

    Java Garbage collection Mid-level Scenario

    Show answer

    Yes. The GC frees only what is unreachable, so an object you no longer need but still reference stays. The classic case is a static collection that only grows, such as a cache with no eviction. The symptom is old generation use climbing after every collection, and eventually an OutOfMemoryError.

    • A Java memory leak is a reachable object that nothing will use again.
    • Common sources are static collections, listeners never removed and ThreadLocal values on pooled threads.
    • Fix it by removing entries or bounding the cache with eviction.
    • Diagnose it with a heap dump, following the path from the object to its GC root.
    class GrowForever {
        private static final Map<Integer, byte[]> CACHE = new HashMap<>();
    
        public static void main(String[] args) {
            for (int i = 0; ; i++) CACHE.put(i, new byte[1_000_000]);
        }
    }
    // java -Xmx64m GrowForever: OutOfMemoryError: Java heap space

    Go to the module

  55. What is the difference between == and equals() when you compare two strings?

    Java String, immutability and final Junior Comparison

    Show answer

    == compares references: it is true only when both sides point at the same object. equals() compares the characters. Two literals with the same text share one object from the string pool, so == can happen to be true, but new String("java") or a string built at runtime is a separate object. Always compare text with equals().

    • == asks whether two references point at the same object; equals() asks whether the characters match.
    • Literals with the same text share one pooled object, so == between them is true.
    • new String(...) and strings built at runtime are separate objects, so == is false.
    • intern() returns the pooled object with the same characters.
    • Write "java".equals(s) or Objects.equals(a, b) to stay safe when a value can be null.
    String a = "java";
    String c = new String("java");
    System.out.println(a == c);          // false: two objects
    System.out.println(a.equals(c));     // true: same characters
    System.out.println(a == c.intern()); // true: the pooled object

    Go to the module

  56. What is the string pool?

    Java String, immutability and final Junior Concept

    Show answer

    The string pool is a table the JVM (Java Virtual Machine) keeps of shared String objects. Every literal with the same text resolves to one pooled object, and intern() adds or finds a string there. Sharing is safe only because a String never changes. Since Java 7, HotSpot keeps the pool in the main heap rather than in PermGen.

    • Literals with the same text share one pooled object.
    • new String(...) always creates a new object outside the pool.
    • intern() returns the pooled copy, adding the string if it is missing.
    • Sharing is safe because String is immutable.

    Go to the module

  57. Why is String immutable in Java?

    Java String, immutability and final Junior Concept

    Show answer

    Because so much code shares strings. Immutability lets literals share one pooled object, lets a String compute its hash code once and cache it, which makes it a reliable HashMap key, and lets threads share it without locks. It also protects security checks: a file path or class name cannot change after it was validated.

    • Pool sharing: one object can serve every literal with the same text.
    • Cached hash: the hash code never changes, so it is computed once.
    • Thread safety: no thread can see a half-changed String.
    • Security: a checked path, URL or class name stays what was checked.
    • Methods like toUpperCase() return a new String and leave the original alone.
    String s = "java";
    s.toUpperCase();          // result ignored
    System.out.println(s);    // java

    Go to the module

  58. Why use StringBuilder instead of += to build a string in a loop?

    Java String, immutability and final Junior Comparison

    Show answer

    Each += creates a new String and copies every character built so far, because a String cannot change. In a loop that is a new object per iteration and work that grows with the square of the length. StringBuilder appends into one buffer and creates a single String with toString(). Outside loops, a + b + c is fine: javac compiles one expression efficiently.

    • s += x in a loop creates one String per iteration and drops the previous one.
    • StringBuilder appends into one buffer that grows only when it runs out of room.
    • toString() creates the single String at the end.
    • A single + expression is already compiled efficiently.
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        sb.append(i);
    }
    String s = sb.toString(); // "0123"

    Go to the module

  59. What is the difference between final, finally and finalize()?

    Java String, immutability and final Junior Comparison

    Show answer

    final is a keyword: a final variable is assigned once, a final method cannot be overridden and a final class cannot be extended. finally is the block after try that runs whether or not an exception was thrown, even after a return. finalize() is an Object method the garbage collector may call before reclaiming an object; it is deprecated for removal since Java 18 (JEP 421, a Java Development Kit Enhancement Proposal).

    • final: assign once, no overriding, no subclassing.
    • finally: cleanup that runs after try and catch, even when the try returns.
    • finalize(): unpredictable and deprecated for removal since Java 18; use try-with-resources or a Cleaner.
    • A return inside finally replaces the try block's return value, so avoid it.
    static int f() {
        try { return 1; }
        finally { return 2; } // f() returns 2
    }

    Go to the module

  60. With String x = "ja";, why is ("ja" + "va") == "java" true but (x + "va") == "java" false?

    Java String, immutability and final Junior Code

    Show answer

    "ja" + "va" is a constant expression, so javac joins it at compile time into the literal "java", which is pooled. x is not a constant, so x + "va" runs at runtime and builds a new String object. Declaring final String x = "ja" makes x a constant variable, and the comparison becomes true. The lesson stays the same: compare with equals().

    • Constant expressions are folded by the compiler into one pooled literal.
    • Concatenation with a non-constant variable creates a new String at runtime.
    • A final local initialized with a constant counts as a constant.
    String x = "ja";
    final String y = "ja";
    System.out.println(("ja" + "va") == "java"); // true: folded
    System.out.println((x + "va") == "java");    // false: runtime
    System.out.println((y + "va") == "java");    // true: constant

    Go to the module

  61. Why must you override hashCode() whenever you override equals()?

    Java The equals and hashCode contract Junior Concept

    Show answer

    Hash-based collections find an object by hashCode() first and call equals() only inside the bucket it picks. The contract says equal objects must return equal hash codes. Override equals() alone and two equal Points keep different identity hashes, so a HashSet or HashMap looks in the wrong bucket and never finds the match. Build both from the same fields.

    • The contract: if a.equals(b) is true, a.hashCode() must equal b.hashCode().
    • The reverse does not hold: equal hashes can belong to unequal objects, a collision.
    • HashMap and HashSet use hashCode() to pick a bucket, then equals() inside it.
    • Compute both from the same fields, for example with Objects.hash(x, y).
    • A record generates both from its components.
    @Override public boolean equals(Object o) {
        return o instanceof Point p && x == p.x && y == p.y;
    }
    @Override public int hashCode() { return Objects.hash(x, y); }

    Go to the module

  62. What breaks in a HashSet if you override equals() but not hashCode()?

    Java The equals and hashCode contract Junior Scenario

    Show answer

    Lookups. Each Point keeps the identity hash it inherits from Object, so an equal Point has a different hash and is searched for in the wrong place: contains() returns false, remove() removes nothing, and add() accepts the duplicate. Nothing throws; the set silently holds two equal elements. HashMap keys break the same way.

    • contains() and remove() miss elements that are equal to one in the set.
    • add() accepts an equal element again, so size() counts it twice.
    • No exception is thrown; the bug shows up as wrong results.
    Set<Point> set = new HashSet<>();
    set.add(new Point(1, 2));
    set.contains(new Point(1, 2)); // false without hashCode()
    set.add(new Point(1, 2));      // true: size() is now 2

    Go to the module

  63. What rules must an equals() implementation follow?

    Java The equals and hashCode contract Junior Concept

    Show answer

    Object's documentation lists five. Reflexive: x.equals(x) is true. Symmetric: x.equals(y) is true exactly when y.equals(x) is. Transitive: if x equals y and y equals z, x equals z. Consistent: repeated calls agree while the compared fields do not change. And x.equals(null) is false. hashCode() must agree with it.

    • Reflexive, symmetric, transitive, consistent, and false for null.
    • Take Object as the parameter; equals(Point) is an overload that collections never call.
    • Compare the same fields that hashCode() uses.

    Go to the module

  64. What happens if you change a field used by hashCode() after adding the object to a HashSet?

    Java The equals and hashCode contract Junior Scenario

    Show answer

    The object stays in the bucket chosen from its old hash. contains() and remove() compute the new hash, look in another bucket and miss, so the element is stuck: you cannot find or remove it, but size() still counts it. Keep key fields immutable, or remove the object, change it, then add it again.

    • The bucket is chosen from the hash at the time of add().
    • contains() and remove() use the current hash and miss.
    • Prefer immutable keys such as String, records and classes with final fields.
    MutablePoint p = new MutablePoint(1, 2);
    set.add(p);
    p.x = 5;
    set.contains(p); // false
    set.size();      // 1

    Go to the module

  65. How do records and Lombok help with equals() and hashCode()?

    Java The equals and hashCode contract Junior Comparison

    Show answer

    A record generates equals(), hashCode() and toString() from all its components, so record Point(int x, int y) gets value equality for free. Lombok's @EqualsAndHashCode, also part of @Data, generates both from the class's fields at compile time. Both remove hand-written mistakes, but you still decide what defines equality, and a mutable field still breaks hash-based collections.

    • A record compares all its components, and its fields are final.
    • Lombok's @EqualsAndHashCode and @Data generate both methods from the fields.
    • A record with a mutable component, such as a List, can still change its hash.
    record Point(int x, int y) {}
    new Point(1, 2).equals(new Point(1, 2)); // true

    Go to the module

  66. If two objects have the same hashCode(), are they equal?

    Java The equals and hashCode contract Junior Concept

    Show answer

    Not necessarily. Equal objects must have equal hashes, but not the other way round: an int has about 4 billion values, and objects can have far more states, so collisions are unavoidable. "Aa" and "BB" both hash to 2112. A HashMap keeps colliding keys in the same bucket and uses equals() to tell them apart.

    • Equal objects imply equal hashes; equal hashes do not imply equal objects.
    • Colliding keys share a bucket, and equals() decides which entry matches.
    • A good hashCode() spreads values so collisions stay rare.
    boolean strings = "Aa".hashCode() == "BB".hashCode();       // true: both 2112
    boolean points = Objects.hash(0, 33) == Objects.hash(1, 2); // true: both 994

    Go to the module

  67. What is the difference between a List, a Set and a Map?

    Java Collections Framework Junior Comparison

    Show answer

    A List is an ordered sequence that allows duplicates and access by index. A Set holds no duplicates; HashSet, LinkedHashSet and TreeSet differ in the order they keep. A Map stores key-value pairs with unique keys. List, Set and Queue extend Collection, but Map does not: you loop over its keySet(), values() or entrySet() views instead.

    • List: ordered, indexed, duplicates allowed; ArrayList by default.
    • Set: no duplicates, judged by equals and hashCode, or by compareTo in a TreeSet.
    • Map: unique keys, each mapped to one value; HashMap by default.
    • List, Set and Queue extend Collection; Map is not a Collection.
    List<String> list = new ArrayList<>(List.of("c", "a", "b", "a")); // [c, a, b, a]
    Set<String> set = new TreeSet<>(list);                            // [a, b, c]
    Map<String, Integer> counts = new TreeMap<>();
    for (String s : list) counts.merge(s, 1, Integer::sum);          // {a=2, b=1, c=1}

    Go to the module

  68. ArrayList or LinkedList, which would you use and why?

    Java Collections Framework Junior Comparison

    Show answer

    ArrayList, almost always. It keeps the elements side by side in one array, so get(i) is O(1) and adding at the end is O(1) amortized; only an insert near the front shifts the rest. LinkedList keeps a node per element: adding or removing at either end is O(1), but get(i) follows links in O(n).

    • ArrayList: get(i) O(1), add at the end O(1) amortized, add(0, x) O(n).
    • LinkedList: add or remove at either end O(1), get(i) O(n).
    • For a queue or a stack, prefer ArrayDeque to LinkedList.

    Go to the module

  69. Which collection would you choose to count words, track unique visitors, or keep tags sorted?

    Java Collections Framework Junior Scenario

    Show answer

    Ask three questions: pairs or single elements, duplicates or not, and which order. Word counts are pairs, so a HashMap, or a TreeMap when the report must be sorted. Unique visitors need no duplicates, so a HashSet. Sorted tags without duplicates fit a TreeSet. Everything else starts as an ArrayList.

    • Pairs: HashMap, LinkedHashMap for insertion order, TreeMap for sorted keys.
    • No duplicates: HashSet, LinkedHashSet or TreeSet, by the same order rule.
    • Otherwise an ArrayList, sorted once if you need sorted output with duplicates.
    Map<String, Integer> counts = new HashMap<>();
    for (String word : words) counts.merge(word, 1, Integer::sum);
    Set<String> visitors = new HashSet<>(visitorIds);
    Set<String> sortedTags = new TreeSet<>(tags);

    Go to the module

  70. What is the Big-O of the common collection operations?

    Java Collections Framework Junior Concept

    Show answer

    ArrayList: get(i) is O(1), add at the end O(1) amortized, contains and an insert in the middle O(n). HashMap and HashSet: get, put and contains are O(1) on average. TreeMap and TreeSet: O(log n), because they are red-black trees. ArrayDeque: adding or removing at either end is O(1). PriorityQueue: offer and poll are O(log n), peek is O(1).

    • Hash-based collections are O(1) on average and rely on a good hashCode.
    • Tree-based collections are O(log n) and keep their keys sorted.
    • contains on a List is O(n): it calls equals on one element after another.

    Go to the module

  71. How do you make an unmodifiable list, and how is List.of different from Collections.unmodifiableList?

    Java Collections Framework Junior Comparison

    Show answer

    List.of, Set.of and Map.of build unmodifiable collections: add or set throws UnsupportedOperationException, and null elements are rejected. List.copyOf takes an unmodifiable copy of another list. Collections.unmodifiableList only wraps a list: the wrapper rejects writes, but changes to the original still show through it.

    • List.of(1, 2).add(3) throws UnsupportedOperationException.
    • List.of rejects null elements with a NullPointerException.
    • unmodifiableList is a read-only view; List.copyOf is a copy.
    List<String> backing = new ArrayList<>(List.of("a"));
    List<String> view = Collections.unmodifiableList(backing);
    List<String> copy = List.copyOf(backing);
    backing.add("b");
    System.out.println(view + " " + copy);   // [a, b] [a]

    Go to the module

  72. What happens if you remove elements from an ArrayList while looping over it with for-each?

    Java Collections Framework Junior Code

    Show answer

    It typically fails with ConcurrentModificationException. The for-each loop uses the list's iterator, which is fail-fast: it remembers the list's modification count and throws when the list changes behind its back. Remove with removeIf, or with remove() on an explicit Iterator.

    • The iterator checks a modification count on every next().
    • list.remove inside the loop changes that count, so the next step throws.
    • Use removeIf, or Iterator.remove() on an explicit iterator.
    • Fail-fast is best effort: removing the second-to-last element ends the loop without an exception.
    List<String> list = new ArrayList<>(List.of("c", "a", "b", "a"));
    for (String s : list) if (s.equals("a")) list.remove(s); // ConcurrentModificationException
    list.removeIf(s -> s.equals("a"));                        // [c, b]

    Go to the module

  73. How does HashMap work internally?

    Java HashMap internals Mid-level Concept

    Show answer

    A HashMap is an array of buckets. put() calls the key's hashCode(), spreads it with h ^ (h >>> 16) and masks it with capacity minus one to pick a bucket. If a key in that bucket is equal by equals(), the value is replaced; otherwise a node is added. When the size passes capacity times load factor, the table doubles.

    • Bucket index: (h ^ (h >>> 16)) & (capacity - 1), so the capacity is always a power of two.
    • A lookup compares stored hashes first, then calls equals() on the keys in that one bucket.
    • Colliding keys share a bucket as a linked list, or as a red-black tree once the list grows long.
    • The default capacity is 16 and the default load factor 0.75, so the first resize comes with the 13th entry.
    • put() returns the previous value for the key, or null when there was none.
    Map<String, Integer> ages = new HashMap<>();
    ages.put("ana", 30);  // returns null: a new entry
    ages.put("ana", 31);  // returns 30: the value is replaced
    ages.size();          // 1

    Go to the module

  74. What happens when two keys collide in a HashMap?

    Java HashMap internals Mid-level Concept

    Show answer

    Both keys land in the same bucket and are stored as a chain of nodes. A lookup goes to that bucket and walks the chain, comparing hashes and then calling equals() until it finds the key. Many collisions turn O(1) lookups into a walk through a long chain, which is why a good hashCode() spreads keys evenly.

    • A collision means the same bucket index, not necessarily the same hashCode().
    • New nodes are added at the end of the bucket's list.
    • A poor hashCode(), such as a constant, puts every key in one bucket.

    Go to the module

  75. What are the load factor and the resize of a HashMap?

    Java HashMap internals Mid-level Concept

    Show answer

    The load factor is how full the table may get before it grows. The threshold is capacity times load factor: with 16 buckets and 0.75 it is 12, so the 13th entry doubles the table to 32 buckets. A resize allocates the new array and moves every node, which costs O(n), so presize a map whose size you know.

    • Default: capacity 16, load factor 0.75, threshold 12.
    • A resize doubles the capacity; each key stays at index i or moves to i plus the old capacity.
    • A lower load factor means fewer collisions but more memory; a higher one the opposite.
    • The table is allocated on the first put, not in the constructor.
    new HashMap<>(4, 0.75f);   // 7 puts: 4 -> 8 -> 16 buckets
    new HashMap<>(16, 0.5f);   // 9 puts: 16 -> 32 buckets

    Go to the module

  76. What is treeification in a HashMap?

    Java HashMap internals Mid-level Concept

    Show answer

    Since Java 8, a bucket whose list passes 8 nodes becomes a red-black tree, so a lookup in a crowded bucket takes O(log n) instead of O(n). It only happens when the table has at least 64 buckets; a smaller table is resized instead. When a resize leaves 6 or fewer nodes in a tree bin, it turns back into a list.

    • OpenJDK constants: TREEIFY_THRESHOLD 8, MIN_TREEIFY_CAPACITY 64, UNTREEIFY_THRESHOLD 6.
    • These are implementation details of OpenJDK, not part of the Map contract.
    • It protects against many colliding keys, for example from a poor hashCode() or crafted input.
    • Comparable keys keep the tree lookup at O(log n) even when their hashes are equal.

    Go to the module

  77. What is the difference between HashMap and ConcurrentHashMap?

    Java HashMap internals Mid-level Comparison

    Show answer

    HashMap is not thread-safe: concurrent puts can lose updates or corrupt the table. ConcurrentHashMap is safe for concurrent use without locking the whole map: in OpenJDK reads take no lock, and a write locks only its one bin, or uses a compare-and-set on an empty bin. It also offers atomic compound operations like merge() and computeIfAbsent(), and rejects null keys and values.

    • Threads writing to different bins of a ConcurrentHashMap do not block each other.
    • Use merge() or compute(), not get() then put(), for an atomic read-modify-write.
    • Its iterators are weakly consistent and never throw ConcurrentModificationException.
    • Collections.synchronizedMap() locks the whole map for every call instead.
    Map<String, Integer> visits = new ConcurrentHashMap<>();
    visits.merge("ana", 1, Integer::sum);  // atomic per key

    Go to the module

  78. Can a HashMap have null keys or null values?

    Java HashMap internals Mid-level Concept

    Show answer

    Yes. A HashMap allows one null key, stored in bucket 0 because its hash is 0, and any number of null values. Because get() returns null both for a missing key and for a null value, use containsKey() to tell them apart. ConcurrentHashMap and Hashtable allow neither and throw NullPointerException.

    • One null key; putting it again replaces its value.
    • get() returning null is ambiguous: missing key or null value.
    • ConcurrentHashMap forbids null so that a null from get() always means "absent".
    Map<String, Integer> m = new HashMap<>();
    m.put(null, 1);
    m.put(null, 2);                            // size 1, get(null) is 2
    new ConcurrentHashMap<String, Integer>()
        .put(null, 1);                         // NullPointerException

    Go to the module

  79. What is the difference between checked and unchecked exceptions?

    Java Exceptions Junior Comparison

    Show answer

    A checked exception is any Exception outside RuntimeException, like IOException: the compiler makes every method that can throw it either catch it or declare it with throws. Unchecked exceptions, RuntimeException and Error with their subclasses, need neither. Use checked ones for failures a caller can expect and recover from, and unchecked ones for bugs such as a null argument.

    • Checked: Exception and its subclasses outside RuntimeException; the compiler enforces catch or declare.
    • Unchecked: RuntimeException, Error and their subclasses; no catch or throws is needed.
    • The check happens only at compile time; at runtime both kinds unwind the stack the same way.
    • Checked exceptions suit recoverable failures, such as a missing file; unchecked ones suit bugs and broken preconditions.
    • A lambda passed to Function or Consumer cannot throw a checked exception, one reason many APIs prefer unchecked ones.
    void load(Path path) throws IOException {   // checked: must declare or catch
        Files.readString(path);
    }
    void charge(Order order) {                  // unchecked: nothing to declare
        if (order == null) throw new IllegalArgumentException("order is null");
    }

    Go to the module

  80. What is the difference between Error and Exception?

    Java Exceptions Junior Comparison

    Show answer

    Both extend Throwable. An Error signals a serious problem in the JVM (Java Virtual Machine) or its environment, such as OutOfMemoryError or StackOverflowError, that a reasonable application should not try to catch. An Exception signals a condition the program may handle, like a missing file or invalid input. Errors are unchecked; exceptions are checked unless they extend RuntimeException.

    • Error: trouble in the JVM or its environment, such as OutOfMemoryError and StackOverflowError; usually not caught.
    • Exception: conditions an application can anticipate and handle.
    • catch (Exception e) does not catch an Error.
    Throwable oom = new OutOfMemoryError();
    System.out.println(oom instanceof Error);      // true
    System.out.println(oom instanceof Exception);  // false: catch (Exception e) misses it

    Go to the module

  81. How does try-with-resources work?

    Java Exceptions Junior Concept

    Show answer

    You declare resources in parentheses after try, and each must implement AutoCloseable. When the block ends, normally or with an exception, Java closes them in the reverse order of opening, before any catch or finally runs. If close() also throws, that exception is added to the body's exception as a suppressed one instead of replacing it.

    • Resources must implement AutoCloseable; Closeable extends it.
    • They close in reverse order, before catch and finally run.
    • A close() failure is attached with addSuppressed(); read it with getSuppressed().
    • Since Java 9, an effectively final variable can be listed directly: try (in) { ... }.
    record Res(String name) implements AutoCloseable {
        Res { System.out.println("open " + name); }
        public void close() { System.out.println("close " + name); }
    }
    
    try (Res a = new Res("A"); Res b = new Res("B")) {
        throw new IllegalStateException("body");
    } catch (IllegalStateException e) {
        System.out.println("catch " + e.getMessage());
    }
    // open A, open B, close B, close A, catch body

    Go to the module

  82. How do you write a custom exception, and should it be checked or unchecked?

    Java Exceptions Junior Code

    Show answer

    Extend Exception for a checked exception or RuntimeException for an unchecked one, name it after the problem, and pass a message and, when you wrap another failure, its cause to super. Make it checked when callers can reasonably recover, like OrderException for an order that cannot be saved, and unchecked when most callers cannot do anything about it.

    • Extend Exception for checked or RuntimeException for unchecked, not Throwable or Error.
    • Offer constructors that take a message and a cause, and pass both to super.
    • Add fields for context, such as the order id, rather than parsing the message.
    class OrderException extends Exception {          // checked
        OrderException(String message, Throwable cause) {
            super(message, cause);
        }
    }
    
    class PaymentException extends RuntimeException { // unchecked
        PaymentException(String message) { super(message); }
    }

    Go to the module

  83. Does finally run if the try block returns? What if finally returns too?

    Java Exceptions Junior Code

    Show answer

    Yes. The return value is computed first, then finally runs, then the method returns, so changing a local in finally does not change an int already being returned. A return in finally wins: try { return 1; } finally { return 2; } returns 2, and it even discards an exception thrown in the try. finally is skipped only if the JVM stops, for example with System.exit().

    • finally runs after a normal end, a return or an exception.
    • The returned value is evaluated before finally runs.
    • A return or throw in finally replaces the outcome of the try; javac -Xlint warns about it.
    static int value() {
        int x = 1;
        try { return x; }      // 1 is evaluated here
        finally { x = 2; }     // too late to change the result
    }
    
    static int override() {
        try { return 1; }
        finally { return 2; }  // wins: the method returns 2
    }

    Go to the module

  84. What is exception translation, and why keep the cause?

    Java Exceptions Junior Concept

    Show answer

    Exception translation means catching a low-level exception and throwing one that fits your layer, with the original as its cause. A repository catches SQLException and throws OrderException. Callers depend on your abstraction instead of JDBC (Java Database Connectivity), and the cause keeps the original failure and its stack trace, printed under "Caused by:".

    • Always pass the original exception as the cause; never drop it.
    • Translate at layer boundaries, so callers see exceptions from their own domain.
    • getCause() returns the wrapped exception.
    void saveOrder(Order order) throws OrderException {
        try {
            repository.save(order);
        } catch (SQLException e) {
            throw new OrderException("could not save order " + order.id(), e);
        }
    }

    Go to the module

  85. What is type erasure in Java generics?

    Java Generics and type erasure Mid-level Concept

    Show answer

    Generics exist for the compiler. javac checks every use of a type argument, then erases it: a List<String> becomes a plain List whose methods take and return Object, and javac inserts a cast where a value is read. At runtime a List<String> and a List<Integer> share one class, which kept generic code compatible with code written before Java 5.

    • The compiler rejects names.add(42) on a List<String>, so the type check happens before the program runs.
    • Erasure replaces a type parameter with its bound: T becomes Object, and T extends Number becomes Number.
    • javac inserts a checkcast where a generic value is read, as in String s = names.get(0).
    • new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass() is true.
    • Erasure is why new T(), new T[n] and o instanceof List<String> on an Object do not compile.

    Go to the module

  86. What is the difference between ? extends and ? super, and what does PECS mean?

    Java Generics and type erasure Mid-level Comparison

    Show answer

    PECS stands for producer extends, consumer super. A List<? extends Number> produces values: every element reads as a Number, but you cannot add one, because the list might be a List<Double>. A List<? super Integer> consumes values: you can add Integers, but reading gives only Object. A list the method both reads and writes takes the exact type, with no wildcard.

    • List<? extends Number> l; l.add(1) is a compile error; null is the only value you can add.
    • Reading a List<? super Integer> gives Object: Integer x = l.get(0) does not compile.
    • Collections.copy(List<? super T> dest, List<? extends T> src) follows the rule: it reads the source and writes the destination.
    • Wildcards widen an API: sum(List<? extends Number>) accepts a List<Integer> and a List<Double>.

    Go to the module

  87. Why can't you write new T() inside a generic class or method?

    Java Generics and type erasure Mid-level Concept

    Show answer

    Because T is erased. The bytecode does not record which class T stands for, so the compiler cannot emit a constructor call, and new T() fails with "unexpected type". For the same reason new T[n] is a "generic array creation" error. Pass the knowledge in instead: a Supplier<T> such as StringBuilder::new, or a Class<T> whose constructor you call through reflection.

    • A Supplier<T> is the type-safe fix, and make(StringBuilder::new) returns a StringBuilder.
    • A Class<T> token also works: type.getDeclaredConstructor().newInstance(), at the cost of checked reflection exceptions.
    • For arrays, use a List<T> or take an IntFunction<T[]>, as Collection.toArray(String[]::new) does.
    static <T> T make(Supplier<T> factory) {
        return factory.get();
    }
    
    StringBuilder sb = make(StringBuilder::new);

    Go to the module

  88. What is a raw type, and why should you avoid it?

    Java Generics and type erasure Mid-level Scenario

    Show answer

    A raw type is a generic type used without type arguments, such as List instead of List<String>. It exists so code written before generics still compiles. The compiler stops checking it and gives only an unchecked warning, so a raw List can put an Integer into a List<String>. The error surfaces later, as a ClassCastException at the cast inserted where the value is read.

    • By default javac prints only a summary note; -Xlint:rawtypes and -Xlint:unchecked warn on each line.
    • The failure is far from the bug, because the add succeeds and a later get throws.
    • Use List<?> for a list of unknown type, which you can read as Object but cannot add to except null.
    List<String> names = new ArrayList<>();
    List raw = names;          // raw type
    raw.add(42);               // unchecked warning, runs
    String s = names.get(0);   // ClassCastException

    Go to the module

  89. What is the difference between intermediate and terminal stream operations?

    Java Streams, lambdas and Optional Junior Comparison

    Show answer

    Intermediate operations such as filter, map and sorted return a new Stream and only describe work; they are lazy. A terminal operation such as collect, count, forEach or findFirst runs the pipeline and produces a result or a side effect. Each pipeline has exactly one terminal operation, after which the stream is consumed and cannot be reused.

    • Intermediate operations return a Stream, so they chain; nothing runs until a terminal operation is called.
    • A terminal operation returns a value, an Optional or nothing, and closes the pipeline.
    • Elements flow one at a time through every stage, so short-circuiting operations like findFirst can stop early.
    • Stateful operations such as sorted and distinct must remember elements; stateless ones like filter and map do not.
    • A stream is single-use; build a new one from the source to run another pipeline.
    Optional<String> first = Stream.of("al", "bob", "cy", "dan")
        .filter(n -> n.length() > 2)   // intermediate: lazy
        .map(String::toUpperCase)      // intermediate: lazy
        .findFirst();                  // terminal: runs the pipeline
    System.out.println(first);         // Optional[BOB]

    Go to the module

  90. What does it mean that streams are lazy?

    Java Streams, lambdas and Optional Junior Concept

    Show answer

    Building a pipeline runs nothing: filter and map only record what to do. When the terminal operation asks for a result, elements are pulled from the source one at a time, and each runs through every stage before the next is read. That is why findFirst can stop after the first match and why a pipeline without a terminal operation never runs at all.

    • Intermediate operations record work; the terminal operation triggers it.
    • Each element passes through every stage before the next element is read.
    • Short-circuiting operations like findFirst, anyMatch and limit stop pulling once they have their answer.
    • A peek or lambda with a print shows the order in which elements are visited.
    Optional<String> first = Stream.of("al", "bob", "cy", "dan")
        .peek(n -> System.out.println("visit " + n))
        .filter(n -> n.length() > 2)
        .map(String::toUpperCase)
        .findFirst();          // prints: visit al, visit bob
    System.out.println(first); // Optional[BOB]

    Go to the module

  91. What is the difference between map and flatMap?

    Java Streams, lambdas and Optional Junior Comparison

    Show answer

    map applies a function to each element and gives exactly one output per input, so a function that returns a list produces a stream of lists. flatMap expects the function to return a stream for each element and joins those streams into one, so the items come out flat. For orders whose items are [a, b], [c, d, e] and [], map gives 3 lists and flatMap gives 5 strings.

    • map: one input, one output, of any type.
    • flatMap: one input, a stream of zero or more outputs, all joined into one stream.
    • An empty list is still one element after map and adds nothing after flatMap.
    • Optional has the same pair: flatMap avoids an Optional<Optional<T>>.
    List<List<String>> nested = orders.stream()
        .map(Order::items).toList();               // [[a, b], [c, d, e], []]
    List<String> flat = orders.stream()
        .flatMap(o -> o.items().stream()).toList(); // [a, b, c, d, e]

    Go to the module

  92. What is a functional interface, and which ones does the JDK (Java Development Kit) provide?

    Java Streams, lambdas and Optional Junior Concept

    Show answer

    A functional interface has exactly one abstract method, so a lambda or method reference can implement it. Default and static methods, and abstract methods that redeclare Object methods such as equals, do not count. @FunctionalInterface makes the compiler check the rule. The JDK provides Predicate, Function, Supplier, Consumer, UnaryOperator and BiFunction in java.util.function, and older ones like Runnable and Comparator qualify too.

    • One abstract method; default and static methods are allowed.
    • @FunctionalInterface is optional, but it turns a second abstract method into a compile error.
    • Predicate<T> tests, Function<T, R> transforms, Supplier<T> creates, Consumer<T> accepts.
    • A method reference like String::toUpperCase is a shorter lambda for the same interface.
    Predicate<String> longName = n -> n.length() > 2;
    Function<String, String> upper = String::toUpperCase;
    Supplier<List<String>> fresh = ArrayList::new;
    System.out.println(longName.test("bob")); // true
    System.out.println(upper.apply("bob"));   // BOB

    Go to the module

  93. How is Optional commonly misused?

    Java Streams, lambdas and Optional Junior Concept

    Show answer

    Optional is meant as a return type that says "there may be no result". It is misused when get() is called without checking, which throws NoSuchElementException on an empty Optional, when Optional.of(null) throws NullPointerException, or when it is used for fields, parameters or collections. orElse(expensive()) also runs expensive() even when a value is present; orElseGet runs it only when needed.

    • Use Optional as a return type, not for fields, parameters or collection elements.
    • get() on an empty Optional throws; prefer orElse, orElseGet, orElseThrow or map.
    • Optional.of(null) throws NullPointerException; use Optional.ofNullable for a value that may be null.
    • orElse(x) always evaluates x; orElseGet(() -> x) evaluates it only for an empty Optional.
    • Return an empty collection, not an Optional of a collection.
    Optional<String> name = Optional.of("bob");
    name.orElse(expensive());          // expensive() runs anyway
    name.orElseGet(() -> expensive()); // expensive() does not run
    Optional.ofNullable(null);         // Optional.empty
    Optional.of(null);                 // NullPointerException

    Go to the module

  94. When should you use a parallel stream?

    Java Streams, lambdas and Optional Junior Scenario

    Show answer

    Rarely, and only after measuring. parallel() splits the work across the common ForkJoinPool, whose default parallelism is one less than the number of processors and which the whole JVM (Java Virtual Machine) shares. It can help CPU-heavy work on large, easily split sources with no shared state. It hurts with small inputs, blocking calls, and lambdas that write to shared collections, which can lose elements.

    • Parallel streams run on the common ForkJoinPool, shared with every other parallel stream in the JVM.
    • They pay off for large, CPU-bound, stateless work on sources like arrays and ArrayList.
    • Never add to a shared ArrayList from forEach; collect with toList() or collect instead.
    • forEachOrdered and toList() keep encounter order; forEach does not.
    • Measure before and after; the split and merge overhead often outweighs the gain.
    List<Integer> unsafe = new ArrayList<>();
    IntStream.range(0, 100_000).parallel()
        .forEach(unsafe::add);           // can lose elements
    List<Integer> safe = IntStream.range(0, 100_000).parallel()
        .boxed().toList();               // 100000 elements, in order

    Go to the module

  95. What is the difference between synchronized and volatile?

    Java Concurrency: threads and synchronization Mid-level Comparison

    Show answer

    synchronized makes a block mutually exclusive: one thread at a time holds the lock, and releasing it makes its writes visible to the next thread that takes the lock. volatile only makes one variable visible: every read sees the latest write, but nothing is locked, so a read-modify-write like count++ can still lose updates. Use volatile for a flag, synchronized or an atomic class for compound updates.

    • synchronized gives mutual exclusion and visibility; volatile gives visibility and ordering only.
    • count++ on a volatile int is still three steps, read, add and write, so two threads can overlap.
    • A volatile boolean flag that one thread sets and others read is the classic correct use.
    • Every object has a monitor; a synchronized method locks this, a static synchronized method locks the class.
    class Worker {
        private volatile boolean running = true;  // a flag: volatile is enough
        private int count;
    
        synchronized void increment() { count++; }  // read, add, write as one unit
        void stop() { running = false; }             // the next read in any thread sees false
    }

    Go to the module

  96. What is the difference between Thread, Runnable and Callable?

    Java Concurrency: threads and synchronization Mid-level Comparison

    Show answer

    A Thread is the object that runs code on a new thread of execution once you call start(). A Runnable is a task whose run() returns nothing and cannot throw a checked exception. A Callable is a task whose call() returns a value and may throw. You give a Runnable to a Thread, and either one to an ExecutorService, rather than subclassing Thread.

    • Runnable: void run(). Callable<V>: V call() throws Exception.
    • Submitting a Callable to an ExecutorService returns a Future that carries its result or its exception.
    • Passing a task to a Thread or a pool separates what runs from how it runs.
    Runnable log = () -> System.out.println("hi");
    Callable<Integer> answer = () -> 42;
    new Thread(log).start();
    try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
        Future<Integer> future = pool.submit(answer);
        System.out.println(future.get());  // 42
    }

    Go to the module

  97. What is a race condition?

    Java Concurrency: threads and synchronization Mid-level Concept

    Show answer

    A race condition is a bug whose outcome depends on how threads happen to interleave. It needs shared mutable state and at least one unsynchronized write. With count++, two threads can both read 0 and both write 1, so the count ends lower than the number of increments. Fix it with synchronized, a Lock or an atomic class, or avoid sharing the state.

    • The result changes from run to run, which makes a race hard to reproduce.
    • Check-then-act, such as if (!map.containsKey(k)) map.put(k, v), is a race too.
    • Two threads doing 1,000,000 unsynchronized count++ each often end below 2,000,000.
    static int count;
    
    Runnable task = () -> {
        for (int i = 0; i < 1_000_000; i++) count++;
    };
    // two threads run task: count often ends below 2,000,000

    Go to the module

  98. What is a deadlock and how do you prevent it?

    Java Concurrency: threads and synchronization Mid-level Concept

    Show answer

    A deadlock is two or more threads each holding a lock and waiting for a lock another of them holds, so none can continue. Thread 1 holds A and waits for B while thread 2 holds B and waits for A. The usual prevention is one global lock order: every thread takes A before B, so the wait can never form a cycle.

    • A deadlock needs a cycle of threads each waiting for a lock the next one holds.
    • Take locks in one fixed order, hold as few as possible, and never call unknown code while holding one.
    • ReentrantLock.tryLock() with a timeout lets a thread give up instead of waiting forever.
    • jstack or ThreadMXBean.findDeadlockedThreads() reports the threads that are stuck.

    Go to the module

  99. What is an ExecutorService and why use one?

    Java Concurrency: threads and synchronization Mid-level Concept

    Show answer

    An ExecutorService runs submitted tasks on a pool of reused worker threads. submit() puts a Runnable or Callable in a work queue and returns a Future at once; a free worker takes the task, and future.get() waits for its result. Reusing threads avoids the cost of one thread per task and caps how many run at once. Shut the pool down when you are done.

    • Executors.newFixedThreadPool(n) keeps n workers over an unbounded queue.
    • future.get() blocks; if the task threw, it throws ExecutionException with the task's exception as the cause.
    • shutdown() refuses new tasks and lets queued ones finish; shutdownNow() interrupts running ones.
    • Since Java 19 an ExecutorService is AutoCloseable, so try-with-resources shuts it down and waits.
    try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
        Future<Integer> future = pool.submit(() -> 6 * 7);
        System.out.println(future.get());  // 42
    }  // close(): shutdown(), then wait for the tasks

    Go to the module

  100. What is the difference between calling start() and run() on a Thread?

    Java Concurrency: threads and synchronization Mid-level Code

    Show answer

    start() creates a new thread, which then calls run(). Calling run() yourself is an ordinary method call: the code runs on the current thread, so nothing happens in parallel. Calling start() a second time on the same Thread throws IllegalThreadStateException.

    • Inside run() called directly, Thread.currentThread().getName() is the caller's thread, for example main.
    • A Thread can be started only once; create a new Thread or use a pool to run the task again.
    Thread worker = new Thread(
        () -> System.out.println(Thread.currentThread().getName()), "worker");
    worker.run();    // prints main
    worker.start();  // prints worker
    worker.start();  // IllegalThreadStateException

    Go to the module

  101. How do you compose asynchronous calls in Java?

    Java CompletableFuture and virtual threads Senior Concept

    Show answer

    Build a chain of stages on CompletableFuture. supplyAsync starts the first call on a pool thread and returns a future at once. thenCompose chains a call that itself returns a future, thenApply maps a value, thenCombine or allOf joins independent calls, and exceptionally or handle deals with a failure once, at the end. Only join() or get() blocks, and only where the result is needed.

    • Without an executor argument, supplyAsync runs on ForkJoinPool.commonPool(); pass your own executor for blocking calls.
    • thenCompose takes a function that returns a CompletableFuture; thenApply would nest it as CompletableFuture<CompletableFuture<T>>.
    • thenCombine merges the results of two independent futures once both complete; allOf waits for any number of them.
    • A failed stage skips every later thenApply and thenCompose until a stage that handles it, such as exceptionally or handle.
    • join() throws an unchecked CompletionException and get() a checked ExecutionException; both carry the original exception as the cause.

    Go to the module

  102. What are virtual threads in Java 21, and when do they help?

    Java CompletableFuture and virtual threads Senior Concept

    Show answer

    A virtual thread is a Thread scheduled by Java, not the OS, and final in Java 21. When it blocks on a socket, a java.util.concurrent lock or sleep, the JVM unmounts it from its carrier platform thread, which then runs another virtual thread. So one thread per request scales to thousands of blocking calls: 10,000 one-second sleeps took about 1 s, against about 50 s on a thread pool of 200.

    • Create them with Executors.newVirtualThreadPerTaskExecutor(), Thread.ofVirtual().start(task) or Thread.startVirtualThread(task); isVirtual() returns true.
    • By default the carriers come from a ForkJoinPool with one thread per core, and a resumed virtual thread can continue on another carrier.
    • They help when tasks spend their time waiting on HTTP calls or database queries, not when they compute.
    • Code stays in plain blocking style, with readable stack traces, instead of a chain of callbacks.

    Go to the module

  103. What is the difference between thenApply and thenCompose?

    Java CompletableFuture and virtual threads Senior Comparison

    Show answer

    Both run after the future completes and pass its value to a function. thenApply is for a function that returns a plain value, like map on a stream. thenCompose is for a function that returns another CompletableFuture, like flatMap: it waits for that inner future and gives you a flat CompletableFuture<T>. Pass fetchOrders to thenApply and you get a CompletableFuture<CompletableFuture<List<Order>>>.

    • Assigning thenApply(user -> fetchOrders(user)) to a CompletableFuture<List<Order>> is a compile error about incompatible bounds.
    • thenCombine is the third option: it merges two futures that do not depend on each other.
    • The Async variants, such as thenApplyAsync, run the function on an executor, by default the common pool.
    CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> findUser(42));
    
    CompletableFuture<List<Order>> orders = user.thenCompose(u -> fetchOrders(u));
    CompletableFuture<CompletableFuture<List<Order>>> nested = user.thenApply(u -> fetchOrders(u));
    CompletableFuture<Integer> count = orders.thenApply(List::size);

    Go to the module

  104. When do virtual threads not help, and what can pin one to its carrier thread?

    Java CompletableFuture and virtual threads Senior Scenario

    Show answer

    When the work computes instead of waiting: 64 CPU-bound tasks took about as long on virtual threads as on a pool sized to the cores. When something else is the limit, such as 10 database connections. And in Java 21 when a virtual thread blocks inside synchronized or a native method: it pins its carrier, which then runs nothing else. Java 24 removed nearly all synchronized pinning (JEP 491).

    • In Java 21, replace synchronized around a blocking call with a ReentrantLock, which lets the virtual thread unmount.
    • Since Java 24, native frames and class initialization still pin (JEP 491, a Java Development Kit Enhancement Proposal).
    • Cap access to a scarce resource with a Semaphore, not with a smaller thread pool.
    • Avoid caching expensive objects in a ThreadLocal; with one virtual thread per task, each task builds its own copy.

    Go to the module

  105. What has changed in Java since Java 8?

    Java Modern Java (8 to 21) Mid-level Concept

    Show answer

    Java 8 brought lambdas and streams. Later releases made data modeling shorter and safer: var in 10, switch expressions in 14, text blocks in 15, records in 16 and sealed classes in 17. Java 21 adds pattern matching for switch, record patterns, sequenced collections and virtual threads. Together, records, sealed types and pattern matching let the compiler check that a switch handles every case.

    • var (Java 10) infers a local variable's type from its initializer; the type is still static.
    • Switch expressions (Java 14) return a value, and their -> arms do not fall through.
    • Records (Java 16) generate the constructor, accessors, equals, hashCode and toString from one line.
    • Sealed classes (Java 17) fix the list of subtypes, so a switch over them can omit default.
    • Java 21 finalized pattern matching for switch, record patterns, sequenced collections and virtual threads.

    Go to the module

  106. What is a record, and how is it different from a regular class?

    Java Modern Java (8 to 21) Mid-level Comparison

    Show answer

    A record, final in Java 16, is a class whose state is exactly its components. From record Point(int x, int y) the compiler generates private final fields, a canonical constructor, the accessors x() and y(), and equals, hashCode and toString based on the components. A record is implicitly final and extends java.lang.Record, so it cannot extend another class, but it can implement interfaces and add methods.

    • new Point(1, 2).equals(new Point(1, 2)) is true, and toString() gives Point[x=1, y=2].
    • Accessors are named after the components, x(), not getX().
    • An instance field beyond the components fails with "field declaration must be static".
    • Immutability is shallow: a List component can still change unless the constructor copies it with List.copyOf.

    Go to the module

  107. What do sealed classes and pattern matching for switch give you together?

    Java Modern Java (8 to 21) Mid-level Concept

    Show answer

    A sealed type lists its permitted subtypes, as in sealed interface Shape permits Circle, Square, and each must be final, sealed or non-sealed; records are implicitly final. Pattern matching for switch (Java 21) tests the type and binds a variable in one case. Because the compiler knows every subtype, a switch with one case per type needs no default, and adding a subtype breaks every incomplete switch at compile time.

    • A missing case fails with "the switch expression does not cover all possible input values".
    • Record patterns (Java 21) take the components apart in the case: case Circle(double r) -> ....
    • A guard narrows a case: case Circle(double r) when r == 0 -> ....
    • A permitted subclass with no modifier fails with "sealed, non-sealed or final modifiers expected".
    sealed interface Shape permits Circle, Square {}
    record Circle(double r) implements Shape {}
    record Square(double side) implements Shape {}
    
    static double area(Shape shape) {
        return switch (shape) {
            case Circle c -> Math.PI * c.r() * c.r();
            case Square s -> s.side() * s.side();
        };
    }

    Go to the module

  108. When can you use var, and when should you avoid it?

    Java Modern Java (8 to 21) Mid-level Scenario

    Show answer

    var (Java 10) declares a local variable whose type the compiler infers from the initializer. It needs an initializer the compiler can type, and it is not allowed on fields, method parameters or return types. Use it when the right-hand side already shows the type, as in var names = new ArrayList<String>(). Avoid it when the reader would have to look up a method to know the type.

    • var x; and var y = null; are compile errors: there is nothing to infer a type from.
    • var on a field, a parameter or a return type fails with "'var' is not allowed here".
    • var list = new ArrayList<>(); infers ArrayList<Object>, so String s = list.get(0) does not compile.
    • var is a reserved type name, not a keyword: int var = 5; still compiles.

    Go to the module

  109. What design patterns do you know, and where have you used them?

    Design Patterns Pattern families (GoF) Junior Concept

    Show answer

    Group them by family, then give one you really used per family. Creational: Builder for an immutable request. Structural: Decorator around a repository, or the proxy behind @Transactional. Behavioral: Strategy to replace a switch on payment type. A pattern is a named solution to a recurring design problem, so name the problem each one solved.

    • The Gang of Four book lists 23 patterns in three families.
    • Answer with a problem you had, the pattern you chose and what it cost.
    • Spring already uses many of them, such as Singleton, Proxy, Template Method and Observer.
    • A pattern is a shared vocabulary, not a library you import.

    Go to the module

  110. What is the difference between creational, structural and behavioral patterns?

    Design Patterns Pattern families (GoF) Junior Comparison

    Show answer

    They answer different questions. Creational patterns decide how objects get created, so callers do not name concrete classes. Structural patterns decide how objects are composed into larger structures. Behavioral patterns decide how objects communicate and share responsibilities. Asking what needs to vary usually tells you which family to look in.

    • Creational (5): Singleton, Factory Method, Abstract Factory, Builder, Prototype.
    • Structural (7): Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy.
    • Behavioral (11): Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor.

    Go to the module

  111. Which design patterns can you point to in the JDK and in Spring?

    Design Patterns Pattern families (GoF) Junior Concept

    Show answer

    The JDK has Builder in HttpRequest.newBuilder(), Decorator in BufferedInputStream, Adapter in InputStreamReader, Strategy in Comparator and Iterator in every collection. Spring has Singleton-scoped beans, Proxy behind @Transactional, Template Method in OncePerRequestFilter, Observer in ApplicationEventPublisher and Chain of Responsibility in its filter chain.

    • Naming a real class shows you recognize a pattern outside a textbook.
    • Spring's default bean scope is one object per container, not a GoF Singleton class.
    • JdbcTemplate fixes the steps but takes callbacks, so it is a variation on Template Method.

    Go to the module

  112. When should you not use a design pattern?

    Design Patterns Pattern families (GoF) Junior Scenario

    Show answer

    When the problem it solves is not there yet. A Strategy interface with one implementation, or a factory that only ever makes one class, adds indirection and gives nothing back. Start with plain code, then introduce the pattern when a second variation or a real need appears. YAGNI (You Aren't Gonna Need It) applies to patterns too.

    • Each pattern trades extra classes and indirection for a kind of flexibility.
    • Refactor toward a pattern when duplication or a change request shows the need.
    • A lambda or an enum is often enough in modern Java.

    Go to the module

  113. How do you make a thread-safe singleton in Java?

    Design Patterns Singleton Junior Code

    Show answer

    Let the JVM (Java Virtual Machine) do it. Class initialization runs once, even across threads, so an enum, a static final field or a lazy holder class is safe with no lock in your code. Prefer an enum when the type needs no superclass, or a holder class when it must be lazy. Double-checked locking also works, but only with volatile.

    • A naive if (instance == null) is check-then-act, so two threads can both create an object.
    • The holder class creates the object on the first getInstance() call, with no lock in your code.
    • An eager field is created on any first use of the class, not only on getInstance().
    • Double-checked locking needs volatile, or another thread can see a partly constructed object.
    • In Spring, make it a bean and let the container keep one instance.

    Go to the module

  114. Why is an enum often called the best way to write a singleton?

    Design Patterns Singleton Junior Comparison

    Show answer

    It is one line and the JVM handles what you would otherwise write by hand. Class initialization makes it thread-safe. Reflection fails with "Cannot reflectively create enum objects". Deserializing returns the same object, with no readResolve(). Its limits: it cannot extend a class, it is created on first use of the enum, and it can feel odd for a mutable service.

    • enum AppConfig { INSTANCE } needs no private constructor or getInstance().
    • A class-based singleton needs readResolve() to survive serialization.
    • An enum can still implement interfaces and hold fields and methods.
    enum AppConfig {
        INSTANCE;
        int timeoutSeconds() { return 30; }
    }
    int seconds = AppConfig.INSTANCE.timeoutSeconds();

    Go to the module

  115. Why is Singleton sometimes called an anti-pattern?

    Design Patterns Singleton Junior Concept

    Show answer

    Because it is global mutable state in disguise. Callers reach for AppConfig.getInstance() instead of declaring a dependency, which hides what they need and makes them hard to test, since you cannot swap the instance for a fake and its state leaks between tests. The fix is dependency injection, with a single instance held by the composition root or container.

    • A hidden static dependency does not show in the constructor.
    • Shared state makes test order matter.
    • The class handles its own lifecycle as well as its real job, which breaks single responsibility.
    • One instance is fine; a globally reachable one is the problem.

    Go to the module

  116. Are Spring beans singletons in the GoF (Gang of Four) sense?

    Design Patterns Singleton Junior Comparison

    Show answer

    No. The default scope gives one object per bean definition per container, not one per JVM. Two @Bean methods returning the same class give two objects, and two application contexts give two sets. The class itself can have a public constructor, so nothing stops new. The container enforces the rule, and this is what makes such beans easy to replace in tests.

    • GoF Singleton: the class guarantees one instance per class loader.
    • Spring singleton scope: the container keeps one instance per bean definition.
    • Singleton-scoped beans are shared across threads, so they must not keep request state in fields.

    Go to the module

  117. How can a class-based singleton end up with two instances?

    Design Patterns Singleton Mid-level Scenario

    Show answer

    Three common ways. Reflection: setAccessible(true) on the private constructor, then newInstance(). Serialization: deserializing creates a new object unless the class defines readResolve(). Class loaders: two loaders each load their own copy of the class, so each gets its own static field. An enum blocks the first two; nothing in the class itself blocks the third.

    • Reflection can call a private constructor unless the constructor checks and throws.
    • readResolve() returning the instance replaces the deserialized copy.
    • Static fields belong to a class per class loader, so "one" means one per loader.

    Go to the module

  118. The getInstance method is thread-safe. Does that make the singleton's own state thread-safe?

    Design Patterns Singleton Junior Scenario

    Show answer

    No. Safe creation only means every thread gets the same object. If that object has a mutable field, all those threads now share it, so an unsynchronized counter or HashMap inside still races. Keep singletons stateless or immutable, or use AtomicInteger, ConcurrentHashMap or locks for the state they must hold.

    • Creation and use are separate concerns.
    • A singleton makes sharing more likely, so its fields need more care, not less.
    • The same rule applies to singleton-scoped Spring beans.

    Go to the module

  119. What is the difference between Factory Method and Abstract Factory?

    Design Patterns Factory Method and Abstract Factory Junior Comparison

    Show answer

    Factory Method is one method that subclasses override to choose one product, so it works through inheritance. Abstract Factory is an object with several create methods that produce a family of related products, so it works through composition: the client is handed a factory. Use Abstract Factory when the products must match each other.

    • Factory Method: abstract Notification createNotification(), overridden by each subclass.
    • Abstract Factory: createMessage() and createSender() on one factory, so the pair always matches.
    • Both leave the client depending on interfaces, not on concrete classes.
    • A new product kind is cheap for Factory Method but changes every Abstract Factory.

    Go to the module

  120. Why use a factory instead of just calling new?

    Design Patterns Factory Method and Abstract Factory Junior Concept

    Show answer

    Calling new ties the caller to one concrete class and to how it is built. A factory moves that decision to one place, so callers depend on an interface and new products leave their code alone. It can also cache objects, pick a class from input and validate arguments, none of which a constructor can do. If only one class exists, new is fine.

    • A factory method has a name, so it can say what it creates.
    • It can return a subclass or a cached object, unlike a constructor.
    • One creation point keeps the choice of class out of many callers.

    Go to the module

  121. What is a simple factory, and how is it different from Factory Method?

    Design Patterns Factory Method and Abstract Factory Junior Comparison

    Show answer

    A simple factory is one class, usually with a static method, that picks a product from an argument, such as NotificationFactory.create("sms"). It is not a GoF pattern, but it is very common. Factory Method relies on subclasses overriding a method. Choose a simple factory when input decides the product, and Factory Method when the subclass does.

    • Simple factory: the choice is made inside one method, from input at runtime.
    • Factory Method: the choice is fixed by which subclass you instantiate.
    • A Map of Suppliers avoids a growing switch in a simple factory.

    Go to the module

  122. How would you write a factory that does not need editing for each new product?

    Design Patterns Factory Method and Abstract Factory Junior Code

    Show answer

    Keep the choices in a Map<String, Supplier<Notification>> and look up the channel instead of switching on it. A new product is then one more entry. Fail clearly on an unknown key with an IllegalArgumentException. In Spring, injecting a Map<String, Notification> builds that map for you from the beans, keyed by bean name.

    • The lookup stays the same as products are added.
    • An unknown key throws rather than returning null.
    • In Spring, a new @Component adds an entry with no factory edit.
    private static final Map<String, Supplier<Notification>> CHANNELS = Map.of(
        "email", EmailNotification::new,
        "sms", SmsNotification::new);
    
    static Notification create(String channel) {
        Supplier<Notification> maker = CHANNELS.get(channel);
        if (maker == null) throw new IllegalArgumentException("Unknown channel: " + channel);
        return maker.get();
    }

    Go to the module

  123. When is Abstract Factory the right choice?

    Design Patterns Factory Method and Abstract Factory Mid-level Scenario

    Show answer

    When products must be used together and mixing them is a bug. For notifications, an email channel needs an HTML message and an SMTP (Simple Mail Transfer Protocol) sender, and an SMS channel needs a short text and an SMS gateway. With one ChannelFactory chosen at startup, the rest of the code cannot pair an HTML message with an SMS gateway.

    • The factory is chosen once, and the client uses only interfaces after that.
    • JDBC (Java Database Connectivity) works this way, because a Connection creates Statement objects that match its driver.
    • One new family means one new factory class.

    Go to the module

  124. How do factories relate to the Open/Closed Principle?

    Design Patterns Factory Method and Abstract Factory Junior Concept

    Show answer

    Clients stay closed to change: they only know the interface, so a new product leaves them alone. Something still has to change, and that is the factory or the registration. A factory does not remove that edit; it concentrates it in one place. Factory Method goes further, since a new subclass extends the design without editing existing classes.

    • Client code stays closed; the composition point stays open.
    • A switch inside one factory is much better than a switch in every caller.
    • Dependency injection moves that composition point into configuration.

    Go to the module

  125. When would you use a Builder instead of a constructor?

    Design Patterns Builder Junior Comparison

    Show answer

    When an object has several optional fields, when values should be named at the call site, or when it must be immutable yet needs validating as a whole. A builder collects values in named calls, then build() validates and creates the object. With two or three required fields and nothing optional, a constructor or a record is simpler.

    • Named calls replace positional arguments such as null, true.
    • Optional values are skipped, not passed as null.
    • build() is one place to validate fields together.
    • The result can have only final fields, because the builder holds the mutable state.

    Go to the module

  126. What is the telescoping constructor problem?

    Design Patterns Builder Junior Concept

    Show answer

    It is the chain of constructors a class grows as it gets optional fields: one with the required fields, then one more for each optional field, each calling the next. To set the last one you must pass all the others, so calls fill up with null and bare values. new Email(to, "Welcome", null, true) compiles but does not say what null and true mean.

    • Same-typed parameters can be swapped by accident, and the compiler accepts it.
    • Constructor count grows with each optional field.
    • A builder or a record with named factories removes the positional guessing.

    Go to the module

  127. What does Lombok @Builder generate, and what should you watch out for?

    Design Patterns Builder Junior Code

    Show answer

    It generates a static builder() method and a nested builder class with one method per field and a build() that calls an all-args constructor. Watch three things: a field initializer is ignored unless it has @Builder.Default, required fields are not enforced unless marked @NonNull, and nothing validates fields together unless you write it. toBuilder = true adds a way to copy and change.

    • @Value @Builder gives an immutable class with a builder.
    • Without @Builder.Default, int retries = 3 builds as 0.
    • @NonNull throws NullPointerException from build(), at runtime rather than compile time.
    @Value
    @Builder(toBuilder = true)
    class EmailMessage {
        @NonNull String to;
        String subject;
        @Builder.Default int retries = 3;
    }

    Go to the module

  128. Why not just use a no-args constructor and setters?

    Design Patterns Builder Junior Comparison

    Show answer

    Setters leave the object mutable forever and allow it to exist half-built: between new Email() and the last setter call, it is invalid and another thread or method can see it. A builder keeps the half-built state in a separate object and only hands out a complete, validated, immutable result, which is safe to share between threads.

    • Setters cannot enforce a rule that spans two fields at a single moment.
    • Immutable objects are thread-safe without synchronization.
    • JPA (Jakarta Persistence API) entities and some serialization frameworks still need a no-args constructor.

    Go to the module

  129. Do records replace the Builder pattern?

    Design Patterns Builder Mid-level Comparison

    Show answer

    Only for simple cases. A record gives an immutable class with a named accessor per field, and a compact constructor can validate. But it has one canonical constructor taking every component, so the positional problem remains when a record has many optional fields. Put a small builder on the record when calls start needing null, or use Lombok's @Builder on it.

    • Use a record when every value is always given and fields are few.
    • Use a builder when many fields are optional.
    • Both end in the same place, an immutable object.

    Go to the module

  130. How does the fluent Builder you see in Java differ from the original GoF (Gang of Four) Builder?

    Design Patterns Builder Mid-level Comparison

    Show answer

    The GoF version separates a director, which knows the steps, from interchangeable builders that produce different representations from those steps. The everyday Java version drops the director and the variety: a nested class with chained methods makes one product, and its goal is readable construction of an immutable object. Interviewers almost always mean the Java version, but naming the difference shows depth.

    • GoF goal: the same steps produce different representations.
    • Fluent goal: replace long constructors with named calls.
    • Each fluent method returns this so calls can chain.

    Go to the module

  131. How would you remove a long if/else or switch from a method?

    Design Patterns Strategy Mid-level Scenario

    Show answer

    If each branch is a different way of doing the same job, turn each branch into a Strategy: one interface with one implementation per case. The method then looks the strategy up, in a Map or from injected beans, and calls it. A new case becomes a new class instead of an edit to a tested method. Two stable branches can stay a plain if.

    • Check first that the branches really are interchangeable behaviors.
    • One interface, one class or lambda per case, and a lookup instead of the branching.
    • The method now follows the Open/Closed Principle for new cases.
    • An enum with a method per constant suits a fixed, small set.

    Go to the module

  132. What is the difference between Strategy and State?

    Design Patterns Strategy Mid-level Comparison

    Show answer

    They have the same class diagram but a different intent. In Strategy, the caller chooses a behavior, and the strategies do not know about each other. In State, the object moves itself between states as things happen, and each state often decides the next one. A discount is a Strategy; an order going from placed to paid to shipped is State.

    • Strategy: the choice comes from outside, and usually stays fixed for the call.
    • State: the transitions come from inside, so behavior changes over time.
    • States often know each other; strategies should not.

    Go to the module

  133. Which SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependency inversion) principles does Strategy support?

    Design Patterns Strategy Mid-level Concept

    Show answer

    Open/Closed: new behavior arrives as a new class, with no edit to the code that uses it. Dependency Inversion: the context depends on an interface rather than on concrete algorithms. Single Responsibility: each algorithm lives in one place. It also shows composition over inheritance, since behavior is held in a field and not inherited.

    • Open/Closed for adding cases.
    • Dependency Inversion through the Discount interface.
    • Composition lets you swap behavior at runtime, which a subclass cannot do.

    Go to the module

  134. Where does the JDK (Java Development Kit) use Strategy?

    Design Patterns Strategy Mid-level Concept

    Show answer

    Comparator is the classic case: list.sort(comparator) keeps the sorting algorithm fixed and takes the ordering rule as an object. ThreadPoolExecutor takes a RejectedExecutionHandler for what to do when it is full. In Spring, AuthenticationProvider and PasswordEncoder are strategies chosen by configuration.

    • The caller supplies the behavior as an object or lambda.
    • The surrounding algorithm stays the same.
    • Passing a lambda is the shortest possible Strategy.

    Go to the module

  135. How is Strategy different from Template Method?

    Design Patterns Strategy Mid-level Comparison

    Show answer

    Both vary part of an algorithm. Template Method uses inheritance: a base class fixes the steps and a subclass overrides some, so the choice is made at compile time. Strategy uses composition: the object holds a replaceable collaborator, so the choice can change at runtime and the same strategy can serve unrelated classes.

    • Template Method varies a step; Strategy replaces a whole algorithm.
    • A subclass is fixed once the object exists; a field can be swapped.
    • When in doubt, favor composition.

    Go to the module

  136. Can an enum implement the Strategy pattern?

    Design Patterns Strategy Mid-level Code

    Show answer

    Yes, and it suits a fixed, small set of behaviors that do not need dependencies. Each constant supplies its own behavior, by overriding a method or holding a lambda, and valueOf gives you the lookup. Adding a case means editing the enum, so use interfaces and beans when others must add strategies, or when strategies need injection.

    • Constants are singletons, so they should hold no mutable state.
    • The compiler checks that every constant has the behavior.
    • An enum is closed to outside extension, unlike an interface.
    enum DiscountType {
        PERCENT10(t -> t.multiply(new BigDecimal("0.90"))),
        NONE(t -> t);
    
        private final UnaryOperator<BigDecimal> rule;
        DiscountType(UnaryOperator<BigDecimal> rule) { this.rule = rule; }
        BigDecimal apply(BigDecimal total) { return rule.apply(total); }
    }

    Go to the module

  137. How do event listeners work, and what pattern is behind them?

    Design Patterns Observer Mid-level Concept

    Show answer

    They use Observer. A subject keeps a list of listeners that share one interface, and when something happens it calls each in turn. New listeners need no change to the subject, so the two stay decoupled. In the simple form the calls are synchronous, so publish() returns only after every listener has finished, and a listener's exception reaches the publisher.

    • The subject depends on an interface, never on concrete listeners.
    • Listeners register and unregister at runtime.
    • By default, notification runs on the publisher's thread.
    • A slow listener slows the publisher, and a failing one can stop the rest.

    Go to the module

  138. What is the difference between Observer and pub/sub?

    Design Patterns Observer Mid-level Comparison

    Show answer

    In Observer, the subject holds its listeners and calls them directly, usually synchronously and in one process. In pub/sub, a broker sits in between: publishers write to a topic and do not know the subscribers, who may be in other processes and may be down. That decouples time and failures too, at the price of running a broker and handling duplicates and eventual consistency.

    • Observer decouples code; pub/sub also decouples time and deployment.
    • Pub/sub keeps an event when a consumer is down, if the broker retains it.
    • Kafka and RabbitMQ are the usual brokers; Spring events are in-process Observer.

    Go to the module

  139. One listener calls a slow external service, and placing an order got slow. What are your options?

    Design Patterns Observer Mid-level Scenario

    Show answer

    The listener runs on the caller's thread, so the order waits for it. Make that listener asynchronous with @Async or an executor, so the caller returns early; note that its failures no longer reach the caller and a crash loses the event. If the work must not be lost, write it to an outbox or publish to a broker instead.

    • First confirm the listener really is synchronous.
    • An @Async listener needs its own error handling.
    • If it must survive a crash, use a broker or an outbox rather than an in-memory thread pool.

    Go to the module

  140. Why would a subject keep its listeners in a CopyOnWriteArrayList?

    Design Patterns Observer Mid-level Code

    Show answer

    A listener might unsubscribe while the subject is looping, or another thread might subscribe. With ArrayList, that throws ConcurrentModificationException or races. CopyOnWriteArrayList iterates over a snapshot and copies on each write, so reads take no lock. That suits listener lists, which are read often and changed rarely.

    • Iteration sees a stable snapshot.
    • Writes are expensive, because each one copies the array.
    • A listener added during a publish misses that event, since the loop uses the old snapshot.

    Go to the module

  141. What is the difference between Decorator and Proxy?

    Design Patterns Decorator and Proxy Mid-level Comparison

    Show answer

    They are built the same way: a wrapper with the same type as its target, forwarding calls. The difference is intent. A Decorator adds behavior, and your code composes as many layers as it wants. A Proxy controls access to the target, for a transaction, security or lazy loading, and a framework usually creates it so the client never knows.

    • Decorator example: new BufferedInputStream(new FileInputStream(file)).
    • Proxy example: the object Spring injects for a @Transactional bean.
    • Decorators are layered by the caller; a proxy usually hides the wrapping.
    • Interviewers want the intent, since the class diagrams are nearly identical.

    Go to the module

  142. How does Spring implement @Transactional and AOP (aspect-oriented programming)?

    Design Patterns Decorator and Proxy Mid-level Concept

    Show answer

    With a proxy. At startup, a bean post-processor sees the annotation and replaces the bean with a proxy of the same type, built with CGLIB or a JDK dynamic proxy. Callers receive the proxy. On each call it runs an interceptor chain around your method: the transaction interceptor begins a transaction, calls the target, and commits, or rolls back on a RuntimeException.

    • Your class contains no transaction code; the advice lives in the proxy.
    • It only works on calls that go through the proxy.
    • By default, checked exceptions do not trigger a rollback.

    Go to the module

  143. Why does a @Transactional method called from the same class not start a transaction?

    Design Patterns Decorator and Proxy Mid-level Scenario

    Show answer

    Because the advice lives in the proxy, and this is the target. An outside caller goes through the proxy, but this.place() is a plain method call on the real object, so no interceptor runs. It compiles and runs without any error, just outside a transaction. Move the method to another bean, or inject a TransactionTemplate.

    • No error is raised, so this tends to show up as a data bug.
    • Moving the method to another bean is usually the cleanest fix.
    • The same limit applies to @Cacheable, @Async and any proxy-based annotation.
    @Service
    class OrderService {
        public void outer() {
            this.place();      // no proxy: runs with no transaction
        }
    
        @Transactional
        public void place() { }
    }

    Go to the module

  144. Why use a Decorator instead of a subclass?

    Design Patterns Decorator and Proxy Mid-level Comparison

    Show answer

    A subclass fixes one combination at compile time, so logging, caching and retry in any combination would need a class for each: a class explosion. Decorators compose at runtime, one wrapper per concern, so three wrappers cover all those combinations. It is composition over inheritance applied to added behavior, and the wrapped class needs no change.

    • N concerns need N decorators, against up to 2^N subclasses.
    • Order matters, since a cache around logging differs from logging around a cache.
    • A long chain can make stack traces and debugging harder.

    Go to the module

  145. Does the order of decorators matter?

    Design Patterns Decorator and Proxy Mid-level Code

    Show answer

    Yes. Calls enter from the outside in, and results come back from the inside out. With logging outside a cache, every call is logged, including hits. With the cache outside logging, a hit never reaches the logger, so you log only the misses. Choose the order for what you want to see, and write it down where the object is composed.

    • The outermost wrapper sees every call.
    • Anything inside a cache runs only on a miss.
    • With Spring aspects, @Order sets the same kind of order.
    // Logs every call, including cache hits
    new LoggingOrderRepository(new CachingOrderRepository(jdbc));
    
    // Logs only cache misses
    new CachingOrderRepository(new LoggingOrderRepository(jdbc));

    Go to the module

  146. What kinds of proxy are there, and what is each one for?

    Design Patterns Decorator and Proxy Mid-level Concept

    Show answer

    A virtual proxy delays creating something expensive until first use, like Hibernate's lazy-loaded entities. A protection proxy checks permissions before forwarding, like method security. A remote proxy makes a network call look local, like a Feign client. A smart proxy adds work around the call, like Spring's transaction proxy. All of them keep the target's type.

    • Each kind controls access for a different reason.
    • Hibernate's getReferenceById returns a virtual proxy.
    • LazyInitializationException happens when that proxy loads after the session closed.

    Go to the module

  147. What is the difference between Adapter and Facade?

    Design Patterns Adapter and Facade Mid-level Comparison

    Show answer

    An Adapter solves a fit problem: it wraps one class and implements the interface your code already expects, translating each call. A Facade solves a complexity problem: it gives many classes one new, simpler interface and coordinates them behind it. Both are wrappers, so ask what is wrong. If the shape is wrong, adapt it; if there is too much to call, put a Facade in front.

    • Adapter: one class, an existing interface, and translation of arguments and results.
    • Facade: many classes, a new interface, and coordination of calls.
    • A Facade does not stop anyone from using the subsystem directly when they need more.

    Go to the module

  148. How would you integrate a legacy or third-party API so it does not spread through your code?

    Design Patterns Adapter and Facade Mid-level Scenario

    Show answer

    Define an interface in your own terms, such as PaymentGateway, and write one Adapter that implements it by calling the third-party client. The Adapter converts types and maps error codes to your exceptions. Only it imports the vendor's classes, so a new vendor means one new Adapter, and tests can use a fake gateway without any network.

    • Name the interface after your needs, not the vendor's API.
    • Convert vendor errors and status codes at the boundary.
    • In Domain-Driven Design, this boundary is called an anti-corruption layer.

    Go to the module

  149. How is an Adapter different from a Decorator?

    Design Patterns Adapter and Facade Mid-level Comparison

    Show answer

    Look at the interface. An Adapter changes it: the wrapped class has one interface and the wrapper exposes a different one. A Decorator keeps it: wrapper and target have the same type, which is why decorators can stack. A Proxy also keeps it. If the caller could use the wrapped object directly, the wrapper is not an Adapter.

    • Adapter changes the type and keeps the behavior.
    • Decorator keeps the type and adds behavior.
    • Proxy keeps the type and controls access.

    Go to the module

  150. What can go wrong with a Facade?

    Design Patterns Adapter and Facade Mid-level Scenario

    Show answer

    It can turn into a god class that knows every subsystem and collects unrelated methods. It can hide details that a caller really needs, such as a transaction boundary. And if it only forwards one call to one class, it adds nothing at all. Keep it thin: it should coordinate, while the rules stay in the subsystems.

    • Split a Facade that serves unrelated use cases.
    • One method that forwards to one class is just indirection.
    • Tests should still cover the subsystems directly.

    Go to the module

  151. Where does Spring use Template Method and Chain of Responsibility?

    Design Patterns Template Method and Chain of Responsibility Mid-level Concept

    Show answer

    Template Method: OncePerRequestFilter has a final doFilter that calls your doFilterInternal, and AbstractApplicationContext.refresh() calls hooks such as onRefresh(). Chain of Responsibility: servlet filters, including Spring Security's filter chain, where each filter calls chain.doFilter or stops the request. JdbcTemplate is a related form: it fixes the JDBC (Java Database Connectivity) steps and takes your code as a callback.

    • Template Method: a base class fixes the steps, and subclasses fill in some of them.
    • Chain of Responsibility: each handler does its part and decides whether to pass the request on.
    • JdbcTemplate is a concrete class using callbacks, so nothing subclasses it.
    • HttpServlet.service() calling doGet() is the classic servlet example.

    Go to the module

  152. What is the Template Method pattern, and what is its main risk?

    Design Patterns Template Method and Chain of Responsibility Mid-level Concept

    Show answer

    A base class defines the steps of an algorithm in a final method and leaves some steps abstract, so subclasses vary the details without changing the order. The risk is inheritance itself: subclasses are tied to the base class, and they can only vary by overriding. If the step could be passed in as an object, Strategy or a callback is usually more flexible.

    • Making the template method final protects the order of the steps.
    • In the JDK (Java Development Kit), AbstractList needs only get and size; the rest is built from them.
    • Many subclass overrides can make the flow hard to follow.

    Go to the module

  153. Why does the order of filters in a chain matter?

    Design Patterns Template Method and Chain of Responsibility Mid-level Scenario

    Show answer

    Each filter relies on what ran before it. Authorization needs the identity that authentication found, so reversing them rejects everyone or checks nothing. Logging has to come first to record requests that are later rejected. Validation should come after authorization, so unauthorized callers get no feedback about the body. In Spring, you set the order with @Order or addFilterBefore.

    • An early filter that stops a request saves the work of all later ones.
    • Authentication answers who you are; authorization answers what you may do.
    • Filters also run on the way back, in reverse order.

    Go to the module

  154. How is Chain of Responsibility different from Decorator?

    Design Patterns Template Method and Chain of Responsibility Mid-level Comparison

    Show answer

    They look alike: each object holds the next one and forwards to it. A Decorator always forwards, since its job is to add behavior around a target that always runs. A handler in a chain may stop and return, so the end of the chain might never run. A servlet filter can do both, so ask whether the design expects the call to be stopped.

    • Decorator guarantees that the target runs.
    • A chain does not guarantee that any given handler runs.
    • Chains are usually assembled from configuration, and decorators by the code that uses them.

    Go to the module

  155. What is the difference between layered, hexagonal and clean architecture?

    Design Patterns Architectures: layered, hexagonal and clean Senior Comparison

    Show answer

    The difference is which way dependencies point. In layered, the controller calls the service and the service calls the repository, so business rules depend on persistence. Hexagonal inverts that: the domain defines ports, and REST (Representational State Transfer) and JPA (Jakarta Persistence API) are adapters that depend on it. Clean is the same rule drawn as rings, with more named layers. Both make rules testable with no framework.

    • Layered is simple and fits CRUD (create, read, update, delete), but persistence tends to shape the model.
    • Hexagonal has ports owned by the domain and adapters outside it.
    • Clean's dependency rule says source dependencies only point inward.
    • The cost is more interfaces and mapping between domain and persistence models.

    Go to the module

  156. Where should business logic live?

    Design Patterns Architectures: layered, hexagonal and clean Senior Concept

    Show answer

    In the domain: entities and use cases, not controllers or repositories. A controller translates HTTP, and a repository translates storage. If a rule like "total must be positive" sits in a controller, another entry point can skip it, such as a message consumer. Put rules where every path passes through, ideally on the object that owns the data.

    • Controllers should hold no business decisions.
    • A record's compact constructor can enforce a rule on every creation.
    • A service with all the logic and entities with only getters is called an anemic domain model.

    Go to the module

  157. What are ports and adapters?

    Design Patterns Architectures: layered, hexagonal and clean Senior Concept

    Show answer

    A port is an interface owned by the domain. An input port says what the application offers, such as PlaceOrder. An output port says what it needs, such as OrderStore. An adapter connects a port to a technology. Driving adapters such as a REST controller call in. Driven adapters such as a JPA repository implement output ports.

    • Ports speak in domain terms, with no HTTP or SQL.
    • A new technology means a new adapter, and no change to the domain.
    • A test adapter runs the real rules with no infrastructure.

    Go to the module

  158. When is a hexagonal architecture worth its cost, and when is it not?

    Design Patterns Architectures: layered, hexagonal and clean Senior Scenario

    Show answer

    It pays off when rules are rich and long-lived, when several channels reach the same logic, such as REST and Kafka, or when infrastructure may change. It costs extra interfaces and mapping classes, which is waste for a thin CRUD service. A good middle ground is one project with clear packages and an ArchUnit rule, adding full ports only where needed.

    • Weigh the cost of mapping against how much logic there really is.
    • Start simple and extract ports when a second adapter or real complexity appears.
    • Enforce the boundary with tests, or it erodes.

    Go to the module

  159. What is the difference between unit, integration and end-to-end tests?

    Unit Testing The testing pyramid Junior Comparison

    Show answer

    They differ in how much real code runs. A unit test checks one unit of logic, usually a class, with no framework, database or network, in milliseconds. An integration test checks that real parts work together, such as a repository against a database. An end-to-end test drives the whole deployed system like a user. Keep many unit tests, fewer integration tests and a few end-to-end tests.

    • Higher layers give more confidence per test but run slower and fail for more reasons.
    • Unit tests pinpoint the broken line; an end-to-end failure only says that something broke.
    • Integration tests catch what mocks hide, such as wrong SQL or JSON mapping.
    • The pyramid is a guide to proportions, not a rule to count tests by.

    Go to the module

  160. What makes a good unit test?

    Unit Testing The testing pyramid Junior Concept

    Show answer

    The F.I.R.S.T. properties. Fast, so the suite runs on every change. Isolated, so tests share no state and can run in any order. Repeatable, so the result never depends on the clock, the machine or the network. Self-validating, so assertions decide pass or fail. Timely, so it is written with the code. A good test also checks one behavior and reads like an example.

    • One reason to fail per test, named after the behavior it checks.
    • Inject time, randomness and I/O so a test can control them.
    • Test behavior through the public API, not private methods.

    Go to the module

  161. Why should most of your tests be unit tests?

    Unit Testing The testing pyramid Junior Concept

    Show answer

    Because they give the fastest and most precise feedback. A thousand unit tests run in seconds, so developers run them on every change, and a failure names the class and the case. Each step up the pyramid costs more time, setup and flakiness per test. Higher layers are still needed, but only for what lower layers cannot see.

    • Cheap tests can cover every edge case; expensive ones should cover the main paths.
    • Fast feedback keeps the suite in use before every commit.
    • A failure low in the pyramid is cheaper to find and fix.

    Go to the module

  162. A team has hundreds of end-to-end tests and few unit tests. What problems do you expect?

    Unit Testing The testing pyramid Junior Scenario

    Show answer

    This is the ice-cream cone anti-pattern. The suite takes many minutes or hours, so it runs rarely and feedback comes late. Tests fail for reasons unrelated to the change, such as timeouts or test data, so people learn to rerun them. A red build says little about where the bug is. The fix is to push each check down to the lowest layer that can catch it.

    • Slow suites move testing to the end of the day or to CI (continuous integration) only.
    • Flaky tests teach the team to ignore red builds.
    • Edge cases are expensive at the top, so they go untested.

    Go to the module

  163. A test passes on your machine but fails in CI now and then. What do you look for?

    Unit Testing The testing pyramid Junior Scenario

    Show answer

    Something the test does not control. Common causes are shared state between tests, so order matters; the current time or time zone; random data without a fixed seed; real network calls; and waiting with a fixed sleep instead of waiting for a condition. Each one breaks the Isolated or Repeatable property. Reproduce it by running the test in a loop or in a different order, then remove that dependency.

    • Run the suite in random order to expose hidden ordering.
    • Replace sleeps with polling on a condition, for example with Awaitility.
    • Quarantine is a short-term measure; fix the cause.

    Go to the module

  164. Is there code you would not cover with unit tests?

    Unit Testing The testing pyramid Mid-level Concept

    Show answer

    Yes. Code with no logic of its own, such as getters, plain mappings or framework configuration, gains little from a unit test. Code whose whole job is to talk to something external, such as a repository query or an HTTP client, needs an integration test to prove anything, since mocking the database tests only the mock. Put unit tests where the decisions are.

    • A mocked repository cannot show that the SQL is right.
    • Trivial code gets covered by the tests of the code that uses it.
    • Test generated or framework code only where you configured it.

    Go to the module

  165. What are the JUnit 5 lifecycle annotations, and in what order do they run?

    Unit Testing JUnit 5 Junior Concept

    Show answer

    @BeforeAll runs once before all tests in a class, and @AfterAll once after them; both are static by default. For every @Test, JUnit creates a new instance of the class, then runs @BeforeEach, the test and @AfterEach. @AfterEach runs even when the test fails. Use the per-test pair for cheap setup and the per-class pair for costly shared resources.

    • A new instance per test means fields never carry state from one test to the next.
    • @AfterEach and @AfterAll are for cleanup, and they run after failures too.
    • @TestInstance(Lifecycle.PER_CLASS) shares one instance and lets @BeforeAll be non-static.
    • JUnit 4 names were @Before, @After, @BeforeClass and @AfterClass.

    Go to the module

  166. Which JUnit 5 assertions do you use most, and when?

    Unit Testing JUnit 5 Junior Code

    Show answer

    assertEquals(expected, actual) for values, assertTrue and assertFalse for conditions, and assertThrows to check an exception; it returns the exception so you can check its message. assertAll runs several assertions and reports every failure, not just the first. Many teams use AssertJ's assertThat(...) instead for readable chains and better messages.

    • The expected value comes first in assertEquals, or the failure message is backwards.
    • assertThrows replaces JUnit 4's @Test(expected = ...) and pins the exact statement that throws.
    • assertAll groups related checks so one run shows every broken field.
    var e = assertThrows(IllegalArgumentException.class,
        () -> cart.add(item("pen", -1)));
    assertEquals("price must not be negative", e.getMessage());
    
    assertAll(
        () -> assertEquals("ana", order.customer()),
        () -> assertEquals(2, order.lines().size()));

    Go to the module

  167. How do you run the same test with different inputs in JUnit 5?

    Unit Testing JUnit 5 Junior Code

    Show answer

    With @ParameterizedTest and a source of arguments. @ValueSource passes single values, @CsvSource passes rows of values, @EnumSource passes enum constants, and @MethodSource takes them from a static method returning a stream. JUnit runs the method once per row and reports each run as its own test, so one failing case does not hide the others.

    • It needs the junit-jupiter-params artifact, which the junit-jupiter aggregate includes.
    • name = "{0} pays {1}" makes each run readable in the report.
    • Prefer it over a loop inside one test, which stops at the first failing case.

    Go to the module

  168. What is the Arrange-Act-Assert pattern?

    Unit Testing JUnit 5 Junior Concept

    Show answer

    A layout for the body of a test. Arrange sets up the object and its inputs, Act calls the one behavior under test, and Assert checks the outcome. Keeping the three parts apart, often with a blank line, makes a test easy to read and makes it obvious what failed. Given-When-Then is the same idea in BDD (behavior-driven development) words.

    • One act per test; a second act usually means a second test.
    • Shared arrange steps move to @BeforeEach or a helper method.
    • The test name should say the case and the expected outcome.

    Go to the module

  169. What changed from JUnit 4 to JUnit 5?

    Unit Testing JUnit 5 Junior Comparison

    Show answer

    JUnit 5 is split into the Platform, which launches tests; Jupiter, the new programming model; and Vintage, which still runs JUnit 4 tests. Annotations were renamed, so @Before became @BeforeEach. Runners and rules were replaced by one extension model, @ExtendWith. Test classes and methods no longer need to be public, and it added assertThrows, assertAll, nested tests and parameterized tests built in.

    • @RunWith(MockitoJUnitRunner.class) becomes @ExtendWith(MockitoExtension.class).
    • Vintage lets JUnit 4 and JUnit 5 tests run side by side during a migration.
    • JUnit 5 needs Java 8 or later.

    Go to the module

  170. Why does JUnit create a new instance of the test class for each test method?

    Unit Testing JUnit 5 Mid-level Concept

    Show answer

    To keep tests isolated. Each test starts from fresh instance fields, so no test can depend on what another one left behind, and tests can run in any order or in parallel. The cost is small, because constructing a test class is cheap. State that should really be shared, such as a container, goes in static fields set up in @BeforeAll.

    • It is the default Lifecycle.PER_METHOD.
    • Static fields are still shared, so they can still leak state.
    • Isolation is what makes running in random order or in parallel safe.

    Go to the module

  171. What is the difference between a mock, a stub, a spy and a fake?

    Unit Testing Mockito: mocks, stubs and spies Junior Comparison

    Show answer

    All four are test doubles that stand in for a real dependency. A stub returns canned answers, and the test checks the result. A mock records calls, and the test verifies the interaction. A spy wraps a real object, so real methods run unless stubbed. A fake is a working, simpler implementation, such as an in-memory repository. In Mockito, one mock() object can be both stubbed and verified.

    • Stubs and fakes support state checks; mocks and spies support interaction checks.
    • Unstubbed calls on a Mockito mock return defaults, such as false, 0, null or an empty list.
    • A fake needs no framework and often makes tests easier to read.
    • Verify only interactions that matter, such as a payment being charged.

    Go to the module

  172. What is the difference between when(...).thenReturn(...) and verify(...)?

    Unit Testing Mockito: mocks, stubs and spies Junior Comparison

    Show answer

    when(...).thenReturn(...) happens before the act: it tells the mock what to answer, so the code under test can run. verify(...) happens after: it checks that a call happened, with the given arguments and how many times. Stub what the code needs to read, and verify what the code must do, such as charging a card or sending an email.

    • Do not verify a call you also stubbed just to feed the code; the result already proves it.
    • verify(mock, never()) checks that something did not happen.
    • times(n), atLeastOnce() and argument matchers like eq() refine a check.

    Go to the module

  173. What does @InjectMocks do?

    Unit Testing Mockito: mocks, stubs and spies Junior Concept

    Show answer

    It creates the object under test and passes it the @Mock and @Spy fields of the test class. Mockito tries constructor injection with the biggest constructor first, then setters, then fields. A dependency with no matching mock gets null, with no error, so a test can fail far from the cause. Constructor injection in the class keeps it predictable, and plain new OrderService(gateway) works just as well.

    • It needs MockitoExtension or MockitoAnnotations.openMocks(this) to run.
    • Mocks are matched to parameters by type, then by name.
    • It is a Mockito feature, unrelated to Spring's context.

    Go to the module

  174. When do you use an ArgumentCaptor?

    Unit Testing Mockito: mocks, stubs and spies Junior Code

    Show answer

    When the code under test builds an object inside and passes it to a dependency, and the test needs to check that object's fields. Verify the call with captor.capture() as the argument, then assert on getValue(). For a simple value, an exact argument or a matcher in verify is clearer than a captor.

    • Capture inside verify, not inside when.
    • getAllValues() returns every captured value when the call happened several times.
    • argThat(...) is an alternative for a one-line condition.
    ArgumentCaptor<Email> email = ArgumentCaptor.forClass(Email.class);
    verify(mailer).send(email.capture());
    assertEquals("[email protected]", email.getValue().to());

    Go to the module

  175. What goes wrong when a test mocks every collaborator?

    Unit Testing Mockito: mocks, stubs and spies Mid-level Scenario

    Show answer

    The test starts describing the implementation instead of the behavior. Every refactoring that changes which methods get called breaks it, even when the result is the same, and it can pass while the real parts do not fit together. Mock what is slow or outside your control, such as payment, email or the clock. Use real objects or fakes for simple collaborators.

    • Do not mock value objects or simple data classes.
    • Prefer not to mock types you do not own; wrap them and test the wrapper with an integration test.
    • A test with many mocks often points to a class with too many dependencies.

    Go to the module

  176. Can Mockito mock final classes and static methods?

    Unit Testing Mockito: mocks, stubs and spies Mid-level Concept

    Show answer

    Yes, with the inline mock maker, which is the default since Mockito 5; Mockito 4 needed the mockito-inline artifact. Static methods are mocked with mockStatic(...) in a try-with-resources block, so the change lasts only inside it. Needing this often is a design smell: inject a Clock or a wrapper instead of mocking a static call.

    • try (var mocked = mockStatic(UUID.class)) { ... } scopes the static mock.
    • The inline mock maker changes the bytecode of the existing class.
    • Private methods still cannot be mocked, by design.

    Go to the module

  177. What is test-driven development?

    Unit Testing TDD: red, green, refactor Mid-level Concept

    Show answer

    A way of writing code in short loops, with the test first. Red: write a small test and watch it fail. Green: write the least code that makes it pass. Refactor: clean up while the tests stay green. Then repeat with the next behavior. The tests come out as a side effect; the main gain is that they shape the design from the caller's view.

    • Seeing the test fail first proves that it can fail.
    • Each loop takes minutes, so the code is never far from working.
    • Refactoring is a required step, not an optional extra.
    • Hard-to-write tests are early feedback on the design.

    Go to the module

  178. What are the benefits and limits of TDD?

    Unit Testing TDD: red, green, refactor Mid-level Concept

    Show answer

    Benefits: small, testable designs, a suite you trust when refactoring, and fast feedback with little debugging. Limits: it costs more time up front, it fits poorly when you are still exploring an unknown API or a UI, and it does not catch wrong requirements or integration problems. A suite that mirrors the implementation can also slow refactoring. Use it where logic matters, and spike first when you are unsure.

    • It works best for business rules with clear inputs and outputs.
    • A throwaway spike is fine for learning; then rebuild the code test-first.
    • Integration and end-to-end tests are still needed.

    Go to the module

  179. Why write the simplest code that passes, even when you know it is incomplete?

    Unit Testing TDD: red, green, refactor Mid-level Concept

    Show answer

    Because each line then exists for a test that demands it, so no untested or speculative code gets in. The next test forces the code to become more general; this is called triangulation. It also keeps each loop short, and a wrong guess costs minutes. Returning a hard-coded value is a legal step, as long as a later test forces it out.

    • It applies YAGNI (You Aren't Gonna Need It) at the level of a single line.
    • Two different examples force a general rule, where one lets you fake it.
    • Clean-up belongs to the refactor step, not the green step.

    Go to the module

  180. Is writing tests after the code just as good as TDD?

    Unit Testing TDD: red, green, refactor Mid-level Comparison

    Show answer

    It can give the same coverage, and good tests either way beat no tests. The difference is feedback. Written first, a test shapes the design and is seen to fail. Written later, it tends to confirm what the code already does, a bug can get locked in, and code that is hard to test is already built. Test-after works if you still check that each test can fail.

    • Temporarily break the code to see a test written later fail.
    • The result to judge is a trustworthy suite, not the order of writing.
    • Mutation testing shows whether a suite catches changes, however it was written.

    Go to the module

  181. What is the difference between @SpringBootTest, @WebMvcTest and @DataJpaTest?

    Unit Testing Testing in Spring Boot Mid-level Comparison

    Show answer

    They differ in how much of the application context they load. @SpringBootTest loads everything, so it checks wiring across layers but starts slowest. @WebMvcTest loads only the web layer, with MockMvc, so services must be mocks. @DataJpaTest loads repositories and JPA (Jakarta Persistence API), and rolls back each test. Use a slice for one layer, and a few full tests for how layers fit.

    • @WebMvcTest skips @Service, @Repository and plain @Component beans.
    • @DataJpaTest uses an embedded database by default, if one is on the classpath.
    • Logic with no framework needs no annotation at all, only a plain unit test.
    • Spring caches contexts, so keep the number of distinct configurations low.

    Go to the module

  182. What is MockMvc, and what does it test?

    Unit Testing Testing in Spring Boot Mid-level Code

    Show answer

    It sends a simulated request through DispatcherServlet with no server or socket. That runs URL mapping, argument binding, validation, JSON conversion, @ControllerAdvice and the status code, none of which a direct call to the controller method would run. It is available in @WebMvcTest, and in @SpringBootTest with @AutoConfigureMockMvc.

    • It tests the HTTP contract of a controller, not just the method.
    • jsonPath("$.id") checks fields in the response body.
    • No network is involved, so it does not check a real server's settings.
    mvc.perform(post("/orders")
            .contentType(MediaType.APPLICATION_JSON)
            .content("{\"amount\": -1}"))
       .andExpect(status().isBadRequest());

    Go to the module

  183. What is @MockitoBean, and how is it different from @Mock?

    Unit Testing Testing in Spring Boot Mid-level Comparison

    Show answer

    @MockitoBean puts a Mockito mock into the Spring application context, adding the bean or replacing the existing one, so anything wired by Spring receives it. @Mock only creates an object in the test class, with no context involved. Use @Mock in plain unit tests. @MockitoBean came with Spring Framework 6.2 and replaces Spring Boot's deprecated @MockBean.

    • It is reset after each test method by default.
    • Each different set of mocks changes the context cache key.
    • @MockitoSpyBean wraps an existing bean, as @SpyBean did.

    Go to the module

  184. How does Spring keep integration tests from starting a new context every time?

    Unit Testing Testing in Spring Boot Mid-level Concept

    Show answer

    The TestContext framework caches application contexts in a static map, keyed by the test's configuration: classes, profiles, properties and mocked beans. A class with the same key reuses the context, so only the first class pays for startup. Anything that changes the key starts another context, and @DirtiesContext throws one away. A shared base test class is a common way to keep one key.

    • A different @MockitoBean list or @TestPropertySource means a new context.
    • The cache lives in the JVM (Java Virtual Machine), so it only helps tests in the same process.
    • Overusing @DirtiesContext removes the benefit.

    Go to the module

  185. Which database does a @DataJpaTest run against?

    Unit Testing Testing in Spring Boot Mid-level Scenario

    Show answer

    By default, an embedded database such as H2 replaces your configured DataSource, and each test rolls back in a transaction. That is fast, but SQL that only works on your real engine can fail or pass wrongly. Add @AutoConfigureTestDatabase(replace = Replace.NONE) and point it at a real database, usually with Testcontainers. Call flush() when you need the SQL to run before the rollback.

    • With no embedded database on the classpath, the default setup fails to start.
    • Without a flush, some writes never reach the database before rollback.
    • TestEntityManager helps set up data for the test.

    Go to the module

  186. A @WebMvcTest fails with NoSuchBeanDefinitionException for a service. Why, and how do you fix it?

    Unit Testing Testing in Spring Boot Mid-level Scenario

    Show answer

    The slice loads the controller but not @Service beans, so the controller's constructor has nothing to receive. Add @MockitoBean for that service. Do not add @Import of the real service unless you want it in the test, since that pulls in its own dependencies too. If the error names a bean unrelated to this controller, check for extra beans declared on the @SpringBootApplication class.

    • Name the controller, @WebMvcTest(OrderController.class), to avoid loading the others.
    • Beans declared on the main class load in every slice, so move them to a @Configuration.
    • The failure comes at context startup, before any test runs.

    Go to the module

  187. Why not use H2 for integration tests?

    Unit Testing Integration testing with Testcontainers Mid-level Scenario

    Show answer

    Because H2 is not your production database. Its SQL dialect, types, functions and locking differ, so a test can fail on valid PostgreSQL, or pass on SQL that production rejects. PostgreSQL features such as jsonb operators, extensions or your real migration scripts may not run at all. Testcontainers runs the same engine and version as production in Docker, at the cost of a few seconds of startup.

    • PostgreSQL mode in H2 is an approximation, not the real engine.
    • Flyway or Liquibase scripts get tested against the real engine too.
    • Sharing one container per test class or suite keeps the cost low.

    Go to the module

  188. How do Testcontainers work?

    Unit Testing Integration testing with Testcontainers Mid-level Concept

    Show answer

    It is a Java library that drives Docker from your tests. Before the tests, it pulls the image if needed, starts the container, waits until the service is really ready, and maps its port to a random free host port. Your test reads the real address from the container object. Afterward it removes the container, and a helper called Ryuk removes anything left behind if the JVM dies.

    • Random ports let many builds run on one machine with no clashes.
    • A wait strategy, not a fixed sleep, decides when the container is ready.
    • It has modules for databases, Kafka and more, plus GenericContainer for any image.

    Go to the module

  189. What is the difference between a static and a non-static @Container field?

    Unit Testing Integration testing with Testcontainers Mid-level Comparison

    Show answer

    A static field gives one container, started before the first test and stopped after the last in that class, so tests share it and its data. An instance field gives each test method its own new container: clean but slow. For a whole suite, the singleton container pattern starts one in a static initializer of a base class and never stops it, leaving cleanup to Ryuk.

    • Shared containers mean tests must clean up or use unique data.
    • @Transactional tests can roll back their writes in a shared container.
    • With a singleton container, Spring's context cache can also be reused across classes.

    Go to the module

  190. The container's port is random. How does Spring Boot find it?

    Unit Testing Integration testing with Testcontainers Mid-level Code

    Show answer

    Since Spring Boot 3.1, @ServiceConnection on the container field does it for you: Boot reads the connection details from the container. Before that, @DynamicPropertySource registers spring.datasource.url and the rest from the container's getters. Either way the container must be running before the context starts, which a static @Container field guarantees.

    • getJdbcUrl() returns the URL with the mapped host port.
    • Hard-coding a port would break parallel builds.
    • The method references are read lazily, once the container has started.
    @DynamicPropertySource
    static void databaseProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
    }

    Go to the module

  191. Is 100% code coverage enough?

    Unit Testing Coverage and mutation testing Senior Scenario

    Show answer

    No. Coverage shows which code ran during the tests, not that anything checked the result. A test with no assertion still counts, and a suite can reach 100% while missing a boundary value. So low coverage is a useful warning about untested code, but high coverage proves little. Mutation testing asks the harder question: would a test fail if this code were wrong?

    • Use coverage to find untested code, not as proof of quality.
    • Setting a high target as a goal invites tests that assert nothing.
    • Boundaries and missing requirements stay invisible to coverage.

    Go to the module

  192. What is JaCoCo, and which coverage does it report?

    Unit Testing Coverage and mutation testing Senior Concept

    Show answer

    The usual Java coverage tool. A Java agent instruments the bytecode as classes load, and the test run records what executed in a jacoco.exec file, which becomes an HTML or XML report. It counts instructions, lines, branches, methods and classes, plus cyclomatic complexity. Its check goal can fail the build below a threshold.

    • It works on bytecode, so it needs no change to your source.
    • Branch coverage counts the outcomes of each condition, which is stricter than lines.
    • Exclude generated code and plain data classes from the report.

    Go to the module

  193. What is mutation testing, and how does PIT work?

    Unit Testing Coverage and mutation testing Senior Concept

    Show answer

    It tests the tests. PIT makes small changes to the bytecode, called mutants, such as >= to > or a return value to 0. For each mutant it runs the tests that cover that line. If a test fails, the mutant is killed; if all pass, it survives and shows a gap. The score is the share killed. It is slow, so run it on changed code or nightly.

    • PIT uses coverage data to run only the tests that reach each mutant.
    • Some survivors are equivalent mutants, which behave the same as the original and can never be killed.
    • Run it with mvn org.pitest:pitest-maven:mutationCoverage.

    Go to the module

  194. How do you test integrations between microservices without end-to-end tests?

    Unit Testing Contract testing Senior Design

    Show answer

    With contract tests. The two sides agree on a contract for one API: this request gets this response. The consumer tests its client against a mock generated from the contract, and the provider replays the contract against its real service. Each runs in its own build, with neither deployed, so a breaking change fails fast. Pact and Spring Cloud Contract are the common tools.

    • A hand-written mock only tests your own assumption; a contract is checked on both sides.
    • Failures point at one API and one consumer, not a whole environment.
    • Contract tests check the shape of an API, not its business rules.
    • Keep a few end-to-end tests for the critical flows.

    Go to the module

  195. What is the difference between Pact and Spring Cloud Contract?

    Unit Testing Contract testing Senior Comparison

    Show answer

    They start from opposite sides. In Pact, contracts are consumer-driven: consumer tests generate them, so the provider learns exactly which fields are used, and it works across languages. In Spring Cloud Contract, contracts usually live with the producer, written in Groovy or YAML; it generates tests for the producer and WireMock stubs for consumers. It fits JVM (Java Virtual Machine) teams on Spring.

    • Consumer-driven contracts fit many consumers with different needs.
    • A shared broker or a stubs JAR (Java archive) is how each tool distributes contracts.
    • Spring Cloud Contract can also support a consumer-driven workflow, through pull requests to the producer.

    Go to the module

  196. Isn't validating against an OpenAPI schema the same as a contract test?

    Unit Testing Contract testing Senior Comparison

    Show answer

    Not quite. An OpenAPI schema says everything a provider offers, and checking against it shows the response is valid. A consumer-driven contract says what one consumer really uses, so the provider knows which change breaks whom, and can remove a field nobody reads. A schema also rarely covers provider states. Bi-directional approaches compare consumer contracts with the provider's schema.

    • A schema can pass while a consumer still breaks on an assumption it never stated.
    • Contracts show which fields are safe to change.
    • Schemas are still valuable as documentation and for generating clients.

    Go to the module

  197. What are inversion of control and dependency injection in Spring?

    Spring Boot IoC and dependency injection Junior Concept

    Show answer

    Inversion of control means a class no longer creates or finds its own dependencies: the framework does. Dependency injection is how Spring does it. You declare what a class needs, usually as constructor parameters, and the container builds the objects and passes them in. Classes depend on abstractions, so they are loosely coupled and easy to test with a mock.

    • IoC is the principle; dependency injection is the technique Spring uses.
    • The container reads bean definitions, then builds the graph from the leaves upward.
    • A bean is an object whose lifecycle the Spring container manages.
    • Beans are singletons by default, so one instance is shared.

    Go to the module

  198. What are the types of dependency injection in Spring, and when do you use each?

    Spring Boot IoC and dependency injection Junior Comparison

    Show answer

    There are three: constructor, setter and field. Constructor injection is the default for required dependencies. Setter injection fits an optional dependency that may change after creation. Field injection sets a private field by reflection: it is short, but it hides dependencies and needs Spring or reflection to test, so keep it out of application code.

    • Only constructor injection allows final fields.
    • Mark an optional dependency with ObjectProvider or @Autowired(required = false).
    • Field injection is still common in test classes, where it does little harm.
    // Constructor: required
    OrderService(OrderRepository repository) { this.repository = repository; }
    
    // Setter: optional
    @Autowired(required = false)
    void setAudit(AuditLog audit) { this.audit = audit; }
    
    // Field: avoid in application code
    @Autowired private OrderRepository repository;

    Go to the module

  199. Why is constructor injection preferred over field injection?

    Spring Boot IoC and dependency injection Junior Comparison

    Show answer

    A constructor makes dependencies explicit and required, so an object can never exist half built. Fields can be final, which gives safe immutability. A unit test can call new and pass mocks with no Spring. A long parameter list is also a useful warning that the class does too much, while field injection hides that growth.

    • With field injection, plain new leaves the field null, so the failure comes at run time.
    • The compiler catches a missing constructor argument.
    • Lombok @RequiredArgsConstructor removes the boilerplate and keeps the benefits.

    Go to the module

  200. What happens when two beans depend on each other?

    Spring Boot IoC and dependency injection Mid-level Scenario

    Show answer

    Startup fails with BeanCurrentlyInCreationException. Since Spring Boot 2.6 this applies to field and setter injection too, because circular references are off by default. Setting spring.main.allow-circular-references=true makes field injection work again, but a constructor cycle still fails, since neither object can exist first. The real fix is a redesign: extract the shared logic into a third bean.

    • A cycle is a design smell, usually two classes that should be split differently.
    • @Lazy on one constructor parameter breaks the cycle by injecting a proxy.
    • Events are another way to remove a dependency in one direction.

    Go to the module

  201. What is the difference between BeanFactory and ApplicationContext?

    Spring Boot IoC and dependency injection Junior Comparison

    Show answer

    BeanFactory is the basic container: it creates and wires beans, lazily, when asked. ApplicationContext extends it and is what you use in practice. It creates singletons eagerly at startup, so wiring errors appear at once, and it adds events, message sources, environment access and automatic post-processor registration. Spring Boot creates an ApplicationContext for you.

    • Eager creation means a missing bean fails the startup, not the first request.
    • @Lazy opts a single bean out of eager creation.
    • You rarely call getBean yourself; injection replaces it.

    Go to the module

  202. Should you inject an interface or a concrete class?

    Spring Boot IoC and dependency injection Mid-level Design

    Show answer

    Inject an interface when there are real alternatives, or a boundary you want to keep replaceable, such as a payment gateway. An interface with one implementation forever adds a file and no value, so injecting the class is fine: Mockito can mock it, and Spring Boot's default proxies work on classes. Choose by whether the abstraction earns its place.

    • The dependency inversion principle is about depending on abstractions at boundaries, not everywhere.
    • Two implementations of one interface need @Primary or @Qualifier.
    • Hexagonal architecture puts its ports, as interfaces, at these boundaries.

    Go to the module

  203. What is the difference between @Component, @Service, @Repository and @Controller?

    Spring Boot Stereotypes and component scan Junior Comparison

    Show answer

    All four make a class a bean, because the last three are themselves annotated with @Component, so the scan finds them the same way. The difference is meaning and a little behavior. @Service adds nothing but intent. @Repository translates persistence exceptions into DataAccessException. @Controller is what Spring MVC (Model-View-Controller) maps URLs to.

    • @RestController is @Controller plus @ResponseBody.
    • Stereotypes let pointcuts and test slices target a layer.
    • Swapping @Service for @Component changes no behavior.
    • The default bean name is the class name with a lowercase first letter.

    Go to the module

  204. When do you use @Bean instead of @Component?

    Spring Boot Stereotypes and component scan Junior Comparison

    Show answer

    @Component goes on a class you own, and the scan finds it. @Bean goes on a method in a @Configuration class, and you write the code that creates the object. Use @Bean for a class from a library, which you cannot annotate, or when creation needs logic or several configured instances of one type. The bean name defaults to the method name.

    • One class can have several @Bean methods with different settings.
    • Parameters of a @Bean method are injected like constructor arguments.
    • @Bean also takes initMethod, destroyMethod and scope settings.
    @Configuration
    class ClientConfig {
        @Bean
        RestClient paymentsClient(RestClient.Builder builder) {
            return builder.baseUrl("https://pay.example").build();
        }
    }

    Go to the module

  205. What is the difference between @Qualifier and @Primary?

    Spring Boot Stereotypes and component scan Junior Comparison

    Show answer

    Both solve "several beans of one type". @Primary goes on a bean and makes it the default wherever nothing more specific is asked. @Qualifier goes on the injection point and names the bean wanted there. @Qualifier wins when both apply. With neither, a parameter name that matches a bean name is the fallback, and otherwise startup fails.

    • @Primary decides at the provider; @Qualifier decides at the consumer.
    • Both can be avoided by injecting List<Gateway> or Map<String, Gateway>.
    • The map's keys are bean names, which suits a strategy lookup.

    Go to the module

  206. Your @Service is not found, and startup fails with a missing bean. What do you check?

    Spring Boot Stereotypes and component scan Junior Scenario

    Show answer

    First the package. @SpringBootApplication scans the package of its own class and everything below it, so a class in a sibling package is never found. Move the main class up to the root package, or add @ComponentScan or @Import. Then check the stereotype is on the implementation, not the interface, and that no profile or condition excludes it.

    • The main class belongs in the root package, above everything else.
    • A stereotype on an interface does not register a bean.
    • A class in a shared library usually joins through auto-configuration, not by a wider scan.

    Go to the module

  207. What does exception translation in @Repository give you?

    Spring Boot Stereotypes and component scan Mid-level Concept

    Show answer

    It turns vendor exceptions, from Hibernate or JDBC (Java Database Connectivity), into Spring's DataAccessException hierarchy. A service can catch DataIntegrityViolationException for a duplicate key, with no dependency on the database or the ORM (object-relational mapping). The translation happens in a proxy around the repository, so it applies to calls coming from outside the bean.

    • DataAccessException is unchecked, so it does not spread through method signatures.
    • A unique key violation arrives as DataIntegrityViolationException, whichever database you use.
    • Translation depends on the proxy, like @Transactional.

    Go to the module

  208. What is the difference between @Configuration and @Component on a class with @Bean methods?

    Spring Boot Stereotypes and component scan Mid-level Code

    Show answer

    A @Configuration class is proxied, so one @Bean method calling another returns the shared bean. In a @Component class, or with proxyBeanMethods = false, that call is a plain Java call, and you get a second object the container does not manage. Boot's own auto-configurations use proxyBeanMethods = false, and take dependencies as parameters.

    • With proxyBeanMethods = true the call returns the same instance, and with false a new one.
    • Declaring dependencies as method parameters works in both modes.
    • false avoids creating a subclass, so startup does less work.
    @Configuration
    class Config {
        @Bean Engine engine() { return new Engine(); }
    
        // The same Engine bean, because the class is proxied
        @Bean Car car() { return new Car(engine()); }
    }

    Go to the module

  209. What is the lifecycle of a Spring bean?

    Spring Boot Bean lifecycle and scopes Mid-level Concept

    Show answer

    The container calls the constructor, then runs field and setter injection. Next come Aware callbacks and BeanPostProcessors, then @PostConstruct, afterPropertiesSet and any initMethod. Post-processors run again, and this is where a proxy may wrap the bean. It then serves calls until the context closes, when @PreDestroy, destroy and any destroyMethod run.

    • Injected fields are still null in the constructor; @PostConstruct is safe.
    • AOP (aspect-oriented programming) proxies are applied after initialization.
    • The setup callbacks run as @PostConstruct, then afterPropertiesSet, then initMethod.
    • Prefer @PostConstruct and @PreDestroy, which do not tie a class to Spring interfaces.

    Go to the module

  210. What is the difference between singleton, prototype and request scope?

    Spring Boot Bean lifecycle and scopes Mid-level Comparison

    Show answer

    A singleton, the default, is one instance per application context, created at startup and shared. A prototype is a new instance each time the container is asked. A request-scoped bean is one instance per HTTP request, and needs a web context. Session and application scopes exist too. A Spring singleton is one per context, not one per JVM (Java Virtual Machine).

    • Most beans are stateless singletons.
    • A prototype is new per lookup or injection, not per method call.
    • @RequestScope is @Scope("request") with a proxy already configured.

    Go to the module

  211. What happens when you inject a prototype bean into a singleton?

    Spring Boot Bean lifecycle and scopes Mid-level Scenario

    Show answer

    The prototype is created once, when the singleton is built, and that same instance is used forever, so it behaves like a singleton. To get a new one per use, inject ObjectProvider and call getObject(), use a @Lookup method, or configure a scoped proxy. Each of those gives a new instance every time.

    • Scope is applied when the container hands out the bean, not on each method call.
    • ObjectProvider avoids a dependency on ApplicationContext.
    • The container forgets a prototype after creating it, so it never calls @PreDestroy.
    class ReportJob {
        private final ObjectProvider<ReportBuilder> builders;
    
        ReportJob(ObjectProvider<ReportBuilder> builders) {
            this.builders = builders;
        }
    
        String run() {
            return builders.getObject().build();    // new each call
        }
    }

    Go to the module

  212. How can a singleton controller use a request-scoped bean?

    Spring Boot Bean lifecycle and scopes Mid-level Scenario

    Show answer

    Through a proxy. @RequestScope makes Spring inject a proxy into the singleton, and each method call on it finds the instance for the current request. Without a proxy, as with plain @Scope("request"), the singleton needs the bean at startup, when no request exists, and the context fails with ScopeNotActiveException.

    • Calling the proxy outside a request throws the same exception.
    • ObjectProvider also works: the lookup happens inside the request.
    • Instances live in the request, so a new thread does not see them.

    Go to the module

  213. Are Spring singleton beans thread-safe?

    Spring Boot Bean lifecycle and scopes Mid-level Concept

    Show answer

    Not by themselves. The container creates one instance, and every request thread calls it at once, with no locking from Spring. A stateless bean with only final dependencies is safe. A mutable field, such as a counter or a request's data, is a race condition. Move that state to local variables, a request scope, or a concurrent type.

    • Local variables live on each thread's stack, so they are safe.
    • Use AtomicInteger or ConcurrentHashMap for state that really is shared.
    • Never keep data for one request in a singleton's field.
    @Service
    class OrderService {
        private Order current;              // a race: all threads share this
    
        void place(Order order) {
            Order current = order;          // safe: a local variable
        }
    }

    Go to the module

  214. Why is @PreDestroy not called on prototype beans?

    Spring Boot Bean lifecycle and scopes Mid-level Concept

    Show answer

    The container creates and initializes a prototype, hands it over, and keeps no reference, so it cannot know when the bean is finished, and has nothing to destroy at shutdown. So @PostConstruct runs and @PreDestroy does not. If a prototype holds a resource, whoever asked for it must close it.

    • Keeping references would be a memory leak, which is why the container does not.
    • Making the bean AutoCloseable lets callers use try-with-resources.
    • Singletons are destroyed in the reverse order of their dependencies.

    Go to the module

  215. What does @SpringBootApplication do?

    Spring Boot Auto-configuration and starters Mid-level Concept

    Show answer

    It combines three annotations. @SpringBootConfiguration marks the class as a configuration source. @ComponentScan finds your beans in this package and below. @EnableAutoConfiguration loads candidate configurations from the classpath, and each registers beans only if its conditions pass. SpringApplication.run then starts the context and, for a web application, the embedded server.

    • Put the main class in the root package, because the scan starts there.
    • Your beans are registered first, so conditions can see them.
    • Starters supply the libraries; auto-configuration supplies the beans.
    • It is a shorthand, and each of the three can be used on its own.

    Go to the module

  216. How does auto-configuration decide what to configure?

    Spring Boot Auto-configuration and starters Mid-level Concept

    Show answer

    Boot reads the candidate classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in each jar. Each is a @Configuration behind conditions: @ConditionalOnClass checks the classpath, @ConditionalOnMissingBean checks your beans, and @ConditionalOnProperty checks settings. Only classes that pass are applied. Spring Boot 2.7 introduced this file, replacing the spring.factories entry.

    • There are several hundred candidates, and most are skipped on any one application.
    • @ConditionalOnWebApplication and @ConditionalOnBean are other common conditions.
    • Conditions on missing beans are why ordering matters, and why your beans go first.

    Go to the module

  217. What is a Spring Boot starter?

    Spring Boot Auto-configuration and starters Mid-level Concept

    Show answer

    A dependency with almost no code that brings a tested set of libraries for one purpose. spring-boot-starter-web, called spring-boot-starter-webmvc from Boot 4, brings Spring MVC (Model-View-Controller), Tomcat and JSON support. Versions come from Boot's dependency management, so you do not pick them one by one. The libraries then satisfy the conditions of auto-configuration, which registers the beans.

    • A starter brings dependencies; auto-configuration creates beans.
    • Swap Tomcat by excluding it and adding another server's starter.
    • A third-party starter is named acme-spring-boot-starter, not spring-boot-starter-acme.

    Go to the module

  218. You define your own DataSource bean. What happens to Boot's auto-configured one?

    Spring Boot Auto-configuration and starters Mid-level Scenario

    Show answer

    Boot backs off. Its DataSource sits behind @ConditionalOnMissingBean, so your bean satisfies the type and Boot's is never created. Everything built on it, such as the EntityManagerFactory and JdbcTemplate, is still auto-configured and uses yours, so the context holds one DataSource, named after your method.

    • Replace the smallest piece that does what you need.
    • Properties such as spring.datasource.url are often enough.
    • With your own bean, the spring.datasource.* properties no longer configure it for you.

    Go to the module

  219. You add the JPA (Jakarta Persistence API) starter and the application stops starting, with a driver or URL error. Why?

    Spring Boot Auto-configuration and starters Mid-level Scenario

    Show answer

    The starter put JPA on the classpath, so its auto-configuration now wants a DataSource. With no driver and no spring.datasource.url, Boot cannot build one, and startup fails with "Failed to determine a suitable driver class". Add an embedded database, set the URL and driver for a real one, or exclude the configuration if you do not need a database yet.

    • A dependency alone can change what starts.
    • An embedded database such as H2 on the classpath needs no URL.
    • Boot's failure analyzer prints a description and a suggested action.

    Go to the module

  220. How would you write your own auto-configuration?

    Spring Boot Auto-configuration and starters Senior Design

    Show answer

    Write a class with @AutoConfiguration, and guard it with @ConditionalOnClass. Mark each @Bean with @ConditionalOnMissingBean, so applications can override it. Bind settings with @ConfigurationProperties. List the class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Publish it in a starter, and test with ApplicationContextRunner, trying each condition.

    • Do not put an auto-configuration in the application's scanned packages.
    • @AutoConfiguration(after = ...) orders it relative to others.
    • ApplicationContextRunner starts a small context for each case, quickly.
    @AutoConfiguration
    @ConditionalOnClass(AuditClient.class)
    public class AuditAutoConfiguration {
        @Bean
        @ConditionalOnMissingBean
        AuditClient auditClient() {
            return new AuditClient();
        }
    }

    Go to the module

  221. What happens to an HTTP request in a Spring Boot REST application, from arrival to response?

    Spring Boot REST: controllers and the request lifecycle Junior Concept

    Show answer

    It passes through servlet filters to DispatcherServlet. HandlerMapping finds the controller method, interceptors run preHandle, and argument resolvers bind and validate the input. Your method runs, and an HttpMessageConverter writes the result as JSON. Interceptors and filters then finish on the way out. If the controller throws, @RestControllerAdvice maps the exception to a response.

    • Filters belong to the servlet container and wrap all of Spring MVC (Model-View-Controller).
    • Validation fails before the controller runs, as a 400.
    • An exception in a filter does not reach @RestControllerAdvice.
    • Jackson does the JSON work through a message converter.

    Go to the module

  222. What does @RestController do that @Controller does not?

    Spring Boot REST: controllers and the request lifecycle Junior Comparison

    Show answer

    @RestController is @Controller plus @ResponseBody. Every return value is written to the response body through a message converter, usually as JSON, and no view is resolved. Use ResponseEntity when you need to set the status or headers yourself, as in a 201 with a Location header.

    • A String from @Controller is a view name; from @RestController it is the body.
    • @ResponseStatus sets a fixed status on a method.
    • Return a DTO (data transfer object), not a JPA (Jakarta Persistence API) entity, to keep the API independent of the database.

    Go to the module

  223. How do you validate a request body in Spring Boot?

    Spring Boot REST: controllers and the request lifecycle Junior Code

    Show answer

    Add spring-boot-starter-validation, put Jakarta Validation constraints such as @NotBlank and @Min on the DTO, and mark the parameter @Valid. Spring validates after binding, and throws MethodArgumentNotValidException before your method runs, which becomes a 400. Handle it in @RestControllerAdvice for a clear list of field errors.

    • Without @Valid, the constraints are never checked.
    • Nested objects need @Valid on the field too.
    • @Validated on a class validates method parameters such as @PathVariable.
    record NewOrder(@NotBlank String sku, @Min(1) int quantity) {}
    
    @PostMapping
    OrderDto create(@Valid @RequestBody NewOrder body) {
        return service.place(body);
    }

    Go to the module

  224. What is @ControllerAdvice, and how do you use it for errors?

    Spring Boot REST: controllers and the request lifecycle Junior Concept

    Show answer

    It is a class of cross-cutting controller logic, most often @ExceptionHandler methods that apply to every controller. A method maps an exception type to a response, so controllers stay clean, and every error has the same shape. @RestControllerAdvice adds @ResponseBody. ProblemDetail gives a standard RFC 9457 body.

    • The most specific @ExceptionHandler wins.
    • A catch-all for Exception also catches Spring Security's access denied exception, turning a 403 into a 500.
    • @ResponseStatus on the exception class is a simpler alternative with less control.
    @RestControllerAdvice
    class ApiErrors {
        @ExceptionHandler(OrderNotFoundException.class)
        ProblemDetail notFound(OrderNotFoundException e) {
            return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }

    Go to the module

  225. Which HTTP status codes should a REST API return, and when?

    Spring Boot REST: controllers and the request lifecycle Junior Concept

    Show answer

    200 for a successful read, 201 with Location for a created resource, 204 for success with no body. 400 for invalid input, 401 when authentication is missing or invalid, 403 when the caller is known but may not do it, 404 for an unknown resource, 409 for a conflict such as a duplicate. 500 means a bug on the server, and it should never be used for client errors.

    • 401 means "who are you?", and 403 means "I know you, and no".
    • 405 and 415 are produced by Spring MVC for you.
    • Returning 200 with an error in the body breaks clients, caches and monitoring.

    Go to the module

  226. What is the difference between a filter and a HandlerInterceptor?

    Spring Boot REST: controllers and the request lifecycle Mid-level Comparison

    Show answer

    A filter belongs to the servlet container and wraps everything, including DispatcherServlet, so it can change the raw request or stop it early. An interceptor belongs to Spring MVC, runs inside DispatcherServlet, and knows which handler was chosen. Use filters for security, CORS (cross-origin resource sharing) and logging, and interceptors for logic tied to controllers.

    • Filters run even for requests no controller matches.
    • A wrong HTTP method passes the filters but never reaches preHandle, because no handler was found.
    • postHandle is skipped when the controller throws; afterCompletion is not.

    Go to the module

  227. The same property is set in several places. Which value does Spring Boot use?

    Spring Boot Configuration and profiles Junior Scenario

    Show answer

    Spring Boot layers its sources, and the highest one that sets a key wins, per key. Command-line arguments beat environment variables, which beat the active profile's file, which beats application.yml. So a container can override a packaged default with an environment variable, and the profile file only needs the keys that differ.

    • Sources merge per key, so a profile file does not replace the whole base file.
    • Test properties such as @TestPropertySource rank above all of these.
    • With both in one location, application.properties beats application.yml.
    • /actuator/env shows which source won, with values masked.

    Go to the module

  228. What is application.yml for, and where does Spring Boot look for it?

    Spring Boot Configuration and profiles Junior Concept

    Show answer

    It holds externalized configuration: settings kept out of the code, so one build runs everywhere. Spring Boot loads it from the classpath root and /config, and from the current directory and its config folder, with outside files overriding packaged ones. YAML and properties are equivalent. Secrets belong in the environment or a vault, not in the file.

    • One artifact, many environments, is a Twelve-Factor practice.
    • spring.config.import pulls in more files or a config server.
    • A --- line splits one YAML file into several documents.

    Go to the module

  229. What are Spring profiles, and what can they change?

    Spring Boot Configuration and profiles Junior Concept

    Show answer

    A profile is a named set of configuration you can switch on. Activate it with spring.profiles.active, usually from the environment. It loads application-{profile}.yml, and it turns on beans marked @Profile("dev"). It suits differences between environments, such as a fake mail sender in development. Do not branch business logic on a profile.

    • spring.profiles.active is invalid inside a profile-specific file, and startup fails.
    • spring.profiles.group activates several profiles under one name.
    • Too many profiles make it hard to know what production runs.
    @Bean
    @Profile("dev")
    MailSender fakeMail() {
        return new LoggingMailSender();
    }

    Go to the module

  230. What is the difference between @Value and @ConfigurationProperties?

    Spring Boot Configuration and profiles Junior Comparison

    Show answer

    @Value injects one property, with an optional default and SpEL. @ConfigurationProperties binds a whole prefix into a typed class or record, with relaxed binding, nesting and validation through @Validated. Use it for any group of settings, so they live in one place and fail at startup when wrong. Keep @Value for a single, simple value.

    • A missing @Value with no default fails the startup with a placeholder error.
    • @Value("${app.retry.maxAttempts}") fails if the file says max-attempts: use the kebab-case form.
    • SpEL works in @Value only.
    @ConfigurationProperties("app.retry")
    @Validated
    record RetryProperties(@Min(1) int maxAttempts, Duration delay) {}

    Go to the module

  231. What is the N+1 problem, and how do you fix it?

    Spring Boot Spring Data JPA and Hibernate Mid-level Scenario

    Show answer

    One query loads N parents, then reading a lazy association sends one more query per parent, so 1 + N statements. It stays hidden in tests with little data and hurts in production. Fix it in the query: join fetch or @EntityGraph load everything in one statement, and @BatchSize groups the extra queries. A DTO (data transfer object) projection fetches only what is needed.

    • Making the association EAGER does not fix it, and spreads the cost everywhere.
    • Detect it by logging SQL, or by asserting the statement count in a test.
    • Paginating over a collection join fetch happens in memory, and Hibernate warns about it.
    • @BatchSize needs no change to the query that loads the parents.

    Go to the module

  232. How do Spring Data repository methods work?

    Spring Boot Spring Data JPA and Hibernate Mid-level Concept

    Show answer

    You declare an interface extending JpaRepository, and Spring creates the implementation at startup. A method name such as findByEmail is parsed into a query, and a bad property name fails at startup. For anything longer, write JPQL (Jakarta Persistence Query Language) with @Query. JpaRepository already gives save, findById, findAll with paging, and more.

    • Derived queries suit one or two conditions; beyond that, names become unreadable.
    • A Pageable parameter adds paging, and Page also runs a count query.
    • findById returns an Optional; getReferenceById returns a lazy proxy.
    interface CustomerRepository extends JpaRepository<Customer, Long> {
        Optional<Customer> findByEmail(String email);
    
        @Query("select c from Customer c where c.total > :min")
        List<Customer> big(@Param("min") int min);
    }

    Go to the module

  233. What are the states of a JPA entity?

    Spring Boot Spring Data JPA and Hibernate Mid-level Concept

    Show answer

    Transient: a new object Hibernate does not know. Managed: tracked by the persistence context, so changes are written at flush. Detached: has an id, but the context was closed, so changes are ignored. Removed: scheduled for deletion at flush. persist makes an object managed, merge copies a detached one into a managed copy, and remove schedules the delete.

    • Dirty checking writes a managed entity's changes with no save call.
    • The first-level cache returns the same object for one id within a transaction.
    • In a Spring transaction, the context lives as long as the transaction.

    Go to the module

  234. What is the difference between lazy and eager loading, and which should you use?

    Spring Boot Spring Data JPA and Hibernate Mid-level Comparison

    Show answer

    Lazy loads an association the first time it is read, through a proxy or a placeholder collection. Eager loads it with the parent, every time. Use lazy for all associations and fetch what each use case needs in its query. @OneToMany is lazy by default, while @ManyToOne and @OneToOne are eager, so set them to lazy.

    • EAGER cannot be turned off per query, while lazy can be fetched per query.
    • Reading a lazy association with no open session throws LazyInitializationException.
    • Boot's spring.jpa.open-in-view keeps a session open for the web request, and is often turned off.

    Go to the module

  235. Do you need to call save() after changing an entity inside a transaction?

    Spring Boot Spring Data JPA and Hibernate Mid-level Scenario

    Show answer

    No. The entity is managed, so at commit Hibernate compares it with its snapshot and sends an UPDATE. A redundant save does no harm. You need it for a new object, which it persists, or for a detached one, which it merges. Then you must use the return value, because merge returns a different object.

    • For an entity that is not new, save calls merge, and returns a managed copy.
    • For a new entity, save calls persist, and returns the same object.
    • Dirty checking only works inside the transaction that loaded the entity.
    Customer saved = customers.save(detached);
    saved.setName("new");       // tracked
    detached.setName("lost");   // not tracked

    Go to the module

  236. What causes LazyInitializationException, and how do you fix it?

    Spring Boot Spring Data JPA and Hibernate Mid-level Scenario

    Show answer

    A lazy association was read after the persistence context closed, usually outside the transaction, for example while mapping an entity to JSON in the controller. Fix it by loading what you need while the transaction is open: use join fetch, @EntityGraph, or a DTO built in the service. Do not reach for EAGER.

    • Return DTOs from the service, so nothing lazy reaches the web layer.
    • Open-in-view hides the error, at the price of queries during serialization.
    • hibernate.enable_lazy_load_no_trans also hides it, and it is an anti-pattern.

    Go to the module

  237. Why does a @Transactional method called from the same class not start a transaction?

    Spring Boot Transactions with @Transactional Mid-level Scenario

    Show answer

    @Transactional works through a proxy around the bean: callers hold the proxy, which begins and commits around the real method. A self-call is this.save(), which stays inside the object and never crosses the proxy, so no transaction starts, and nothing warns you. Move the method to another bean, so the call goes through a proxy.

    • It applies to any proxy-based feature, such as @Async and @Cacheable.
    • Injecting the bean into itself with @Lazy works, but hides a design problem.
    • TransactionTemplate gives a transaction with no proxy involved.
    • AspectJ weaving removes the limit, at the cost of a build or load-time step.

    Go to the module

  238. What are transaction propagation and isolation?

    Spring Boot Transactions with @Transactional Mid-level Concept

    Show answer

    Propagation says what a method does when a transaction may already exist. REQUIRED, the default, joins it or starts one, and REQUIRES_NEW suspends it and runs its own. Isolation says what a transaction can see of others: READ_COMMITTED prevents dirty reads, REPEATABLE_READ also non-repeatable reads, and SERIALIZABLE phantoms too. The database enforces isolation.

    • The default isolation is the database's own, often READ_COMMITTED.
    • NESTED uses a savepoint, and JpaTransactionManager rejects it by default.
    • REQUIRES_NEW holds a second connection, and can exhaust the pool under load.
    • Stronger isolation costs throughput, through locks or retries.

    Go to the module

  239. Which exceptions roll a transaction back?

    Spring Boot Transactions with @Transactional Mid-level Concept

    Show answer

    By default, RuntimeException and Error roll back, and a checked exception commits. Change that with rollbackFor and noRollbackFor. A catch inside the method means the proxy sees no exception, so it commits. To roll back after catching, rethrow or call setRollbackOnly().

    • A checked exception committing is the classic surprise.
    • The rule comes from EJB (Enterprise JavaBeans), where checked meant a recoverable business outcome.
    • Catching an exception hides it from the proxy.
    @Transactional(rollbackFor = Exception.class)
    public void pay(Order order) throws PaymentDeclinedException {
        orders.save(order);
        gateway.charge(order);    // a checked exception now rolls back
    }

    Go to the module

  240. An inner @Transactional method throws, the outer method catches it, and you still get UnexpectedRollbackException. Why?

    Spring Boot Transactions with @Transactional Mid-level Scenario

    Show answer

    With REQUIRED, inner and outer share one transaction. When the exception crosses the inner proxy, it marks that transaction rollback-only. The outer method catches the exception and returns normally, so the proxy tries to commit, finds the mark, rolls back, and throws. Use REQUIRES_NEW or NESTED if the inner failure really is optional.

    • The mark is set at the proxy boundary, so catching it later is too late.
    • Calling a private helper does not set a mark, because no proxy is crossed.
    • Both rows are gone, and the exception reaches the caller.

    Go to the module

  241. When would you use REQUIRES_NEW, and what can go wrong?

    Spring Boot Transactions with @Transactional Mid-level Design

    Show answer

    Use it for work that must survive the caller's rollback, such as an audit record: its row stays even when the outer method throws. It suspends the outer transaction and takes a second connection, so the outer's connection sits idle, and a pool can deadlock under load. The inner cannot see the outer's uncommitted rows, and can block on its locks.

    • A small pool plus REQUIRES_NEW per request can exhaust connections.
    • An outbox or an event after commit is often a better design.
    • @TransactionalEventListener runs work after the commit succeeds.

    Go to the module

  242. Where should @Transactional go, and how long should a transaction last?

    Spring Boot Transactions with @Transactional Mid-level Design

    Show answer

    Put it on the service method that defines one unit of business work, not on controllers or on each repository call. Keep it short: a transaction holds a database connection and locks, so a slow HTTP call inside one can exhaust the pool. Do remote calls before or after it. Mark read-only work with readOnly = true.

    • readOnly = true lets Hibernate skip dirty checking, and can route reads to a replica.
    • A remote call cannot be rolled back with the database.
    • timeout limits how long a transaction may run.

    Go to the module

  243. What is the difference between authentication and authorization, and how does Spring Security apply them?

    Spring Boot Spring Security Mid-level Comparison

    Show answer

    Authentication proves who you are, and authorization decides what you may do. Spring Security runs both in servlet filters, before any controller. A filter turns credentials into an Authentication in the SecurityContext, then AuthorizationFilter checks the rule for the URL. Missing or bad credentials give 401, and a known caller without permission gets 403.

    • Authentication always comes first; authorization needs to know who is asking.
    • SecurityContextHolder holds the current user for the thread.
    • Method rules such as @PreAuthorize add a second check on individual methods.
    • An authority is a plain string, such as SCOPE_read or ROLE_ADMIN.

    Go to the module

  244. What is the security filter chain, and how does a request go through it?

    Spring Boot Spring Security Mid-level Concept

    Show answer

    DelegatingFilterProxy connects the servlet container to the FilterChainProxy bean, which picks the first SecurityFilterChain matching the request and runs its filters in a fixed order. Authentication filters such as BearerTokenAuthenticationFilter come first, and ExceptionTranslationFilter and AuthorizationFilter come last. You declare chains as beans.

    • All of this runs before DispatcherServlet.
    • ExceptionTranslationFilter turns security exceptions into 401 or 403.
    • Several chains with securityMatcher can serve an API and a web UI.
    • Set the logging.level.org.springframework.security to TRACE to see each filter run.

    Go to the module

  245. What is a JWT, and what are its pros and cons?

    Spring Boot Spring Security Mid-level Concept

    Show answer

    A signed token with three Base64URL parts: a header, a payload of claims, and a signature. Any service holding the public key can verify it with no database call, which suits microservices. The cost: it is readable by anyone, and hard to revoke before it expires. So keep it short-lived, put no secrets in it, and use refresh tokens.

    • Signed is not encrypted; Base64URL is only an encoding.
    • Prefer an asymmetric algorithm, so services cannot mint tokens.
    • Reject alg: none, as Spring's decoder does.
    • Revoking one needs a deny list or short lifetimes.

    Go to the module

  246. What does it mean for a Spring Boot API to be an OAuth2 resource server?

    Spring Boot Spring Security Mid-level Concept

    Show answer

    The API does not log anyone in. It accepts access tokens issued by an authorization server, such as Keycloak or Okta, and validates them. Set spring.security.oauth2.resourceserver.jwt.issuer-uri, and Boot discovers the public keys, then checks each token's signature, expiry and issuer. Scopes become SCOPE_ authorities for your rules.

    • Login, passwords and tokens stay in the authorization server.
    • Keys are fetched from the JWK (JSON Web Key) set and cached, so verifying is local.
    • An opaque token is checked by introspection, a call per request.
    spring:
      security:
        oauth2:
          resourceserver:
            jwt:
              issuer-uri: https://auth.example/realms/shop

    Go to the module

  247. A @PreAuthorize denial returns 500 instead of 403. What is the likely cause?

    Spring Boot Spring Security Mid-level Scenario

    Show answer

    A catch-all @ExceptionHandler(Exception.class) in @RestControllerAdvice. A method rule fails inside the controller's proxy, so the access denied exception reaches the handlers of Spring MVC (Model-View-Controller) before it can reach ExceptionTranslationFilter. The advice catches it and returns 500. Add a handler that rethrows AccessDeniedException, or narrow the catch-all.

    • URL rules in the filter chain are not affected, since they run before Spring MVC.
    • With that advice, one token gets 403 from a URL rule and 500 from a method rule.
    • AuthorizationDeniedException extends AccessDeniedException in current versions.
    @ExceptionHandler(AccessDeniedException.class)
    void denied(AccessDeniedException e) {
        throw e;    // let the security filters answer 403
    }

    Go to the module

  248. Why do many REST (Representational State Transfer) APIs disable CSRF (cross-site request forgery) protection, and when is that wrong?

    Spring Boot Spring Security Mid-level Design

    Show answer

    CSRF abuses the cookies a browser attaches to a request by itself. An API that takes a bearer token in the Authorization header has no such cookie, because a forged request cannot add the header, so CSRF protection can go. If the API uses session cookies, including a browser app that stores its token in one, keep it on.

    • The risk follows how credentials are sent, not the words "REST API".
    • Pair csrf.disable() with STATELESS session management.
    • CORS (cross-origin resource sharing) is a different thing, and it does not stop CSRF.

    Go to the module

  249. What does Spring Boot Actuator give you for health, metrics and readiness?

    Spring Boot Actuator and observability Mid-level Concept

    Show answer

    Production endpoints under /actuator. /health reports UP or DOWN for load balancers. Its liveness and readiness groups tell Kubernetes when to restart a pod and when to send it traffic. /metrics and /prometheus expose Micrometer metrics, such as request timings and JVM (Java Virtual Machine) memory. Only health is exposed over HTTP by default, because the others can leak information.

    • Add more with management.endpoints.web.exposure.include.
    • Failing health returns 503, which is what infrastructure reacts to.
    • The starter is spring-boot-starter-actuator.
    • Put management endpoints on a separate port to keep them private.

    Go to the module

  250. What is Micrometer, and how do you add a custom metric?

    Spring Boot Actuator and observability Mid-level Concept

    Show answer

    Micrometer is a facade for metrics, as SLF4J (Simple Logging Facade for Java) is for logs. You record through a MeterRegistry, and the dependency you add decides the backend: Prometheus, Datadog and others. Boot auto-configures the registry and records HTTP timings as http.server.requests. Inject MeterRegistry to create a Counter for how many, a Timer for how long, or a Gauge for a current value.

    • Tags add dimensions, such as status or uri.
    • Avoid tags with unbounded values, such as a user id, because each value makes a new time series.
    • Prometheus names use underscores and a suffix, such as orders_placed_total.
    Counter placed = Counter.builder("orders.placed")
            .tag("channel", "web")
            .register(registry);
    placed.increment();

    Go to the module

  251. What is the difference between the liveness and readiness probes?

    Spring Boot Actuator and observability Mid-level Comparison

    Show answer

    Liveness asks whether the process is healthy; on failure, Kubernetes restarts the pod. Readiness asks whether it can take traffic now; on failure, Kubernetes stops routing to it, with no restart. An application can refuse traffic while warming up or during shutdown, while staying alive: readiness answers 503 while liveness stays 200.

    • Publish AvailabilityChangeEvent to change the state from code.
    • Boot 4.1 exposes both by default; Boot 3.5 needs Kubernetes or management.endpoint.health.probes.enabled.
    • A startup probe gives a slow application time before liveness starts counting.

    Go to the module

  252. How do you expose Actuator safely in production?

    Spring Boot Actuator and observability Mid-level Design

    Show answer

    Expose only what is needed, with an explicit include list. Put management on a separate port with management.server.port, so it is not reachable through the public ingress, and require an admin role for anything beyond health. /env, /heapdump and /loggers are sensitive: a heap dump can contain passwords and tokens from memory, and /loggers changes behavior.

    • Values in /env are masked by default, since Boot 3.
    • Never use include=* on a public port.
    • Network rules and authentication add up; rely on both.

    Go to the module

  253. What are an aspect, advice and a pointcut in Spring AOP?

    Spring Boot Spring AOP and proxies Senior Concept

    Show answer

    An aspect is a class holding a cross-cutting concern, such as logging or timing. A pointcut is an expression selecting methods. Advice is the code that runs there: @Before, @AfterReturning, @AfterThrowing, @After or @Around. A join point is one matched method call. Spring applies all this through a proxy at run time, and it is how @Transactional works.

    • Spring AOP only intercepts method calls on beans, from outside.
    • @Around must call proceed(), or the method never runs.
    • Use the weakest advice that does the job, such as @Before over @Around.
    • Lowest @Order is the outermost aspect.

    Go to the module

  254. What is the difference between a JDK (Java Development Kit) dynamic proxy and a CGLIB (Code Generation Library) proxy?

    Spring Boot Spring AOP and proxies Senior Comparison

    Show answer

    A JDK proxy implements the target's interfaces, so it is not an instance of the class. A CGLIB proxy is a generated subclass, so it needs a non-final class and overridable methods. Spring Framework alone prefers JDK proxies when an interface exists, while Spring Boot sets spring.aop.proxy-target-class=true, so CGLIB is the default. That is why injecting a concrete class works in Boot.

    • With a JDK proxy, injecting by class fails with BeanNotOfRequiredTypeException.
    • A class with no interface always gets CGLIB.
    • Objenesis creates the subclass, so your constructor is not called twice.

    Go to the module

  255. What are the limits of proxy-based AOP?

    Spring Boot Spring AOP and proxies Senior Scenario

    Show answer

    Only calls that go through the proxy are advised. A self-call on this skips it. Private and static methods cannot be overridden, so they are not advised. A final method runs on the proxy object itself, whose fields are null, with no error at startup. A final class fails at startup. Objects you create with new have no proxy at all.

    • Kotlin classes are final by default, and the kotlin-spring plugin opens them.
    • Advice applies to beans only, not to any Java object.
    • AspectJ weaving removes these limits, with more tooling.
    @Service
    public class PayService {
        private final Audit audit = new Audit();
    
        @Timed
        public final void pay() {
            audit.log();    // NullPointerException through the proxy
        }
    }

    Go to the module

  256. A final class matches a pointcut. What happens when the application starts?

    Spring Boot Spring AOP and proxies Senior Scenario

    Show answer

    Startup fails: CGLIB cannot subclass it, with "Cannot subclass final class". This failure is loud, unlike a final method, which is silently not advised. Remove final, or extract an interface and force JDK proxies. Records are final too, so they cannot be proxied this way, and they make poor beans for advice.

    • The error comes from AopConfigException, at bean creation.
    • A broad pointcut can catch a class you did not intend, so keep pointcuts narrow.
    • JDK proxies do not need the class to be open, only an interface.

    Go to the module

  257. What is the difference between the thread-per-request model and an event loop?

    Reactive Programming Why reactive: blocking vs non-blocking Mid-level Comparison

    Show answer

    In thread-per-request, each request holds one thread until it finishes, parked through every I/O wait. In an event loop, a few threads, one per core by default, run short callbacks. A waiting request holds no thread, and a callback continues it when data arrives. So an event loop handles many slow requests with few threads, but one blocking call stalls every request on it.

    • Tomcat's default pool is 200 threads; Reactor Netty's loop has one per core, at least 4.
    • Threads needed in thread-per-request are the request rate times the latency.
    • The gain is in waiting, and neither model makes the I/O itself any faster.
    • Thread-per-request is simpler to write, read and debug.

    Go to the module

  258. When does reactive programming pay off, and when does it not?

    Reactive Programming Why reactive: blocking vs non-blocking Mid-level Scenario

    Show answer

    It pays off when many concurrent requests mostly wait on I/O, as in gateways and services fanning out to slow APIs, and when you stream data and need backpressure. It does not pay off for CPU-heavy work, for simple CRUD (create, read, update, delete) at modest load, or when your drivers block, because a blocking call on the loop stalls everything.

    • Run the numbers first, as 500 requests per second at 10 ms is only 5 busy threads.
    • The whole path must be non-blocking, including the database driver.
    • Costs include harder debugging, stack traces and onboarding.
    • Consider virtual threads when you only need cheap waiting.

    Go to the module

  259. What does the Reactive Manifesto say?

    Reactive Programming Why reactive: blocking vs non-blocking Mid-level Concept

    Show answer

    It describes what reactive systems are: responsive, resilient, elastic and message-driven. Responsive is the goal, meaning timely answers. Resilient means staying responsive during failure, elastic means staying responsive under varying load, and message-driven communication is how both are achieved. It describes system architecture, not a library, so it is broader than Reactor or Reactive Streams.

    • Reactive systems are an architecture; reactive programming is a code technique.
    • Reactive Streams is a separate specification, about async streams with backpressure.
    • A Reactor app with one fragile database is not a reactive system.

    Go to the module

  260. A service gets 1,000 requests per second, and each waits 500 ms on a downstream call. How many threads does thread-per-request need?

    Reactive Programming Why reactive: blocking vs non-blocking Senior Scenario

    Show answer

    About 500, by Little's law: requests in flight equal the arrival rate times the time in the system, so 1,000 times 0.5. With Tomcat's default 200 threads, the pool finishes only 400 per second, and the queue grows until requests time out. You can raise the pool, use virtual threads, or use non-blocking I/O.

    • Capacity of a full pool: threads divided by latency.
    • A latency spike can saturate a pool with no extra traffic.
    • Limit the downstream with a timeout, or its slowness becomes yours.

    Go to the module

  261. What are the downsides of reactive code?

    Reactive Programming Why reactive: blocking vs non-blocking Mid-level Concept

    Show answer

    It is harder to write, read and debug. Stack traces show operators and not your call path, so a failure can be hard to trace. ThreadLocal-based tools, such as MDC (Mapped Diagnostic Context) and security contexts, need extra care. The whole path must be non-blocking, or the benefit is lost, and a forgotten subscribe silently does nothing. Teams also need time to learn it.

    • Hooks.onOperatorDebug and checkpoint() improve stack traces, at a cost.
    • One blocking library call can undo the whole design.
    • Errors move from try/catch to operators.

    Go to the module

  262. Is reactive programming the same as asynchronous programming?

    Reactive Programming Why reactive: blocking vs non-blocking Mid-level Comparison

    Show answer

    No. Asynchronous means a caller does not wait for a result, as with a CompletableFuture. Reactive adds a model of streams: many values over time, composed with operators, with demand signalled upstream through backpressure. A Mono is close to a lazy future; a Flux has no future equivalent. A stream can even be synchronous, as Flux.range is with no scheduler.

    • Backpressure is what a future does not have.
    • A future is eager, and a Mono is lazy.
    • Reactor is concurrency-agnostic, so it does not create threads unless asked to.

    Go to the module

  263. What is backpressure, and how is it signalled in Reactive Streams?

    Reactive Programming Reactive Streams and backpressure Mid-level Concept

    Show answer

    Backpressure lets a slow consumer control how fast it receives data. In Reactive Streams, the signal is explicit: the Subscriber calls request(n) on its Subscription, and the Publisher may send at most n elements through onNext. Demand flows up and data flows down. A plain subscribe() requests everything, so a slow consumer must opt in to limits.

    • Demand is a number the Subscriber sends, and it adds up across calls.
    • A Publisher never sends more than was requested.
    • A source that cannot wait, such as a timer, needs a strategy instead.
    • onComplete and onError need no demand.

    Go to the module

  264. What are Publisher, Subscriber and Subscription in Reactive Streams?

    Reactive Programming Reactive Streams and backpressure Mid-level Concept

    Show answer

    A Publisher produces elements and has one method, subscribe. A Subscriber receives onSubscribe, onNext, onComplete and onError. A Subscription links one Subscriber to one Publisher, with request(n) and cancel(). A Processor is both a Subscriber and a Publisher. The specification defines only these, and libraries such as Reactor implement them.

    • The order is onSubscribe, then any number of onNext, then at most one terminal signal.
    • Java 9 copied these interfaces as java.util.concurrent.Flow.
    • You rarely implement them, because Flux and Mono already do.

    Go to the module

  265. A Kafka listener or timer pushes data faster than you can process it. What are your options?

    Reactive Programming Reactive Streams and backpressure Mid-level Scenario

    Show answer

    It cannot obey request(n), so choose what to lose. onBackpressureBuffer holds elements, at a memory cost. onBackpressureDrop loses the excess but keeps running. onBackpressureLatest keeps only the newest, which suits prices or sensor readings. onBackpressureError fails fast. Also try consuming faster, or batching with buffer. With no strategy, Flux.interval fails by itself.

    • Drop suits metrics; latest suits current state; error suits data you cannot lose.
    • An unbounded buffer only delays the failure until memory runs out.
    • Flux.interval throws OverflowException when demand runs out.

    Go to the module

  266. With onBackpressureBuffer(100), a source at 100 per second and a consumer at 20, when does the subscriber see the error?

    Reactive Programming Reactive Streams and backpressure Senior Scenario

    Show answer

    Later than you would expect. The buffer fills after about 1.25 seconds, because it gains 80 per second, and the source is cancelled then. The subscriber still drains what was buffered, so OverflowException reaches it after about 6 seconds. Between those moments, the stream looks healthy while no new data enters.

    • Overflow time is capacity divided by the gap in rates.
    • The error waits behind the elements already buffered.
    • Pass an overflow strategy, such as BufferOverflowStrategy.DROP_OLDEST, to keep the stream alive.

    Go to the module

  267. What does limitRate do?

    Reactive Programming Reactive Streams and backpressure Mid-level Code

    Show answer

    It splits a large demand into small batches. limitRate(10) requests 10 from upstream, then 8 each time three quarters of the batch is consumed, even when downstream asked for everything. This keeps a source such as a database cursor from fetching a huge amount at once. It shapes demand, not time, so it is not a rate limiter per second.

    • It replenishes at 75 percent by default, which is why the next request is 8.
    • For a limit per second, delay elements or use a dedicated rate limiter.
    Flux.range(1, 30)
        .doOnRequest(n -> System.out.println("request " + n))
        .limitRate(10)
        .subscribe();    // request 10, 8, 8, 8

    Go to the module

  268. How does a consumer stop a stream early, and what happens upstream?

    Reactive Programming Reactive Streams and backpressure Mid-level Concept

    Show answer

    It calls cancel() on the Subscription, and the signal travels upstream through every operator, so a source can release its connection or stop its work. Operators such as take(n) do this for you once they have n elements. Elements already in flight may still arrive, so a Subscriber must tolerate a few.

    • Cancel is what frees a database cursor when a client disconnects.
    • doOnCancel runs when it happens; doFinally runs on any kind of ending.
    • A stream can end without onComplete, so cleanup belongs in doFinally.

    Go to the module

  269. What is the difference between Mono and Flux?

    Reactive Programming Mono and Flux Mid-level Comparison

    Show answer

    Both are Reactor's Publishers. A Mono delivers at most one element, then completes or fails; a Flux delivers zero to N, possibly without end. The type states the contract: Mono<Order> is one result or none, and Flux<Order> is a sequence. They are lazy, so nothing runs until something subscribes.

    • Empty is a normal completion for both, not an error.
    • Mono<Void> means only success or failure, with no value.
    • collectList() turns a Flux into a Mono, and flux() does the reverse.
    • Use Mono for one result and Flux for many, so the signature tells callers what to expect.

    Go to the module

  270. Why does nothing happen until you subscribe?

    Reactive Programming Mono and Flux Mid-level Concept

    Show answer

    A chain is a description of work, not the work. Each operator wraps the previous one at assembly time. Subscribing sends a signal up to the source, and only then do elements flow down. This laziness lets you build a chain once, run it many times, retry it from the start and stop it, because no work has begun.

    • Assembly builds the chain, subscription starts it, and run time moves the data.
    • A retry works because it can subscribe again.
    • Forgetting to return or subscribe a chain silently does nothing.
    repository.save(order);    // nothing is saved
    
    return repository.save(order);    // the framework subscribes

    Go to the module

  271. What is the difference between cold and hot publishers?

    Reactive Programming Mono and Flux Mid-level Comparison

    Show answer

    A cold publisher starts a new run for each subscriber, so everyone gets everything from the start; most are cold, such as an HTTP call or a database query. A hot publisher runs regardless of its subscribers, so a late one only gets what comes next, as with a Sinks stream or live events. share() makes a cold one hot.

    • Two subscribers to a cold HTTP Mono make two HTTP calls.
    • share() runs the source once for everyone while someone is subscribed.
    • cache() also replays stored values to late subscribers.

    Go to the module

  272. What is the difference between Mono.just(call()) and Mono.fromCallable(this::call)?

    Reactive Programming Mono and Flux Mid-level Code

    Show answer

    Mono.just(call()) runs call() immediately, on the current thread and during assembly, because Java evaluates arguments first. It is not lazy, it runs even if nobody subscribes, and a retry reuses the same value. Mono.fromCallable runs it at subscription, once per subscriber. So wrap a blocking or failing call in fromCallable, or use defer.

    • With Mono.just(call()).retry(2), call ran once.
    • With Mono.fromCallable(...).retry(2), a failing call ran three times.
    • Mono.just also rejects null, with a NullPointerException.
    • Mono.defer is the same idea when the supplier already returns a Mono.

    Go to the module

  273. Can a Mono hold null? How do you model "not found"?

    Reactive Programming Mono and Flux Mid-level Concept

    Show answer

    No. Reactive Streams forbids null elements, so Mono.just(null) throws a NullPointerException, and a map returning null fails the stream. Model "not found" as an empty Mono, and use justOrEmpty to convert a nullable value. Handle it with switchIfEmpty or defaultIfEmpty, because operators such as map are simply skipped on empty.

    • An empty Mono completes with no value, so map never runs.
    • switchIfEmpty(Mono.error(...)) turns not found into a failure, such as a 404.
    • block() on an empty Mono returns null, which is a common surprise.

    Go to the module

  274. When should you call subscribe() yourself?

    Reactive Programming Mono and Flux Senior Scenario

    Show answer

    Rarely, and almost never inside a chain or a controller. At the edge of the application, the framework subscribes, or a test does. Call it yourself only at a true entry point, such as a scheduled task or a startup listener, and always pass an error handler. Without one, the error is only logged through onErrorDropped.

    • Nested subscribe() breaks backpressure, cancellation and the Reactor Context.
    • Compose with flatMap or then instead of subscribing inside a callback.
    • A subscribe with no error consumer does not throw to the caller.

    Go to the module

  275. What is the difference between map and flatMap in Reactor?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Mid-level Comparison

    Show answer

    map applies a synchronous function, turning each element into one value on the spot. flatMap takes a function returning a Publisher, subscribes to it and flattens its results into the stream. Use map for a calculation and flatMap for anything asynchronous, such as a database or HTTP call. On a Flux, flatMap runs inner calls concurrently, so order can change.

    • map with a function returning a Mono gives Mono<Mono<T>>, and the inner one never runs.
    • flatMap subscribes for you, so the inner call really happens.
    • An inner Mono that completes empty adds nothing to the output.
    • A map function must not return null.

    Go to the module

  276. What is the difference between flatMap and concatMap in ordering?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Mid-level Comparison

    Show answer

    flatMap subscribes to inner publishers eagerly, up to 256 at once by default, and emits results as they finish, so order follows speed. concatMap subscribes to one at a time, waiting for each to complete, so order is preserved but the times add up. With calls of 300, 100 and 200 ms, flatMap takes 300 ms and concatMap takes 600.

    • flatMap(fn, 1) behaves like concatMap.
    • flatMapSequential runs concurrently and restores the order, at the cost of a buffer.
    • Use concatMap when order matters, as with updates to the same account.

    Go to the module

  277. What do zip and merge do?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Mid-level Comparison

    Show answer

    zip waits for one element from each source and combines them, so it pairs by position and ends when the shortest source ends. merge subscribes to all sources at once and interleaves elements as they arrive, without combining them. Use Mono.zip to call two services in parallel and join the answers. concat differs from both: it runs sources one after another.

    • If any source of zip completes empty, the zip completes with no result.
    • Mono.zip fails as soon as one source fails, and cancels the others.
    • merge needs sources of the same type.

    Go to the module

  278. When would you use switchMap?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Mid-level Scenario

    Show answer

    When only the newest element matters, such as search-as-you-type. Each new element cancels the inner call still running and starts a new one, so a slow answer to an old query can never overwrite a newer one. Do not use it for writes, because cancelling can lose work: use concatMap there.

    • In-flight calls are cancelled, so their results never arrive.
    • It saves work, as the server may stop processing a cancelled call.
    • A slow inner call with a fast source may never emit at all.

    Go to the module

  279. You use flatMap to call a service for each of 10,000 elements. What could go wrong, and how do you limit it?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Senior Scenario

    Show answer

    By default it runs 256 inner calls at once, which can overload the service or exhaust a connection pool. Pass a concurrency argument, as in flatMap(fn, 16), which keeps only 16 in flight and requests more as they finish. This is backpressure at work: the limit reaches the source, because flatMap only requests what it can run.

    • The default of 256 is Queues.SMALL_BUFFER_SIZE, and a measured peak was exactly 256.
    • Size the limit to the service's capacity and the connection pool.
    • flatMap(fn, 1) is sequential.

    Go to the module

  280. Why can Flux.interval(...).concatMap(slowCall) fail with an OverflowException?

    Reactive Programming Operators: map, flatMap, concatMap, switchMap Senior Scenario

    Show answer

    A timer cannot wait. concatMap requests only what it can handle, so while one slow call runs, demand reaches zero, and the next tick has nowhere to go. Flux.interval then fails with OverflowException instead of silently losing a tick. Choose what to do: onBackpressureDrop skips ticks, and onBackpressureBuffer queues them.

    • It only fails when a call outlasts the tick, so it can pass in tests and fail under load.
    • flatMap hides this longer, because it runs up to 256 at once.

    Go to the module

  281. What is the difference between onErrorResume and onErrorReturn?

    Reactive Programming Error handling and retries Mid-level Comparison

    Show answer

    Both catch an error signal and continue with a normal completion. onErrorReturn replaces the failure with one fixed value, chosen when the chain is assembled. onErrorResume takes a function that receives the error and returns a new Publisher, so it can branch on the exception and call a cache or another service. In both, the original stream is over: the elements it had left are lost.

    • An error is terminal, so upstream is cancelled when it occurs.
    • onErrorMap changes the exception, and doOnError only observes it.
    • To keep a Flux going, handle the error inside flatMap or concatMap.
    • Both accept a type or predicate, so you can catch only some errors.

    Go to the module

  282. How do you retry with backoff in Reactor?

    Reactive Programming Error handling and retries Mid-level Code

    Show answer

    Use retryWhen(Retry.backoff(3, Duration.ofMillis(100))). It subscribes again up to 3 times, doubling the wait to 100, 200 and 400 ms, with 50 percent jitter by default so clients do not retry in step. When it gives up, it fails with RetryExhaustedException, with the last error as its cause. Add filter so you only retry errors that can succeed.

    • By default it retries every error, including a 400, so add a filter.
    • maxBackoff caps the wait, and it has no cap by default.
    • Only retry idempotent operations, because the first attempt may have worked.
    • A retried Flux starts again, so its subscriber receives earlier elements twice.
    • onRetryExhaustedThrow rethrows the original error instead.
    Retry.backoff(3, Duration.ofMillis(100))
         .maxBackoff(Duration.ofSeconds(2))
         .filter(e -> e instanceof TimeoutException)
         .onRetryExhaustedThrow((spec, signal) -> signal.failure());

    Go to the module

  283. How do timeouts work, and does their position relative to a retry matter?

    Reactive Programming Error handling and retries Mid-level Scenario

    Show answer

    timeout(d) fails with TimeoutException if no element or terminal signal arrives within d, and it cancels upstream. Position matters. timeout(100).retry(2) limits each attempt, so a stuck call gets 3 tries and fails at 300 ms. retry(2).timeout(100) limits the whole thing, so it fails at 100 ms after one attempt. Usually you want both limits.

    • timeout(d, fallback) switches to a fallback instead of failing.
    • On a Flux, the limit applies to each gap between elements, not the total.
    • Cancelling stops waiting, and the remote side may still finish its work.

    Go to the module

  284. Mono.just(call()).retry(2) does not call the service again when it fails. Why not?

    Reactive Programming Error handling and retries Senior Code

    Show answer

    Because Java ran call() once, while assembling the chain, and retry only subscribes again. If call() throws, the exception escapes before any Mono exists. If it returns, the value is fixed. Wrap it in Mono.fromCallable(() -> call()) or Mono.defer, so each subscription runs it again; a failing call then ran three times.

    • A retry re-subscribes, so it needs a source that does its work on subscribe.
    • WebClient is already lazy, so each retry sends a new request.

    Go to the module

  285. What is the difference between publishOn and subscribeOn?

    Reactive Programming Schedulers and threads Senior Comparison

    Show answer

    subscribeOn sets the thread on which the subscription travels up and the source starts, so it affects the whole chain, wherever you write it. publishOn switches thread for the elements travelling down, so it only affects the operators after it. Without either, everything runs on the thread that subscribed. Reactor is concurrency-agnostic: it does not create threads unless asked to.

    • With two subscribeOn calls, the one closest to the source wins.
    • Each publishOn switches again, so a chain can hop threads.
    • Some operators switch by themselves; Mono.delay continues on parallel.
    • Use subscribeOn to move a blocking source, and publishOn to move later steps.

    Go to the module

  286. What is boundedElastic, and how does it differ from parallel?

    Reactive Programming Schedulers and threads Senior Comparison

    Show answer

    boundedElastic is for blocking work. It grows up to 10 threads per core, removes idle ones, and queues tasks when full, at most 100,000 per thread. parallel is for fast CPU work, with one thread per core, and it rejects blocking: block() throws there. So wrap JDBC (Java Database Connectivity) or legacy calls in fromCallable plus subscribeOn(boundedElastic).

    • On a 32-core machine, the bound was 320 threads and the queue limit 100,000.
    • It keeps blocking calls off event loop threads, which is its whole purpose.
    • It only moves the blocking, so its threads are still a bounded resource.
    • On Java 21, reactor.schedulers.defaultBoundedElasticOnVirtualThreads runs it on virtual threads.

    Go to the module

  287. What happens if you block in a reactive chain?

    Reactive Programming Schedulers and threads Senior Scenario

    Show answer

    It depends on the thread. On an event loop, a blocking call freezes that thread, so every request sharing it waits: with one loop thread, a 500 ms sleep delayed the next request to about 1,000 ms. Nothing warns you. Only Reactor's own block() is detected, throwing IllegalStateException on non-blocking threads. Under load, throughput collapses.

    • Thread.sleep and JDBC raise no error; they just stall the loop.
    • BlockHound detects blocking calls on non-blocking threads, in tests.
    • Fix it with fromCallable and subscribeOn(boundedElastic).
    • Event loop threads are few, one per core by default.

    Go to the module

  288. Why does ThreadLocal not work in a reactive chain, and what replaces it?

    Reactive Programming Schedulers and threads Senior Scenario

    Show answer

    One request hops across threads, and one thread serves many requests, so a value set in a ThreadLocal stays behind: after publishOn, reading it gave null. Reactor's Context replaces it. It is an immutable map attached to the subscription: write with contextWrite and read with deferContextual. It propagates from the subscriber upward, so the write goes below the read.

    • This is why SecurityContextHolder and MDC (Mapped Diagnostic Context) need special care in WebFlux.
    • A contextWrite above the reader is invisible to it.
    • A nested subscribe() loses the Context.
    • Micrometer's context propagation can restore ThreadLocals automatically.

    Go to the module

  289. When would you choose WebFlux over Spring MVC?

    Reactive Programming WebFlux vs Spring MVC Mid-level Scenario

    Show answer

    Choose WebFlux for streaming with backpressure, or for very many connections mostly waiting on I/O, as long as the whole path is non-blocking. Otherwise start with MVC: it is simpler, it debugs better, and JDBC (Java Database Connectivity) and JPA (Jakarta Persistence API) just work. Since Java 21, virtual threads solve cheap waiting for MVC too, which leaves streaming as WebFlux's clearest advantage.

    • In a test with 1,000 requests per second and a 500 ms downstream, MVC's median was 2 s.
    • WebFlux and MVC with virtual threads both stayed near 500 ms.
    • A blocking driver undoes WebFlux, unless moved to boundedElastic.
    • WebFlux is not faster per request; it uses fewer threads while waiting.

    Go to the module

  290. What is the difference between WebClient, RestTemplate and RestClient?

    Reactive Programming WebFlux vs Spring MVC Mid-level Comparison

    Show answer

    RestTemplate is the original blocking client with a template API, now in maintenance mode. RestClient, from Spring Framework 6.1, is its blocking replacement with a fluent API, and the natural choice for MVC. WebClient is the non-blocking client returning Mono and Flux, required in WebFlux, and also useful in MVC for parallel calls or streaming.

    • In WebFlux, never use RestTemplate or RestClient on the event loop.
    • RestClient on virtual threads gives cheap waiting with plain code.
    • Mono.zip with WebClient makes parallel calls easy.

    Go to the module

  291. What is R2DBC (Reactive Relational Database Connectivity), and why not use JPA with WebFlux?

    Reactive Programming WebFlux vs Spring MVC Mid-level Concept

    Show answer

    R2DBC is a non-blocking database driver specification, the reactive counterpart of JDBC. JDBC, and so JPA and Hibernate, block the calling thread, which on an event loop stalls every request. Spring Data R2DBC gives reactive repositories returning Mono and Flux. It is deliberately simpler than JPA: no lazy loading, no persistence context, and relationships are your job.

    • It needs a driver for your database.
    • Reactive transactions use R2dbcTransactionManager, with @Transactional or TransactionalOperator.
    • If you must keep JDBC, wrap calls with subscribeOn(boundedElastic).
    • Giving up JPA features is often the real cost of WebFlux.

    Go to the module

  292. Do virtual threads replace WebFlux?

    Reactive Programming WebFlux vs Spring MVC Mid-level Comparison

    Show answer

    For cheap waiting, largely yes: spring.threads.virtual.enabled=true gives MVC one virtual thread per request, and in a test its latency matched WebFlux with no code changes. They do not replace streaming, backpressure or operator composition. So plain request and response services can usually stay blocking, and real stream processing still fits reactive.

    • Virtual threads need Java 21 or later.
    • A connection pool still limits you, so virtual threads can overwhelm a database.
    • Blocking code keeps normal stack traces and ThreadLocals.
    • Do not rewrite a working WebFlux service just for this.

    Go to the module

  293. How does WebFlux differ from MVC internally?

    Reactive Programming WebFlux vs Spring MVC Mid-level Comparison

    Show answer

    MVC is built on the Servlet API: DispatcherServlet runs on a container such as Tomcat, with one thread per request by default. WebFlux has DispatcherHandler on a non-blocking server, Netty by default, and handlers return Mono or Flux, which the framework subscribes to. The annotations look the same, as with @RestController, but the filter types and the threading differ.

    • WebFlux uses WebFilter, not servlet Filter.
    • WebFlux also offers functional routes, through RouterFunction.
    • An event loop thread is named like reactor-http-nio-1, and a Tomcat one like http-nio-8080-exec-1.

    Go to the module

  294. Your MVC service is saturating under slow downstream calls. What would you try before rewriting it in WebFlux?

    Reactive Programming WebFlux vs Spring MVC Senior Design

    Show answer

    First measure: confirm that threads are waiting, not computing. Add timeouts, because a slow dependency should not hold threads forever. Then enable virtual threads, a one-line change if libraries cooperate. Use WebClient with Mono.zip for parallel calls. A pool increase is a short-term option. Rewrite only if you need streaming, since the rewrite touches every layer, including the database driver.

    • A full pool at 500 ms latency finishes 400 per second, so check the arithmetic.
    • A rewrite only helps if every call on the path becomes non-blocking.
    • Check a thread dump to see what the threads are doing.

    Go to the module

  295. How do you test a Flux, and what does StepVerifier do?

    Reactive Programming Testing reactive code Mid-level Concept

    Show answer

    Use StepVerifier from reactor-test. You script what should happen: expectNext for values, expectError for failures, and expectComplete for the end. verify() subscribes and checks each real signal against the next line, in order, blocking the test until it finishes. It tests order and the terminal signal, which a block() on a list cannot show.

    • Without a verify call, nothing runs, and the test passes.
    • verifyComplete() is shorthand for expectComplete().verify().
    • assertNext checks an element with your own assertions, and expectNextCount skips many.
    • Pass a timeout to verify(Duration) so that a stuck stream fails instead of hanging.

    Go to the module

  296. How do you control a publisher in a test, or check that a fallback was actually used?

    Reactive Programming Testing reactive code Mid-level Scenario

    Show answer

    TestPublisher lets you emit by hand, so you can trigger exact sequences, and even misbehave on purpose. PublisherProbe wraps a publisher and records what happened to it, so assertWasSubscribed proves a switchIfEmpty branch ran. With Mockito, return a Mono from a stub, and a test can then use StepVerifier on the result as usual.

    • A probe answers "was this branch used?", which output alone may not show.
    • Stubbing a Mono method to return null gives a NullPointerException in the chain.

    Go to the module

  297. What is Quarkus, and why was it created?

    Quarkus What Quarkus is and why Junior Concept

    Show answer

    Quarkus is a Java framework built for containers and Kubernetes. It moves framework work, such as scanning annotations, wiring beans and generating proxies, from startup to the build. Apps start faster and use less memory, in JVM (Java Virtual Machine) mode and even more as a GraalVM native image. It builds on standards, such as CDI, Jakarta REST and MicroProfile, and adds a fast dev mode.

    • Build-time processing means extensions do their framework work during the build and record the result as bytecode.
    • Startup time and memory matter when containers scale out, restart often or scale to zero.
    • Two outputs come from one code base, a fast-jar for the JVM or a native executable.
    • It uses standard APIs, such as CDI (Contexts and Dependency Injection) through ArC, Jakarta REST, and JPA (Jakarta Persistence API) through Hibernate ORM (object-relational mapping).

    Go to the module

  298. What is the difference between build-time and runtime processing?

    Quarkus What Quarkus is and why Junior Comparison

    Show answer

    Runtime processing, as in a classic Spring Boot app, reads annotations, evaluates conditions and creates proxies with reflection at every start. Quarkus extensions do this during the build: they read a Jandex index, resolve injection, generate bytecode and record initialization steps. At run time, the app only replays those steps and opens connections, so it starts faster and keeps less metadata in memory.

    • Augmentation is the build phase that runs the build steps of every extension.
    • Recorders turn initialization code into bytecode that runs when the app starts.
    • Classes used only to analyze the app are never loaded at run time.
    • A missing or ambiguous bean fails the build, not the first request.

    Go to the module

  299. How does Quarkus compare with Spring Boot?

    Quarkus What Quarkus is and why Junior Comparison

    Show answer

    Both are full Java stacks for REST, data and messaging. Spring Boot configures the app at startup and has the larger ecosystem and community. Quarkus does that work at build, so it starts faster and uses less memory, with native images and a fast dev mode built in. Quarkus uses standard APIs, such as CDI and Jakarta REST, and offers Spring compatibility extensions.

    • Spring Boot 3 also builds native images, through Spring AOT and GraalVM.
    • For long-running services on the JVM, throughput is close; the clear gaps are startup and memory.
    • Team skills and the libraries you need matter as much as startup numbers.

    Go to the module

  300. What is a Quarkus extension, and why not just add any library?

    Quarkus What Quarkus is and why Junior Concept

    Show answer

    An extension is a library plus a deployment module that runs at build. The deployment part tells Quarkus what the library needs: which classes to index, which beans to register, what a native image must keep for reflection, and what to initialize ahead of time. A plain library still works in JVM mode, but its scanning and reflection run at startup, and it may break in a native image.

    • Each extension has a runtime module and a deployment module.
    • Add one with quarkus ext add, or as a Maven or Gradle dependency.
    • Extensions also provide Dev Services and the panels of the Dev UI.

    Go to the module

  301. You set quarkus.datasource.db-kind to another database at run time, and the app ignores it. Why?

    Quarkus What Quarkus is and why Junior Scenario

    Show answer

    Some properties are fixed at build, because extensions use them during augmentation. The database kind chooses the JDBC (Java Database Connectivity) driver and how Hibernate is set up, and both were decided and recorded when the app was built. Changing it at run time has no effect, and Quarkus logs a warning that a build-time property differs. Rebuild with the new value; keep the URL and credentials as runtime settings.

    • The configuration reference marks build-time properties with a lock icon.
    • Runtime properties, such as the JDBC URL and credentials, can change per environment.
    • Profiles such as %dev. and %prod. choose values per environment.

    Go to the module

  302. Your team runs 40 small services on Kubernetes, and many scale to zero at night. Why might Quarkus fit?

    Quarkus What Quarkus is and why Junior Scenario

    Show answer

    Each instance starts in a fraction of the time and uses less memory, so cold starts are short and more pods fit on each node. Scaling to zero only works if the first request does not wait long, which a native image makes practical. Keep the JVM where peak throughput matters more, and weigh how much Spring experience the team already has.

    • Memory per pod sets how many pods fit on a node, and so the cost.
    • Fast startup helps scaling out, rolling deployments and scaling to zero.
    • Native builds take minutes, so most teams build native images only in CI (continuous integration).

    Go to the module

  303. What is a GraalVM native image, and how does Quarkus build one?

    Quarkus JVM mode vs native image Mid-level Concept

    Show answer

    A native image is a standalone executable that the native-image tool compiles ahead of time from the app and every library it reaches. It has no JIT (just-in-time) compiler, loads no new classes, and starts from a heap snapshot made at build. Quarkus builds one with ./mvnw package -Dnative, and can run the build inside a container with Mandrel, so GraalVM need not be installed.

    • It compiles under a closed-world assumption, so only code reachable at build is included.
    • Mandrel is a GraalVM distribution from Red Hat, focused on native images for Quarkus.
    • The binary is platform-specific, so build it for the operating system of the container.
    • @QuarkusIntegrationTest runs tests against the built binary.

    Go to the module

  304. Where do the startup and memory gains of a native image come from?

    Quarkus JVM mode vs native image Mid-level Concept

    Show answer

    Nothing loads or verifies classes at startup, because the code is already machine code. No JIT compiler runs, so there is no warm-up and no memory for compiled code or profiles. Objects initialized during the build are stored in the image heap and are ready at once. Quarkus adds to this, since its build-time processing leaves little framework work for startup.

    • For a small service, startup typically falls from about a second to tens of milliseconds.
    • Memory falls because no class metadata, JIT compiler or profiling data is kept.
    • Measure RSS (resident set size), the memory the process really uses, not only the heap.

    Go to the module

  305. What do you give up with a native image?

    Quarkus JVM mode vs native image Mid-level Comparison

    Show answer

    Build time, often minutes and several gigabytes of memory instead of seconds. Peak throughput, because no JIT optimizes the code from run-time profiles, so a warmed-up JVM is usually faster on long runs. Dynamic features, since reflection, resources and proxies must be known at build. Tooling, because Java agents and many JVM monitoring tools do not work the same way.

    • Profile-guided optimization in Oracle GraalVM narrows the throughput gap.
    • A library that relies on reflection may need configuration or a Quarkus extension.
    • Some failures appear only in the binary, so test the binary itself.

    Go to the module

  306. In the native binary only, a class read through reflection has no fields. Why, and how do you fix it?

    Quarkus JVM mode vs native image Mid-level Scenario

    Show answer

    The native build keeps only what it can see being used. A class reached only through reflection looks unused, so its fields and methods are left out, and reflection finds nothing at run time. Quarkus registers the types its extensions use, such as REST (Representational State Transfer) payloads. For other classes, add @RegisterForReflection, or a reflection configuration file.

    • The GraalVM tracing agent can record the reflection a test run uses.
    • Prefer an extension that registers what it needs over hand-written configuration.
    • Run integration tests against the native binary in CI to catch this early.

    Go to the module

  307. Which workloads benefit most from a native image?

    Quarkus JVM mode vs native image Mid-level Scenario

    Show answer

    Those that start often or run many small instances: serverless functions, services that scale to zero, command-line tools, and fleets of small pods where memory sets the cost. Long-running services under heavy, steady load usually do better on the JVM, where the JIT reaches higher peak throughput and builds are fast.

    • Cold start time decides whether scaling to zero is acceptable.
    • Memory per instance decides how many instances fit on a node.
    • Decide per service, since one code base can build both.

    Go to the module

  308. How do you test a native build in Quarkus?

    Quarkus JVM mode vs native image Mid-level Concept

    Show answer

    Build the binary, then run tests annotated with @QuarkusIntegrationTest. They start the built artifact as a separate process and call it over HTTP, so they cannot inject beans, but they check the real binary, including anything the native build left out. Run them in CI with ./mvnw verify -Dnative, since a native build is too slow for every change.

    • @QuarkusTest runs in JVM mode with injection; @QuarkusIntegrationTest runs against the package.
    • An integration test class often extends the @QuarkusTest class to reuse its HTTP tests.
    • The same annotation also tests a fast-jar or a container image.

    Go to the module

  309. What is the difference between @ApplicationScoped, @Singleton and @RequestScoped in Quarkus?

    Quarkus CDI and ArC Mid-level Comparison

    Show answer

    All three come from CDI. @ApplicationScoped gives one instance per app behind a client proxy, created on its first method call. @Singleton also gives one instance, with no proxy, so it is created when first injected. @RequestScoped gives one instance per HTTP request, behind a proxy, so an application-scoped bean can inject it safely. Prefer @ApplicationScoped unless you have a reason.

    • A client proxy lets a long-lived bean reach the right instance, created only when needed.
    • @Singleton skips the proxy, so it is a little cheaper, but @InjectMock cannot replace it.
    • With no scope declared, a CDI bean is @Dependent, a new instance per injection point.
    • The Quarkus documentation recommends @ApplicationScoped as the default choice.

    Go to the module

  310. What is a client proxy in CDI, and why does it exist?

    Quarkus CDI and ArC Mid-level Concept

    Show answer

    A client proxy is what gets injected for a normal-scoped bean, such as @ApplicationScoped or @RequestScoped. It is a generated subclass that, on every call, finds the current instance in its context and delegates to it. This lets a long-lived bean hold a request-scoped one safely, makes creation lazy, and allows circular dependencies between normal-scoped beans.

    • ArC generates its proxies as bytecode during the build, with no reflection.
    • Each call pays a small lookup, which is why @Singleton exists.
    • Spring uses the same idea for request-scoped beans, with scoped proxies.

    Go to the module

  311. What does ArC do during the build that a runtime CDI container does at startup?

    Quarkus CDI and ArC Mid-level Concept

    Show answer

    ArC reads the Jandex index, discovers beans, matches every injection point to exactly one bean, removes beans nothing uses, and generates bean classes, factories and client proxies as bytecode. An unsatisfied or ambiguous dependency fails the build. At startup, nothing is scanned and no reflection is needed; the generated code creates instances when they are first used.

    • Package-private injection fields avoid reflection; private ones need it.
    • ArC implements CDI Lite, so portable extensions are replaced by build compatible extensions.
    • Wiring errors surface during the build, before anything is deployed.

    Go to the module

  312. A bean you only look up programmatically at run time is not found in Quarkus. Why?

    Quarkus CDI and ArC Mid-level Scenario

    Show answer

    ArC removes beans that nothing injects, observes or names, to save memory and startup time. A lookup such as CDI.current().select() happens at run time, so the build cannot see it and removes the bean. Mark the bean @Unremovable, inject it through Instance<T> somewhere, or list it in quarkus.arc.unremovable-types.

    • Beans with observer methods, REST (Representational State Transfer) endpoints and @Named beans are kept.
    • quarkus.arc.remove-unused-beans=none turns removal off, at a cost in memory and startup.
    • Removal is why a Quarkus app carries only the beans it really uses.

    Go to the module

  313. What is the difference between the active record and repository patterns in Panache?

    Quarkus REST and Hibernate with Panache Mid-level Comparison

    Show answer

    Both are Panache patterns over Hibernate ORM (object-relational mapping). In active record, the entity extends PanacheEntity and carries the operations, as static methods such as Order.findById and instance methods such as persist. In the repository pattern, a CDI bean implements PanacheRepository<Order>, and the entity stays a plain JPA (Jakarta Persistence API) class. The operations are the same; the choice is where the code lives and how you test it.

    • PanacheEntity gives a generated Long id; extend PanacheEntityBase to declare your own.
    • Panache entities can use public fields, because Quarkus generates the accessors at build.
    • A repository is mocked with @InjectMock; active record statics need PanacheMock.
    • Writes need @Transactional in both patterns.

    Go to the module

  314. How do you write a REST endpoint in Quarkus?

    Quarkus REST and Hibernate with Panache Mid-level Concept

    Show answer

    With Jakarta REST annotations, served by Quarkus REST, formerly RESTEasy Reactive. A class with @Path holds methods annotated @GET, @POST and so on. Parameters come from @RestPath, @RestQuery or the body, which Jackson maps. Return the object for 200, or a RestResponse to choose the status. Methods that return Uni or Multi run on the event loop; others run on a worker thread.

    • Resource classes are singletons by default in Quarkus.
    • @ServerExceptionMapper turns an exception into a response.
    • With Hibernate Validator, a failed @Valid parameter returns 400.

    Go to the module

  315. A REST method calls order.persist() and fails with a TransactionRequiredException. Why, and what is the fix?

    Quarkus REST and Hibernate with Panache Mid-level Scenario

    Show answer

    Hibernate writes only inside a transaction, and Quarkus does not open one for you. Annotate the method that writes, or the service method it calls, with @Transactional from jakarta.transaction. The transaction commits when the method returns and rolls back on a runtime exception. Reads work without one, but group writes that must succeed together in one transaction.

    • Checked exceptions commit unless listed in rollbackOn.
    • ArC also intercepts self-invocation, a call from one method of the bean to another.
    • Panache.withTransaction is the equivalent with Hibernate Reactive.

    Go to the module

  316. How do you query with Panache, and how do you page the results?

    Quarkus REST and Hibernate with Panache Mid-level Concept

    Show answer

    Call find with a short form of HQL (Hibernate Query Language): find("status", OPEN) expands to a where clause, and find("status = ?1 and total > ?2", OPEN, 100) takes positional parameters. It returns a PanacheQuery, which you finish with list, firstResult, stream or count. For paging, call page(Page.of(index, size)), and pass a Sort to order the rows.

    • Simple queries can leave out select and from; Panache adds them.
    • list loads every row, so page large tables.
    • For complex queries, write full HQL or project into a smaller class.

    Go to the module

  317. How does live reload work in Quarkus dev mode?

    Quarkus Dev mode, Dev Services and testing Junior Concept

    Show answer

    Run quarkus dev, or ./mvnw quarkus:dev. Dev mode watches the sources, and when the next HTTP request arrives after a change, it recompiles what changed, reruns the build steps and restarts the app inside the same JVM (Java Virtual Machine), often in about a second. There is no separate build or redeploy, and changes to configuration are picked up the same way.

    • Reload is lazy, so it runs on the next request, or when you force it from the console.
    • Dev mode also opens a debug port, 5005, and the Dev UI at /q/dev-ui.
    • Dev Services containers keep running across reloads.

    Go to the module

  318. What are Dev Services, and when do they start?

    Quarkus Dev mode, Dev Services and testing Junior Concept

    Show answer

    Dev Services start the infrastructure your extensions need, such as PostgreSQL, Kafka or Keycloak, as containers through Testcontainers, in dev and test modes. One starts only when its extension is present, you have not configured a connection such as a datasource URL, and a container runtime like Docker or Podman is running. Quarkus then passes the URL and credentials to the app.

    • Configure a URL and that Dev Service stays off; production never uses Dev Services.
    • Containers are kept across live reloads, so data survives a reload.
    • quarkus.devservices.enabled=false turns them all off.

    Go to the module

  319. What is continuous testing in Quarkus?

    Quarkus Dev mode, Dev Services and testing Junior Concept

    Show answer

    In dev mode, press r and Quarkus runs your tests in the background, alongside the running app. After each change, it reruns only the tests that cover the changed code, and shows the results in the console and the Dev UI. You get test feedback seconds after saving, without running Maven.

    • It runs the same @QuarkusTest tests as the build.
    • Set quarkus.test.continuous-testing=enabled to start it with dev mode.
    • It suits a red, green, refactor loop, with no tool switching.

    Go to the module

  320. What does @QuarkusTest do, and how is it different from a plain unit test?

    Quarkus Dev mode, Dev Services and testing Junior Comparison

    Show answer

    @QuarkusTest starts the whole application once, on port 8081 by default, and reuses it for every test class with the same profile. The test class is a CDI (Contexts and Dependency Injection) bean, so it can inject beans, and it calls endpoints over HTTP, often with REST Assured. @InjectMock swaps one bean for a Mockito mock. A plain JUnit test starts nothing and runs in milliseconds.

    • A @TestProfile with other settings restarts the app, so group tests by profile.
    • @InjectMock works for normal-scoped beans, such as @ApplicationScoped, not @Singleton.
    • Dev Services give these tests a real database with no setup.

    Go to the module

  321. How do Mutiny's Uni and Multi compare with Reactor's Mono and Flux?

    Quarkus Reactive Quarkus: Mutiny and Vert.x Senior Comparison

    Show answer

    They play the same roles: Uni and Mono hold zero or one item, Multi and Flux hold many, and all four are lazy until subscribed. Mutiny's API is event-driven, grouping operators under onItem(), onFailure() and so on, so there are fewer names to learn. A Uni may emit null, which a Mono cannot. Quarkus uses Mutiny throughout, and converters bridge it to Reactor.

    • map becomes onItem().transform, and flatMap becomes onItem().transformToUni, or chain.
    • Mutiny 2 implements java.util.concurrent.Flow, the JDK (Java Development Kit) form of Reactive Streams.
    • Multi and Flux both support backpressure.
    • Mutiny comes from the SmallRye project and was designed with Quarkus.

    Go to the module

  322. In Quarkus, what runs on the event loop and what runs on a worker thread?

    Quarkus Reactive Quarkus: Mutiny and Vert.x Senior Comparison

    Show answer

    Vert.x handles network I/O on a few event loop threads, two per core by default, which must never block. Quarkus REST chooses from the method signature: a method returning Uni or Multi runs on the event loop, and a method returning a plain value runs on a worker thread from a larger pool, where blocking calls such as JDBC (Java Database Connectivity) are allowed.

    • Block an event loop, and every request on that thread waits.
    • Vert.x logs a blocked thread warning when a loop is busy for more than 2 seconds.
    • The worker pool is bounded, so long blocking waits can still use it up.

    Go to the module

  323. What do @Blocking, @NonBlocking and @RunOnVirtualThread do?

    Quarkus Reactive Quarkus: Mutiny and Vert.x Senior Concept

    Show answer

    They override the thread Quarkus picks from the signature. @Blocking runs a method on a worker thread even if it returns Uni, for example a Uni that wraps JDBC. @NonBlocking keeps a method with a plain return type on the event loop, when it never blocks. @RunOnVirtualThread runs the method on a new virtual thread, so blocking code waits cheaply.

    • The same annotations apply to messaging methods, such as Kafka consumers.
    • @RunOnVirtualThread needs Java 21 or later.
    • Prefer clear signatures, and annotate only when the default is wrong.

    Go to the module

  324. A method returns a Uni but calls a JDBC repository inside it. What happens, and how do you fix it?

    Quarkus Reactive Quarkus: Mutiny and Vert.x Senior Scenario

    Show answer

    The method runs on the event loop, so the JDBC call blocks a loop thread, and every request on that thread waits. Hibernate ORM (object-relational mapping) refuses outright to run on an I/O thread, and other blocking calls make Vert.x log blocked thread warnings. Fix it with @Blocking, by returning a plain value, or by switching to a reactive client such as Hibernate Reactive.

    • Uni.createFrom().item(supplier) runs the supplier on the subscribing thread, here the loop.
    • emitOn and runSubscriptionOn move work to another executor, like publishOn and subscribeOn.
    • Test under load, since one blocked loop slows unrelated endpoints.

    Go to the module

  325. Which MicroProfile specifications does Quarkus support, and how do you use Config, Health and Fault Tolerance?

    Quarkus Configuration and cloud-native extensions Mid-level Concept

    Show answer

    Quarkus implements MicroProfile through SmallRye. Config is built in: inject values with @ConfigProperty or a @ConfigMapping interface, and override them with environment variables. Health, from quarkus-smallrye-health, serves liveness and readiness endpoints from @Liveness and @Readiness beans. Fault Tolerance adds retries, timeouts, a circuit breaker, bulkheads and fallbacks to bean methods, through annotations such as @Retry. OpenAPI, REST Client and JWT (JSON Web Token) work the same way.

    • Each specification is an extension, so the build includes only what you add.
    • Liveness answers whether to restart the pod; readiness whether to send it traffic.
    • Fault Tolerance defaults come from the specification, such as a 1 second timeout.
    • Quarkus recommends Micrometer for metrics, rather than MicroProfile Metrics.

    Go to the module

  326. What does the Quarkus Kubernetes extension do?

    Quarkus Configuration and cloud-native extensions Mid-level Concept

    Show answer

    It generates Kubernetes manifests during the build. With quarkus-kubernetes, the build writes target/kubernetes/kubernetes.yml with a Deployment and a Service, using the image name and ports of the app. If the health extension is present, it adds liveness and readiness probes that call its endpoints. You tune it with quarkus.kubernetes.* properties, and quarkus.kubernetes.deploy=true applies it.

    • A container image extension, such as Jib or Docker, builds the image in the same build.
    • Variants exist for OpenShift, Minikube and Kind.
    • quarkus-kubernetes-config reads ConfigMaps and Secrets as configuration.

    Go to the module

  327. What are the pros and cons of microservices compared with a monolith?

    Microservices Monolith vs microservices Junior Comparison

    Show answer

    A monolith is one deployable: simple to build, test, debug and run, with fast in-process calls and local transactions. Its cost is coupling: teams share one release, and the whole app scales as one. Microservices let each team deploy, scale and fail independently, and choose its own stack. In exchange, every call crosses the network, data spreads over many databases, and you need automation, monitoring and tracing to run them.

    • Microservices solve an organizational problem first, teams blocking each other, and a scaling problem second.
    • The network is not free: calls can be slow or fail, so timeouts, retries and circuit breakers become mandatory.
    • A local ACID (atomicity, consistency, isolation, durability) transaction becomes eventual consistency across services.
    • A modular monolith keeps one deployable with enforced module borders, and is the usual starting point.

    Go to the module

  328. When should you NOT use microservices?

    Microservices Monolith vs microservices Junior Scenario

    Show answer

    When one or two teams own the product, when the domain is new and its boundaries are still moving, when there is no automated deployment, monitoring and on-call to run many services, or when the load is even and a few replicas of one app handle it. In those cases a wrong split costs more than a monolith ever would.

    • Moving a boundary between modules is a refactoring; moving one between services is a migration.
    • Each service needs its own pipeline, dashboards, alerts and on-call.
    • Martin Fowler's advice is monolith first, then extract once the boundaries are proven.

    Go to the module

  329. What is a modular monolith?

    Microservices Monolith vs microservices Junior Concept

    Show answer

    One deployable application split into modules along business capabilities, such as orders, payments and shipping. Each module owns its data and exposes a small public API; everything else is internal. Tools such as Spring Modulith or ArchUnit fail the build when a module reaches past a border. You keep in-process calls and one release, and gain the clear boundaries you need to extract a service later.

    • Modules talk through public interfaces or in-process events, never through each other's tables.
    • A schema per module keeps data ownership clear inside one database.
    • Extracting a well-kept module later is mostly moving code, not untangling it.

    Go to the module

  330. What does Conway's law say, and how does it affect the choice of architecture?

    Microservices Monolith vs microservices Junior Concept

    Show answer

    Conway's law says a system's structure copies the communication structure of the organization that builds it. Five teams that rarely talk will produce five loosely connected parts, whatever the diagram says. So service boundaries should match team boundaries: one team owns one or a few services end to end. The inverse Conway maneuver shapes the teams first to get the architecture you want.

    • A service owned by two teams turns every change into a meeting.
    • Team size is a real input to the choice, not an afterthought.
    • Team Topologies calls these stream-aligned teams, each owning a business flow.

    Go to the module

  331. How would you migrate a monolith to microservices without a big-bang rewrite?

    Microservices Monolith vs microservices Junior Design

    Show answer

    Use the strangler fig pattern. Put a gateway or proxy in front of the monolith, modularize the code, then extract one module at a time: build it as a service with its own database, move its route in the gateway, and delete the old code. Pick first a module with clear borders and a real reason to leave, such as its own scaling.

    • Keep a rollback route in the gateway until the new service has proven itself.
    • Move the data too, or the services stay coupled through the old schema.
    • Big-bang rewrites stop feature work for months and usually miss behavior nobody documented.

    Go to the module

  332. What must a team have in place before running microservices in production?

    Microservices Monolith vs microservices Junior Concept

    Show answer

    Automated build and deployment per service, so releasing is cheap. Centralized logs, metrics and distributed tracing, so one request can be followed across services. Health checks and an orchestrator such as Kubernetes to restart and scale them. Resilience in every client: timeouts, retries and circuit breakers. And clear ownership: each service has one team that runs it in production.

    • Martin Fowler lists rapid provisioning, basic monitoring and rapid deployment as prerequisites.
    • Without tracing, a slow request across five services is a guessing game.
    • Contract tests replace much of the end-to-end testing a monolith had for free.

    Go to the module

  333. How do you decide where to split a system into services?

    Microservices Decomposition and bounded contexts Mid-level Design

    Show answer

    Split by business capability, along bounded contexts from Domain-Driven Design (DDD): areas where words and rules have one meaning, such as Ordering, Payments and Shipping. Each service owns its data and is owned by one team. A good split keeps changes local: most features touch one service. Avoid splitting by technical layer, and avoid services so small that every feature needs several to change together.

    • Find the contexts by listening to the business, for example with event storming.
    • High cohesion inside a service, loose coupling between them, measured by how often they change together.
    • Start coarse; splitting a service later is cheaper than merging two.
    • Match services to teams, as Conway's law predicts you will anyway.

    Go to the module

  334. What is a bounded context?

    Microservices Decomposition and bounded contexts Mid-level Concept

    Show answer

    A boundary inside which one model, and one meaning of each word, applies. "Product" in Catalog has a name and photos; in Shipping it has a weight and a box size; in Ordering it is a line with the price paid. Each context keeps its own model instead of one shared model with every field. Bounded contexts are the natural candidates for service boundaries.

    • The ubiquitous language is the vocabulary the team and the business share inside one context.
    • Contexts share IDs, not models.
    • A subdomain is a problem area; a bounded context is the solution's boundary, often one per subdomain.

    Go to the module

  335. Why should each service have its own database, and how do services then share data?

    Microservices Decomposition and bounded contexts Mid-level Design

    Show answer

    A shared database couples services through its schema: one team's migration can break another, and nobody knows who owns a column. With a database per service, only the owner reads and writes its data, and others get it through its API or from events. Services that need someone else's data often keep a local, read-only copy, updated by events, and accept that it is slightly stale.

    • It can be a separate schema on the same server, as long as no service reads another's.
    • A query across services becomes an API composition or a read model built from events.
    • A transaction across services becomes a saga.

    Go to the module

  336. What is a context map, and what does an anticorruption layer do?

    Microservices Decomposition and bounded contexts Mid-level Concept

    Show answer

    A context map draws the bounded contexts and how they relate: who is upstream and who is downstream, and how a downstream context copes with an upstream model. An anticorruption layer is a translator in the downstream context that turns the upstream model, often a legacy or external system, into its own, so foreign names and rules never spread through its code.

    • Common relationships: customer-supplier, conformist, shared kernel, open host service with a published language.
    • The anticorruption layer is where you put the adapter pattern at the boundary.
    • Use one when integrating a legacy system during a strangler fig migration.

    Go to the module

  337. When do you use synchronous calls between microservices, and when asynchronous messaging?

    Microservices Synchronous vs asynchronous communication Mid-level Comparison

    Show answer

    Use a synchronous call, HTTP or gRPC, when the caller needs the answer to continue, such as checking stock before confirming a checkout. Use asynchronous messaging when it does not: publish an event and let others react in their own time. Sync is simpler and immediately consistent, but couples services in time, so one outage spreads. Async isolates failures and absorbs bursts, but brings eventual consistency, duplicates and harder debugging.

    • A chain of synchronous calls is only as available as the product of its parts.
    • Every synchronous call needs a timeout, and usually a retry and a circuit breaker.
    • Messaging needs idempotent consumers, because brokers deliver at least once.
    • Most systems mix both, query synchronously and propagate changes with events.

    Go to the module

  338. REST, gRPC or messaging between services, how do you choose?

    Microservices Synchronous vs asynchronous communication Mid-level Comparison

    Show answer

    REST (Representational State Transfer) over HTTP with JSON is universal, readable and cacheable: the default for public APIs and simple internal ones. gRPC uses HTTP/2 and Protocol Buffers, a compact binary format with a typed contract, for fast internal calls, streaming and polyglot clients; browsers need a proxy. Messaging through Kafka or RabbitMQ decouples sender and receiver in time, for events and work that can happen later.

    • gRPC generates client and server code from a .proto file, and fails at compile time on a contract mismatch.
    • JSON is easy to debug with curl; Protocol Buffers are smaller and faster to parse.
    • Messaging adds a broker to run, monitor and secure.

    Go to the module

  339. What is temporal coupling, or coupling in time, between services?

    Microservices Synchronous vs asynchronous communication Mid-level Concept

    Show answer

    Two services are coupled in time when one can only work while the other is up and answering. A synchronous call creates it: if Payments is down, Orders cannot finish. Messaging removes it, because the broker holds the message until the receiver is back. It is separate from coupling in format: services can still share a contract, but no longer need to be available at the same moment.

    • Temporal coupling turns one outage into many, a cascading failure.
    • Caching and local copies of data also reduce it, for reads.
    • The broker must be highly available, since everyone now depends on it.

    Go to the module

  340. A page calls five services to render. How do you keep its latency low?

    Microservices Synchronous vs asynchronous communication Mid-level Scenario

    Show answer

    Call independent services in parallel, so the page waits for the slowest call rather than the sum. Give each call a tight timeout, and a fallback for optional parts such as reviews, so one slow service costs a bounded delay. Watch the tail: the more calls, the more often at least one is slow. Then cut calls: cache, keep local copies via events, or let an aggregator or a backend for frontend fetch once.

    • With 1% slow calls, a page that fans out to ten services is slow almost 10% of the time.
    • Measure p99 latency, not the average, which hides the tail.
    • Hedged requests, sending a second copy after a delay, trim the tail for idempotent reads.

    Go to the module

  341. What makes communication between services chatty, and why is it a problem?

    Microservices Synchronous vs asynchronous communication Mid-level Concept

    Show answer

    Chatty communication is many small calls where one would do: fetching an order, then each line, then each product, one request at a time. Each hop adds network latency, serialization and a chance of failure, so a few dozen calls make a slow and fragile request. It usually means the service boundary is in the wrong place, or the API is too fine-grained.

    • Prefer coarse operations, such as getting an order with its lines in one call.
    • Batch endpoints replace N calls with one.
    • Services that call each other constantly may belong together.

    Go to the module

  342. How do you change an API or event without breaking the services that use it?

    Microservices Synchronous vs asynchronous communication Mid-level Design

    Show answer

    Make backward-compatible changes: add optional fields, never remove or rename one that consumers read, and make consumers ignore fields they do not know. For a breaking change, run both versions side by side, a new path or event version, migrate consumers, then remove the old one. Contract tests catch a provider that breaks a consumer before it deploys.

    • The tolerant reader pattern lets consumers survive added fields.
    • Version in the path, such as /v2/orders, or in a header or media type.
    • Consumer-driven contracts, with Pact or Spring Cloud Contract, test each pair of services.

    Go to the module

  343. Why use an API gateway in front of microservices?

    Microservices API gateway, service discovery and load balancing Mid-level Concept

    Show answer

    It gives clients one entry point and hides how the system is split, so services can be moved, split or merged without breaking clients. It also does the cross-cutting work once: routing, authentication, rate limiting, TLS (Transport Layer Security) termination, request logging and tracing, and sometimes response aggregation. Spring Cloud Gateway, Kong, NGINX or a cloud API gateway are typical choices.

    • It cuts round trips for mobile clients by aggregating calls.
    • It must stay thin and generic; business rules belong in the services.
    • Run several replicas behind a load balancer, so it is not a single point of failure.
    • Services still authorize each request; the gateway only stops bad tokens early.

    Go to the module

  344. How do services find each other in a microservices system?

    Microservices API gateway, service discovery and load balancing Mid-level Concept

    Show answer

    Through service discovery. Instances register their address with a registry, such as Eureka or Consul, at startup, and send heartbeats; an instance that stops is removed. Callers look up a service by name and get the healthy instances. On Kubernetes, the platform does this: a Service gets a stable DNS (Domain Name System) name and virtual IP, and routes to the ready pods behind it.

    • Hard-coded hosts break as soon as instances scale, move or restart.
    • Client-side discovery asks the registry; server-side discovery goes through a router that asks it.
    • Registries cache entries, so a dead instance can be called for a few seconds; retries cover the gap.

    Go to the module

  345. What is the difference between client-side and server-side load balancing?

    Microservices API gateway, service discovery and load balancing Mid-level Comparison

    Show answer

    With client-side load balancing, the caller gets the instance list from a registry and picks one itself, as Spring Cloud LoadBalancer does: no extra hop, and the caller can retry on another instance, but every client needs the library. With server-side load balancing, callers send to one stable address, and a load balancer, an NGINX or a Kubernetes Service, picks the instance: simple clients, one more hop to run.

    • Typical algorithms are round robin, least connections and weighted random.
    • A service mesh moves client-side balancing into a sidecar proxy, with no library in the code.
    • Health checks keep failing instances out of the pool, whichever side balances.

    Go to the module

  346. How would you implement rate limiting in an API gateway that runs as several replicas?

    Microservices API gateway, service discovery and load balancing Mid-level Design

    Show answer

    Count requests per client key, such as the API key or the token's subject, in a shared store such as Redis, so all replicas see the same counter. A token bucket allows short bursts while capping the average rate. When a client is over the limit, answer 429 Too Many Requests with a Retry-After header. Spring Cloud Gateway's RequestRateLimiter filter does this with Redis.

    • Counters local to each replica let a client get N times the limit.
    • Limit per client and per route, since some endpoints are far costlier than others.
    • Decide what happens if Redis is down, failing open or closed.

    Go to the module

  347. An instance crashes. How long can callers keep sending it requests, and how do you limit the damage?

    Microservices API gateway, service discovery and load balancing Mid-level Scenario

    Show answer

    Until the registry or the balancer notices. Eureka evicts after missed heartbeats, 90 seconds by default, and clients refresh their cached list every 30 seconds, so a dead instance can get traffic for a minute or two. On Kubernetes, a failing readiness probe removes the pod in seconds. Limit the damage with short connection timeouts, retries on another instance for idempotent calls, and shorter lease settings.

    • A graceful shutdown deregisters the instance before it stops.
    • Kubernetes removes a terminating pod from its Service endpoints before killing it.
    • Retries must go to a different instance, which client-side balancing allows.

    Go to the module

  348. What is the difference between an API gateway and a load balancer?

    Microservices API gateway, service discovery and load balancing Mid-level Comparison

    Show answer

    A load balancer spreads traffic across instances of one service, at layer 4 by connection or at layer 7 by HTTP request, and knows little about the request's meaning. An API gateway works at the application level for many services: it routes by path, authenticates, rate limits, transforms and aggregates. Gateways often sit behind a load balancer and use one internally to reach service instances.

    • Load balancer means many instances of one thing; gateway means one door to many things.
    • Cloud load balancers already do some layer 7 routing, which blurs the line.
    • A service mesh handles traffic between services, while the gateway handles traffic from outside.

    Go to the module

  349. How does a circuit breaker work, and what are its states?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Concept

    Show answer

    It wraps calls to a dependency and counts failures over a sliding window. Closed: calls pass through. When the failure rate, or the slow-call rate, reaches a threshold, it opens: calls fail immediately, often to a fallback, which spares threads and gives the dependency time to recover. After a wait it goes half-open and lets a few trial calls through; if they succeed it closes, otherwise it opens again.

    • It fails fast instead of making every caller wait for a timeout.
    • It protects the struggling service from more load while it recovers.
    • Window size, minimum calls, threshold and open duration are the settings to tune.
    • In Resilience4j, an open breaker throws CallNotPermittedException, which the fallback can catch.

    Go to the module

  350. How should a service retry a failed call to another service?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Concept

    Show answer

    Retry only transient failures, such as timeouts, connection errors and 503, never a 400. Limit the attempts, to three or so. Wait longer each time, with exponential backoff, and add random jitter so clients that failed together do not retry together. Retry only idempotent operations, or send an idempotency key. And keep the total time within the caller's own timeout.

    • Retries multiply load; retrying at every layer of a five-service chain can multiply it many times over.
    • A retry budget caps retries at a share of normal traffic.
    • Put the retry outside the circuit breaker, so an open breaker stops the retries too.

    Go to the module

  351. What is the bulkhead pattern?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Concept

    Show answer

    It isolates resources per dependency, like the watertight compartments of a ship, so one failing dependency cannot sink the whole service. In practice it caps concurrent calls to each dependency, with a semaphore or a separate thread pool. When Inventory is slow, at most 20 threads wait on it; the 21st call is rejected at once, and the threads serving other endpoints stay free.

    • Resilience4j offers a semaphore bulkhead and a thread pool bulkhead.
    • Size it from expected throughput times latency, plus headroom.
    • Separate pools, or even separate deployments, isolate critical from batch traffic.

    Go to the module

  352. What makes a good fallback when a call to another service fails?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Design

    Show answer

    A fallback returns something useful without the dependency: a cached value, a default, a reduced answer, or a clear error the client can act on. For product recommendations, show bestsellers; for stock, show "availability unknown"; for a payment, there is no safe fallback, so fail clearly. It must be cheap and must not call another fragile service, or it fails too.

    • Make degraded answers visible to the user or the caller, not silently wrong.
    • Decide per feature whether failing open or closed is safe.
    • Count fallback use in metrics; frequent fallbacks hide an outage.

    Go to the module

  353. What does Resilience4j give a Spring Boot service, and how are its parts combined?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Concept

    Show answer

    Resilience4j is a lightweight library with CircuitBreaker, Retry, TimeLimiter, Bulkhead and RateLimiter modules. In Spring Boot you annotate a method, configure each named instance in properties, and get metrics through Actuator and Micrometer. When several annotations apply, the default order is Retry outermost, then the circuit breaker, rate limiter, time limiter and bulkhead around the call. It replaced Netflix Hystrix, now in maintenance.

    • The fallbackMethod takes the same parameters plus a Throwable.
    • Annotations work through Spring proxies, so self-invocation skips them.
    • Spring Cloud Circuit Breaker offers a neutral API over Resilience4j.

    Go to the module

  354. A service calls three others with no timeouts. Why is that dangerous, and how do you pick the values?

    Microservices Resilience: circuit breaker, retry, timeout, bulkhead Mid-level Scenario

    Show answer

    Without a timeout, a dependency that hangs holds the caller's threads forever, and the caller hangs too: one slow service brings down its callers. Set a connect timeout of a few hundred milliseconds and a read timeout just above the dependency's normal p99 latency. Make the timeouts along a chain shrink downstream, so the caller never gives up before the services it waits on.

    • Default HTTP client timeouts are often infinite or very long.
    • A deadline passed along the chain, as gRPC does, keeps all hops within budget.
    • A timed-out call may still succeed on the other side, so retries need idempotency.

    Go to the module

  355. What does the CAP theorem say, and what does it mean in practice?

    Microservices CAP and eventual consistency Senior Concept

    Show answer

    CAP says that when the network partitions, a distributed data store must choose between consistency, every read sees the latest write, and availability, every request to a working node gets an answer. It cannot have both during the partition. Partitions are not optional in real networks, so the practical choice is CP, refusing what you cannot confirm, or AP, answering with possibly stale data.

    • Consistency in CAP means linearizability, not the C of ACID (atomicity, consistency, isolation, durability).
    • Without a partition, a system can be both consistent and available.
    • Examples: ZooKeeper, etcd and a single primary database lean CP; Cassandra and DynamoDB lean AP, tunable per query.
    • The choice can differ per operation, not just per system.

    Go to the module

  356. What is the difference between strong and eventual consistency?

    Microservices CAP and eventual consistency Senior Comparison

    Show answer

    With strong consistency, once a write is acknowledged every later read, from any node, returns it, as if there were one copy. With eventual consistency, replicas may disagree for a while, but if writes stop they converge to the same value. Strong costs latency and availability, since replicas must coordinate; eventual is fast and survives partitions, but readers can see old data.

    • Between services with their own databases, eventual consistency through events is the norm.
    • Read-your-writes and monotonic reads are useful middle grounds.
    • Conflicting concurrent writes need a resolution rule, such as last write wins or a merge.

    Go to the module

  357. How do quorum reads and writes give strong consistency in a replicated store?

    Microservices CAP and eventual consistency Senior Concept

    Show answer

    With N replicas, a write waits for W acknowledgements and a read asks R replicas. If R plus W is greater than N, every read set overlaps every write set, so at least one replica in the read has the latest write, and the newest version wins. With N of 3, QUORUM writes and reads use 2 and 2. Lower values are faster and more available, but may read stale data.

    • Cassandra and DynamoDB let you choose the level per query.
    • A quorum needs a majority, so the minority side of a partition cannot serve quorum requests.
    • Overlapping sets alone are not linearizable without care for concurrent writes and repairs.

    Go to the module

  358. In a microservices system that is eventually consistent, how do you keep users from being confused?

    Microservices CAP and eventual consistency Senior Design

    Show answer

    Let users read their own writes: answer a command with the state it produced, or read from the primary for that user right after a write. Show pending states honestly, such as "payment processing", instead of a wrong final value. Return 202 with a link to poll, or push an update when the read model catches up. Keep the lag small and measure it.

    • Version numbers let a client wait until a read model reaches the version it wrote.
    • Monitor consumer lag; it is the size of the inconsistency window.
    • Design the business process to tolerate delay, as banks do with pending transactions.

    Go to the module

  359. What is a saga, and why use one instead of a distributed transaction?

    Microservices Distributed transactions and Saga Senior Concept

    Show answer

    A saga is a sequence of local transactions, one per service, each committed in its own database and triggering the next step. If a step fails, the saga runs compensating transactions that undo the effects of the steps already committed, in reverse order. It replaces a distributed transaction, which needs every database to hold locks and agree, with a series of short, independent commits.

    • Each service keeps its own database and its own short transactions.
    • The result is eventual consistency; intermediate states, such as PENDING, are visible.
    • Coordinate it by choreography, with events, or by orchestration, with a central coordinator.
    • Every step and compensation must be idempotent, because messages can be redelivered.

    Go to the module

  360. Why not use two-phase commit (2PC) across microservices?

    Microservices Distributed transactions and Saga Senior Concept

    Show answer

    In two-phase commit (2PC), a coordinator asks every participant to prepare, holding its locks, and then to commit. All participants must be up, support the protocol, and wait for the slowest one; if the coordinator fails after prepare, they hold locks until it returns. That couples services in time, hurts throughput and availability, and most brokers and NoSQL stores, and HTTP APIs, do not support XA, the standard 2PC protocol.

    • 2PC is a blocking protocol; locks are held across network round trips.
    • Availability of the whole is the product of every participant's availability.
    • It works inside one database or a small trusted cluster, not across autonomous services.

    Go to the module

  361. What is the difference between saga choreography and orchestration, and when do you pick each?

    Microservices Distributed transactions and Saga Senior Comparison

    Show answer

    In choreography, there is no coordinator: each service listens for events and publishes its own, so the flow emerges from the chain. It is simple and loosely coupled, but the flow is spread across services and hard to follow. In orchestration, a coordinator sends commands to each service and handles replies, so the flow and its compensations live in one place. Choose choreography for two or three steps, orchestration for longer flows with branches.

    • Choreography risks cyclic dependencies between services' events.
    • The orchestrator must not absorb the services' business logic.
    • Tracing and a correlation ID are essential either way.

    Go to the module

  362. What is a compensating transaction, and what makes one hard to design?

    Microservices Distributed transactions and Saga Senior Concept

    Show answer

    It is an action that semantically undoes a committed step: refund a charge, cancel a reservation, release stock. It does not erase history; both the step and its compensation remain. It is hard when the effect cannot be undone, such as an email already sent or a ticket already issued, or when other actions already built on the result. Such steps go last, as the pivot.

    • Compensations must be idempotent and retryable until they succeed.
    • Some compensations are business decisions, such as a refund with a fee.
    • Order steps so that the riskiest and the irreversible ones run last.

    Go to the module

  363. Sagas have no isolation between them. What can go wrong, and how do you guard against it?

    Microservices Distributed transactions and Saga Senior Scenario

    Show answer

    Other sagas can see and act on uncommitted intermediate state. A dirty read: a customer spends credit that a failing saga is about to return. A lost update: two sagas change the same record, and one compensation overwrites the other. Guards include semantic locks, a PENDING flag that others respect; commutative updates, such as adding or subtracting instead of setting; rereading values before acting; and ordering steps so risky ones go first.

    • ACID (atomicity, consistency, isolation, durability) gives isolation in one database; a saga gives only eventual atomicity.
    • A pending state shown to users is often the simplest countermeasure.
    • Version checks catch a record that changed since the saga read it.

    Go to the module

  364. How do you make each step of a saga reliable when services crash and messages are redelivered?

    Microservices Distributed transactions and Saga Senior Design

    Show answer

    Commit each local change and the message that triggers the next step together, with a transactional outbox, so neither is lost. Make every handler idempotent, by recording processed message IDs or checking the current state, because the broker delivers at least once. Persist the saga's state, so an orchestrator resumes after a crash, and add timeouts for steps that never answer.

    • A step that never replies needs a timeout that triggers compensation.
    • Correlate every message with the saga ID and log it.
    • Test each failure point, including a crash between steps.

    Go to the module

  365. What is the dual-write problem?

    Microservices Outbox, CDC and idempotency Senior Concept

    Show answer

    A service that must change its database and publish a message does two writes to two systems with no shared transaction. A crash or a failure between them leaves them disagreeing: the order is saved but the event is lost, or the event is sent but the order rolls back. Retrying does not help when the process died. The fix is to make one write the source of the other: the transactional outbox, or change data capture on the database.

    • Sending inside a database transaction does not help; the broker is not part of it.
    • Sending first just reverses the failure, an event for an order that does not exist.
    • Distributed transactions across database and broker are rarely available, and slow when they are.
    • Listening to your own event to update your database is another, less common, way out.

    Go to the module

  366. How does the transactional outbox pattern work?

    Microservices Outbox, CDC and idempotency Senior Design

    Show answer

    In the same local transaction as the business change, the service inserts the event into an outbox table. Both commit or neither does. A separate relay then reads unsent rows and publishes them to the broker, marking each as sent, or a change data capture tool such as Debezium reads them from the database's log. Events are never lost, but can be published more than once.

    • Publish in creation order per aggregate, using its ID as the message key, to keep ordering.
    • Clean up sent rows, or the table grows without bound.
    • The outbox row's ID makes a natural event ID for consumers to deduplicate on.

    Go to the module

  367. How do you make a message consumer idempotent?

    Microservices Outbox, CDC and idempotency Senior Design

    Show answer

    Make processing the same message twice have the same effect as once. Give each message a unique ID, and record processed IDs in the consumer's database in the same transaction as its changes; skip an ID already seen. Or make the operation naturally idempotent: set a status rather than toggle it, upsert by a business key, or use a unique constraint such as one payment per order.

    • At-least-once delivery plus an idempotent consumer gives effectively once processing.
    • External side effects, such as a card charge, need the provider's idempotency key.
    • Keep processed IDs long enough to cover the longest redelivery window.

    Go to the module

  368. Where do duplicate messages come from, even with a reliable broker?

    Microservices Outbox, CDC and idempotency Senior Concept

    Show answer

    From every retry that cannot know whether the first attempt worked. A producer resends after a lost acknowledgement. An outbox relay republishes rows it published but had not yet marked sent. A consumer that crashes or loses its partition in a rebalance before committing its offset gets the same records again. Brokers guarantee at-least-once because the alternative, at-most-once, loses messages.

    • Kafka's idempotent producer removes producer resend duplicates, not consumer redeliveries.
    • Committing the offset before processing turns duplicates into lost messages.
    • Design every consumer for duplicates and for out-of-order arrival.

    Go to the module

  369. What is CQRS?

    Microservices CQRS and Event Sourcing Senior Concept

    Show answer

    Command Query Responsibility Segregation separates the model that changes data from the model that reads it. Commands go to a write model that enforces the business rules; queries go to one or more read models, denormalized and shaped for each screen or API, often in a different database. The read models are updated from the write side's changes, usually asynchronously, so they can lag behind.

    • Each side can be designed, stored and scaled for its own workload.
    • Read models can be rebuilt from the source of truth at any time.
    • The cost is more moving parts and eventual consistency on the read side.
    • It is applied to one bounded context, not to a whole system.

    Go to the module

  370. What is event sourcing?

    Microservices CQRS and Event Sourcing Senior Concept

    Show answer

    Instead of storing the current state and overwriting it, you store every change as an immutable event, in order, in an append-only event store. The current state is derived by replaying the events, and read models are built by projections that subscribe to them. You get a full audit trail, the ability to rebuild state at any point in time, and new read models from old data.

    • Events are facts in the past tense, such as Withdrew, and are never updated or deleted.
    • Mistakes are corrected with new events, not edits.
    • Optimistic concurrency on the aggregate's version stops two conflicting appends.

    Go to the module

  371. When are CQRS and event sourcing worth their cost, and when are they not?

    Microservices CQRS and Event Sourcing Senior Scenario

    Show answer

    CQRS pays when reads and writes differ a lot: complex rules on write, many differently shaped reads, or very different loads. Event sourcing pays when the history itself has business value, such as ledgers, audit-heavy domains or systems that must answer what was true at a past date. Neither suits simple CRUD, teams new to eventual consistency, or data that must be erased on request.

    • Event sourcing makes schema changes harder; old events live forever and need upcasting.
    • Deleting personal data in an immutable log needs crypto-shredding or separate storage.
    • Start with one bounded context, not the whole system.

    Go to the module

  372. In an event-sourced system, how do you change the shape of an event that is already stored?

    Microservices CQRS and Event Sourcing Senior Design

    Show answer

    Stored events never change, so the code must read every version. Add fields in a backward-compatible way with defaults. For larger changes, write a new event type or version, and an upcaster that converts old versions into the new shape when they are read. Version events explicitly, and keep old event classes or schemas as long as old events exist.

    • Weak schemas, such as JSON with optional fields, evolve more easily than rigid ones.
    • Rebuilding a read model replays old versions, so test projections against them.
    • Copy-and-transform the store only as a last resort, and keep the original.

    Go to the module

  373. What is distributed tracing, and how does it work?

    Microservices Observability: logs, metrics and traces Mid-level Concept

    Show answer

    Distributed tracing follows one request across every service it touches. The first service creates a trace ID; each service records a span, a timed unit of work with its parent span's ID, and passes the trace context on, in an HTTP header such as W3C traceparent or a message header. Spans are exported to a backend, which joins them by trace ID into a waterfall showing where time went and what failed.

    • Instrumentation is mostly automatic, through framework integrations or the OpenTelemetry Java agent.
    • Context must cross thread pools and async boundaries, or the trace breaks.
    • Sampling keeps cost under control; tail sampling keeps the errors and slow traces.
    • Put the trace ID in every log line to jump from a trace to its logs.

    Go to the module

  374. What are trace IDs and span IDs?

    Microservices Observability: logs, metrics and traces Mid-level Concept

    Show answer

    A trace ID identifies one whole request across all services: 16 random bytes, the same in every span of that request. A span ID identifies one operation within it, such as one HTTP call or one database query: 8 bytes, new for every span. Each span also stores its parent's span ID, which turns the spans into a tree. Both travel in the W3C traceparent header: version, trace ID, parent span ID and flags.

    • The flags say whether the trace is sampled, so all services make the same choice.
    • Baggage carries extra key-value pairs along the trace, such as a tenant ID.
    • Logs record both IDs, through the logging MDC (Mapped Diagnostic Context).

    Go to the module

  375. What is a correlation ID, and how does it differ from a trace ID?

    Microservices Observability: logs, metrics and traces Mid-level Comparison

    Show answer

    A correlation ID is any identifier passed along a request or a business flow so that related logs can be found together, often an X-Correlation-ID header set at the edge and logged everywhere. A trace ID is a standardized correlation ID that tracing systems manage, with spans and timings. Today the trace ID usually serves as the correlation ID; a business ID, such as an order ID, still helps to follow a flow across several requests.

    • A saga spanning hours covers many traces; an order ID ties them together.
    • Return the ID in error responses, so users can quote it to support.
    • Never trust an incoming ID blindly from outside; validate or replace it at the gateway.

    Go to the module

  376. What is OpenTelemetry, and how does a Spring Boot service use it?

    Microservices Observability: logs, metrics and traces Mid-level Concept

    Show answer

    OpenTelemetry is the vendor-neutral standard for telemetry: APIs and SDKs (software development kits) to create traces, metrics and logs, automatic instrumentation for common libraries, the OTLP (OpenTelemetry Protocol) wire format, and a collector that receives, processes and forwards data to any backend. A Spring Boot 3 service uses Micrometer Observation with the OpenTelemetry bridge and an OTLP exporter, or runs the OpenTelemetry Java agent with no code changes.

    • It replaced OpenTracing and OpenCensus.
    • Backends such as Jaeger, Tempo, Datadog or New Relic all accept OTLP, so no lock-in.
    • The collector can sample, filter and enrich data before it is stored.

    Go to the module

  377. Which OAuth2 and OIDC flows matter in a microservices system, and when is each used?

    Microservices Security between services Mid-level Concept

    Show answer

    OAuth2 issues access tokens; OIDC (OpenID Connect) adds an ID token that says who the user is. For a user in a browser or mobile app, use the authorization code flow with PKCE (Proof Key for Code Exchange): the user logs in at the authorization server, and the app trades a one-time code for tokens. For a service calling as itself, with no user, use client credentials. Implicit and password grants are deprecated.

    • Services act as resource servers that validate tokens; the gateway or the app is the OAuth2 client.
    • Access tokens are short-lived; refresh tokens get new ones without a new login.
    • With a backend for frontend, tokens stay on the server and the browser holds a session cookie.
    • Token exchange swaps a user's token for one meant for a specific downstream service.

    Go to the module

  378. How do you pass the user's identity from the gateway to services further down the call chain?

    Microservices Security between services Mid-level Design

    Show answer

    Pass the user's access token, a JWT (JSON Web Token), in the Authorization header on every hop, which Spring Cloud Gateway's TokenRelay filter does, and have every service validate it: signature with the issuer's public keys, issuer, audience, expiry, then scopes. For a tighter setup, exchange the token at each hop for one with a narrower audience and scope, so a leaked token works on fewer services.

    • Never pass identity in a plain header such as X-User-Id; any caller can forge it.
    • Validation is local and fast; keys are fetched once from the issuer and cached.
    • Asynchronous messages carry the user ID as data, since tokens expire before old messages are read.

    Go to the module

  379. Should authentication happen at the API gateway or in every service?

    Microservices Security between services Mid-level Comparison

    Show answer

    Both, with different jobs. The gateway handles the login flow and rejects requests without a valid token early, so bad traffic never reaches the services. Every service still validates the token and checks permissions for its own data, because the internal network is not a trust boundary: a compromised service or a misrouted request must not get in for free. This is the zero trust approach.

    • The gateway knows coarse rules, such as a route needs a login; services know fine rules, such as whose order this is.
    • Validating a JWT locally is cheap, so checking at every hop costs little.
    • Object-level checks, such as order ownership, can only happen in the service that owns the data.

    Go to the module

  380. What is mTLS, and why use it between services?

    Microservices Security between services Mid-level Concept

    Show answer

    mTLS (mutual Transport Layer Security) is TLS where both sides present a certificate, so the client proves its identity to the server as well as the other way round. Between services it encrypts traffic and authenticates the calling service, not the user. A service mesh such as Istio or Linkerd issues, rotates and enforces the certificates in sidecars, so application code does not change.

    • mTLS answers which service is calling; the JWT answers for which user and with which rights.
    • Short-lived certificates, rotated automatically, limit the damage of a stolen key.
    • Mesh policies can allow only Orders to call Payments, by service identity.

    Go to the module

  381. What is Kafka, and what is it used for?

    Kafka Core concepts: broker, topic, partition, offset Junior Concept

    Show answer

    Kafka is a distributed event streaming platform: a cluster of brokers that stores streams of records in topics, as replicated, append-only logs. Producers append records; consumers read them by offset, at their own pace, and the records stay until retention deletes them. It is used for event-driven microservices, activity tracking, log and metrics pipelines, change data capture and stream processing, wherever high throughput, ordering per key and replay matter.

    • A topic is split into partitions; a partition is an ordered log on disk.
    • Records are kept for a retention time, not deleted when read, so many groups can read them.
    • Partitions spread load across brokers and are replicated, usually three times, for fault tolerance.
    • Consumers in one group split the partitions, which is how reading scales.

    Go to the module

  382. What is the difference between a topic and a partition?

    Kafka Core concepts: broker, topic, partition, offset Junior Comparison

    Show answer

    A topic is a named, logical stream, such as orders. A partition is one ordered log that holds part of the topic's records, stored on a broker and replicated to others. A record's key decides its partition, so one key always lands in the same one. Partitions are the unit of parallelism, ordering and replication: more partitions allow more consumers in a group, but order is only guaranteed within one partition.

    • Partition count caps the consumers of one group that can work at once.
    • Partitions can be added later but never removed, and adding them moves keys.
    • Each partition has one leader replica serving its reads and writes.

    Go to the module

  383. What is an offset, and who keeps track of it?

    Kafka Core concepts: broker, topic, partition, offset Junior Concept

    Show answer

    An offset is the position of a record inside its partition: 0, 1, 2 and on, assigned on append and never reused. The broker assigns it; the consumer tracks how far it has read. A consumer group commits, per partition, the offset of the next record to read, and Kafka stores it in the internal topic __consumer_offsets. After a restart or a rebalance, consumption resumes from the committed offset.

    • Offsets are per partition, so offset 5 exists in every partition.
    • The committed offset is the next one to read, not the last one processed.
    • With no committed offset, auto.offset.reset decides: latest by default, or earliest.

    Go to the module

  384. How long does Kafka keep records, and what is log compaction?

    Kafka Core concepts: broker, topic, partition, offset Junior Concept

    Show answer

    By default Kafka deletes records after a retention time, retention.ms, 7 days by default, or once a partition passes retention.bytes, unlimited by default, whether or not anyone read them. It deletes whole segment files, so records can outlive the limit a little. Log compaction, cleanup.policy=compact, keeps the latest record per key instead, which suits a changelog of current state. A record with a null value, a tombstone, deletes its key.

    • Retention is per topic and independent of consumers.
    • Compaction keeps at least the last value of every key, forever.
    • Topics can combine both policies, compact and delete.

    Go to the module

  385. Why is Kafka called a log and not a queue?

    Kafka Core concepts: broker, topic, partition, offset Junior Comparison

    Show answer

    A queue hands each message to one consumer and deletes it once acknowledged. Kafka appends records to a log and keeps them for the retention time; consumers only move their own offset. So many consumer groups read the same records independently, a group can rewind and replay, and order holds within a partition. The price: Kafka acknowledges a position, not a single message, so it cannot skip one failed record and redeliver it alone.

    • Reading does not delete; retention does.
    • Load sharing comes from partitions, not from handing out messages one by one.
    • Replay rebuilds read models or feeds a new service from history.

    Go to the module

  386. What happens to a topic when a broker goes down?

    Kafka Core concepts: broker, topic, partition, offset Junior Scenario

    Show answer

    Each partition has replicas on several brokers, typically three. One is the leader that serves reads and writes; the followers copy it. When the leader's broker dies, the controller elects a new leader from the followers that were in sync, and clients refresh their metadata and carry on against it. With a replication factor of 3, the topic survives one broker down with no data loss, given the producer waited for all in-sync replicas.

    • Replication factor 1 means one broker down makes that partition unavailable.
    • Leaders are spread across brokers so load stays balanced.
    • Producers and consumers only talk to the leader, by default.

    Go to the module

  387. How does a Kafka producer choose the partition for a record?

    Kafka Producers, keys and partitioning Mid-level Concept

    Show answer

    If the record names a partition, it goes there. Otherwise, with a key, the default partitioner hashes the serialized key with murmur2 and takes it modulo the partition count, so the same key always lands in the same partition. Without a key, the producer sticks to one partition until the batch is full or sent, then switches, favoring less loaded brokers. A custom Partitioner can replace the rule.

    • Same key, same partition, which is what keeps the events of one entity in order.
    • Adding partitions changes the modulo, so existing keys move to other partitions.
    • A key with far more traffic than the others makes one partition hot.
    • Unkeyed records are spread for throughput, with no ordering between them.

    Go to the module

  388. How do you keep the order of events in Kafka?

    Kafka Producers, keys and partitioning Mid-level Scenario

    Show answer

    Kafka guarantees order only within a partition, so give every event that must stay in order the same key, such as the order ID. Keep the idempotent producer on, so retries cannot swap batches. On the consumer side, a partition is read by one consumer of the group; process its records sequentially, or in parallel only across different keys. Order across different keys is not guaranteed, and usually not needed.

    • Ordering is per key, through the partition, not per topic.
    • Retries without idempotence and with several requests in flight can reorder records.
    • A single partition keeps total order, but caps the group at one consumer.

    Go to the module

  389. What do acks=0, acks=1 and acks=all mean for a producer?

    Kafka Producers, keys and partitioning Mid-level Comparison

    Show answer

    acks sets when the leader answers a write. With 0, the producer does not wait, so it never learns of a failure. With 1, the leader answers after writing to its own log; if it crashes before the followers copy the record, the record is lost although acknowledged. With all, the leader answers once every in-sync replica has it, which survives a leader crash. all is the default since Kafka 3.0.

    • acks=all waits for in-sync replicas, not for every replica.
    • min.insync.replicas, often 2, sets how many in-sync replicas acks=all needs, or the write fails.
    • Higher acks costs latency, not much throughput, thanks to batching.

    Go to the module

  390. What is an idempotent producer?

    Kafka Producers, keys and partitioning Mid-level Concept

    Show answer

    A producer whose retries cannot create duplicates or reorder records. The broker gives it a producer ID, and the producer numbers every batch per partition. If a retry arrives with a sequence number the leader already wrote, the leader acknowledges it without writing it again. It needs acks=all and at most 5 requests in flight, and it is on by default since Kafka 3.0.

    • It removes duplicates caused by retries, within one producer session and partition.
    • It does not stop your code from calling send twice for the same event.
    • Exactly-once across partitions and with consumers needs transactions on top.

    Go to the module

  391. How do linger.ms and batch.size affect a producer?

    Kafka Producers, keys and partitioning Mid-level Concept

    Show answer

    The producer groups records per partition into batches. batch.size, 16 KB by default, caps a batch; linger.ms is how long the producer waits for more records before sending a batch that is not full. A few milliseconds of linger gives bigger batches, better compression and far fewer requests, for a small latency cost. Kafka 4.0 raised the linger.ms default from 0 to 5 ms for that reason.

    • Throughput comes from batching and compression, such as lz4 or zstd.
    • Batches are per partition, so many partitions with little traffic each make small batches.
    • buffer.memory caps what waits to be sent; when full, send blocks.

    Go to the module

  392. Is KafkaProducer.send synchronous? How do you know a record was written?

    Kafka Producers, keys and partitioning Mid-level Code

    Show answer

    No. send adds the record to a batch in memory and returns a Future at once; a background thread sends batches and retries. You learn the result from the callback, or by calling get, which blocks and kills throughput if done for every record. If retries run out within delivery.timeout.ms, two minutes by default, the future fails, and the application must log, alert or store the record.

    • Spring's KafkaTemplate.send returns a CompletableFuture in Spring Kafka 3.
    • Unhandled failures are silent data loss.
    • close and flush wait for batches still in memory.

    Go to the module

  393. How do consumer groups let you scale consumption in Kafka?

    Kafka Consumer groups and rebalancing Mid-level Concept

    Show answer

    Consumers that share a group ID split the partitions of the topics they subscribe to: each partition is assigned to exactly one consumer of the group, and a consumer can hold several. To read faster, you add consumers, up to the number of partitions. Different groups are independent: each gets every record and keeps its own offsets. So partitions scale one service, and groups let many services read the same data.

    • The partition count is the ceiling on parallelism inside one group.
    • Each partition is read by one consumer, which keeps per-partition order.
    • A rebalance redistributes partitions whenever members or partitions change.
    • One group per service; one consumer per thread.

    Go to the module

  394. What happens when a group has more consumers than the topic has partitions?

    Kafka Consumer groups and rebalancing Mid-level Scenario

    Show answer

    The extra consumers get no partition and sit idle. Kafka never gives one partition to two consumers of the same group, because that would break ordering and offset tracking. Idle consumers are not useless: if a consumer fails, the rebalance can hand its partitions to one of them at once. To use more consumers, add partitions, accepting that keys move to new partitions.

    • Parallelism is the smaller of consumers and partitions.
    • Plan partitions for the peak consumer count you expect.
    • Kafka 4 share groups allow several consumers per partition, without per-partition order.

    Go to the module

  395. What is a rebalance, and what triggers it?

    Kafka Consumer groups and rebalancing Mid-level Concept

    Show answer

    A rebalance reassigns the partitions of a group among its current members. It is triggered when a consumer joins, leaves, misses heartbeats for session.timeout.ms, or does not poll within max.poll.interval.ms, and when the subscribed topics gain partitions. With the classic eager protocol, everyone stops reading until it ends. Each new owner resumes from the committed offset, so uncommitted work is redone.

    • Cooperative rebalancing moves only the partitions that change owner.
    • Static membership, with group.instance.id, avoids rebalances on a quick restart.
    • Kafka 4.0 made a new protocol, where the broker assigns incrementally, generally available.

    Go to the module

  396. What is consumer lag, and what do you do when it keeps growing?

    Kafka Consumer groups and rebalancing Mid-level Scenario

    Show answer

    Lag is, per partition, the log end offset minus the committed offset of the group: records produced but not yet processed. Growing lag means the group processes slower than producers write. First find out where: one hot partition, or all of them. Then speed up processing, add consumers up to the partition count, add partitions, or batch the expensive work. Alert on lag, or on its growth, per group.

    • Lag on one partition only points at a hot key or a stuck consumer.
    • Frequent rebalances show up as lag spikes.
    • Retention keeps running, so very high lag can turn into lost records.

    Go to the module

  397. Why does a consumer get thrown out of its group when processing is slow?

    Kafka Consumer groups and rebalancing Mid-level Scenario

    Show answer

    Two timers watch a consumer. Heartbeats, sent from a background thread, prove the process is alive within session.timeout.ms, 45 seconds by default. Separately, the application must call poll again within max.poll.interval.ms, 5 minutes by default, to prove it is making progress. If one batch takes longer, the consumer leaves the group, its partitions move, and its commit fails. Lower max.poll.records or speed up the work.

    • The defaults are 500 records per poll and 5 minutes between polls.
    • Raising the interval delays detecting a stuck consumer.
    • A CommitFailedException after a slow batch is the typical sign.

    Go to the module

  398. What partition assignment strategies does the Java consumer offer?

    Kafka Consumer groups and rebalancing Mid-level Comparison

    Show answer

    Range gives each consumer a contiguous range of each topic's partitions, and is the first default. RoundRobin deals partitions one by one across consumers. Sticky balances while keeping as many assignments as possible. CooperativeSticky does the same, but rebalances incrementally: consumers keep the partitions that do not move and keep reading them. In Kafka 4 the new consumer protocol moves assignment to the broker.

    • The default list is Range, then CooperativeSticky, so a group can upgrade with rolling restarts.
    • Sticky assignment reduces rework, since partitions rarely change owner.
    • All members must agree on a common strategy.

    Go to the module

  399. What are at-most-once, at-least-once and exactly-once delivery in Kafka?

    Kafka Offsets and delivery semantics Mid-level Comparison

    Show answer

    They describe what a crash does to records in flight, and the consumer decides it by when it commits. Commit before processing: at-most-once, a crash can lose records. Commit after processing: at-least-once, a crash repeats them, so processing must be idempotent. Exactly-once means the output records and the input offsets commit in one Kafka transaction, read with read_committed; it covers results written back to Kafka.

    • At-least-once with idempotent processing is the usual choice.
    • The producer side needs acks=all and idempotence not to lose or duplicate on retries.
    • Exactly-once does not cover side effects outside Kafka, such as a database or an email.
    • Kafka Streams turns it on with processing.guarantee=exactly_once_v2.

    Go to the module

  400. What is the difference between auto commit and manual commit, and which do you choose?

    Kafka Offsets and delivery semantics Mid-level Comparison

    Show answer

    With enable.auto.commit=true, the client commits the offsets returned by the previous poll every 5 seconds, during poll. That is at-least-once only if you finish each batch before polling again; with asynchronous processing it commits work not done, and loses it on a crash. Manual commit, with commitSync, commitAsync or a Spring acknowledgment, commits exactly when the work is done. Spring Kafka disables auto commit and commits for you after each batch.

    • Auto commit also commits on close, and can repeat up to 5 seconds of work after a crash.
    • Commit the next offset to read, last processed plus one.
    • Committing per record is safe but slow; per batch is the usual middle.

    Go to the module

  401. How do Kafka transactions work?

    Kafka Offsets and delivery semantics Mid-level Concept

    Show answer

    A producer with a transactional.id registers with a transaction coordinator, a broker. Between beginTransaction and commitTransaction, its records to any partitions, plus the consumer offsets it adds with sendOffsetsToTransaction, form one unit. On commit or abort the coordinator writes markers into every partition involved. Consumers with isolation.level=read_committed only see committed records. A restarted producer with the same transactional.id fences the old one off.

    • Aborted records stay in the log; read_uncommitted consumers, the default, still see them.
    • read_committed consumers wait for open transactions, so long ones add latency.
    • The transactional.id must be stable per producer instance and unique across instances.

    Go to the module

  402. A consumer processed offsets 10 to 14. Which offset does it commit, and why does it matter?

    Kafka Offsets and delivery semantics Mid-level Code

    Show answer

    It commits 15: the committed offset is the position of the next record to read, not the last one processed. A restarted or new owner of the partition starts exactly there. Committing 14 by mistake makes record 14 run again after every restart; committing too far ahead skips records. With commitSync and no arguments, the consumer commits the positions returned by the last poll, which already follow this rule.

    • The position is per partition.
    • The offset map passed to commitSync must hold record.offset() + 1.
    • Committed offsets live in the internal topic __consumer_offsets.

    Go to the module

  403. What acknowledgment modes does a Spring Kafka listener container offer?

    Kafka Offsets and delivery semantics Mid-level Concept

    Show answer

    The container commits for you according to its AckMode. BATCH, the default, commits after all records of a poll are processed. RECORD commits after each record. TIME and COUNT commit after an interval or a number of records. MANUAL and MANUAL_IMMEDIATE let the listener call Acknowledgment.acknowledge; the first queues the commit until the batch ends, the second commits at once.

    • All of them commit after processing, so the result is at-least-once.
    • With a transaction manager, offsets commit with the transaction instead.
    • An error handler decides whether a failed record is retried, skipped or sent to a Dead Letter Topic.

    Go to the module

  404. Does Kafka exactly-once cover a service that reads from Kafka and calls a payment API?

    Kafka Offsets and delivery semantics Mid-level Scenario

    Show answer

    No. Kafka transactions cover records written to Kafka and offsets committed to Kafka, nothing else. If the payment API is called and the transaction then aborts, the call already happened, and the retry calls it again. For external effects, design for at-least-once: send an idempotency key the API recognizes, or record the processed event ID in your own database with the change, and skip repeats.

    • Exactly-once is a property of a read-process-write loop inside Kafka.
    • The outbox pattern covers the opposite direction, from a database to Kafka.
    • Idempotency keys make repeated external calls harmless.

    Go to the module

  405. How does replication work in Kafka?

    Kafka Replication, ISR and fault tolerance Mid-level Concept

    Show answer

    Each partition has a replication factor, usually 3: one copy per broker. One replica is the leader, which takes all writes and, by default, all reads. The followers fetch from the leader to stay in sync. The replicas that are caught up form the ISR, the in-sync replicas. If the leader's broker fails, the controller elects a new leader from the ISR, and clients switch to it.

    • acks=all waits for every replica in the ISR, so a new leader from the ISR has every acknowledged record.
    • Leaders are spread across brokers, so each broker leads some partitions and follows others.
    • Consumers only see records up to the high watermark, the offset copied to every in-sync replica.

    Go to the module

  406. What is the ISR, and how does a replica fall out of it?

    Kafka Replication, ISR and fault tolerance Mid-level Concept

    Show answer

    The ISR, in-sync replicas, is the set of replicas that are caught up with the leader, the leader included. A follower that has not caught up to the leader's log end within replica.lag.time.max.ms, 30 seconds by default, or whose broker dies, is removed. It rejoins once it catches up. The ISR decides when acks=all writes count as committed, and who may become leader.

    • Replicas lists every assigned copy; ISR lists the ones caught up.
    • A shrinking ISR is a key alert: under-replicated partitions.
    • The controller keeps the ISR in the cluster metadata.

    Go to the module

  407. What does min.insync.replicas do?

    Kafka Replication, ISR and fault tolerance Mid-level Concept

    Show answer

    It sets how many replicas must be in sync for an acks=all write to be accepted. If fewer are, the leader rejects the write with NotEnoughReplicas, instead of acknowledging a record held by too few brokers. With replication factor 3 and min.insync.replicas=2, one broker can be down and writes continue, each on at least 2 disks. It has no effect on producers with acks=0 or 1.

    • Set it below the replication factor, or one broker restart blocks writes.
    • It is a topic setting with a broker default.
    • It trades availability for durability when replicas are missing.

    Go to the module

  408. What is KRaft, and why did Kafka replace ZooKeeper?

    Kafka Replication, ISR and fault tolerance Mid-level Comparison

    Show answer

    KRaft is Kafka's built-in metadata quorum: a few controller nodes agree, with the Raft protocol, on cluster metadata such as brokers, topics, partition leaders and ISRs, and store it as an internal log that brokers replicate. Before, an external ZooKeeper cluster held it. KRaft means one system to deploy and secure, faster controller failover, and far more partitions per cluster. Kafka 4.0 removed ZooKeeper support.

    • Usually 3 or 5 controllers, so a majority survives one or two failures.
    • Brokers learn metadata changes by reading the metadata log.
    • Migration from ZooKeeper happens on a 3.x release before moving to 4.0.

    Go to the module

  409. What is the core difference between Kafka and RabbitMQ?

    Kafka Kafka vs RabbitMQ Mid-level Comparison

    Show answer

    Kafka is a distributed log: producers append records to partitions, records stay for a retention time, and each consumer group pulls them and tracks its own offset. RabbitMQ is a message broker: producers send to exchanges, which route messages into queues; the broker pushes each message to one consumer and deletes it once acknowledged. So Kafka suits streams that many readers replay; RabbitMQ suits tasks routed to workers.

    • Kafka scales by partitions and keeps order per partition.
    • RabbitMQ routes per message with direct, topic, fanout and headers exchanges.
    • RabbitMQ acknowledges and redelivers single messages; Kafka commits a position.
    • Kafka is built for very high throughput and long retention.

    Go to the module

  410. How do you replay messages in Kafka, and can RabbitMQ do it?

    Kafka Kafka vs RabbitMQ Mid-level Scenario

    Show answer

    In Kafka, records stay for the retention time, so you move a group's offsets back with kafka-consumer-groups.sh --reset-offsets, to the earliest offset, an offset or a date, or call seek in code, or start a new group. In a classic RabbitMQ queue, an acknowledged message is deleted, so it is gone; replay needs a stream, or the producer to resend from its own store.

    • Replay only reaches as far back as retention.
    • Consumers must tolerate reprocessing, so keep them idempotent.
    • Reset offsets only while the group is stopped.

    Go to the module

  411. When would you choose Kafka, and when RabbitMQ?

    Kafka Kafka vs RabbitMQ Mid-level Design

    Show answer

    Choose Kafka for event streams: high volume, several independent consumers, replay, ordering per key, stream processing, change data capture, long retention. Choose RabbitMQ for work queues and integration: tasks handed to one worker, routing by pattern, priorities, per-message acknowledgment and redelivery, delays, request and reply. At low volume both work; then the team's experience and what already runs matter most.

    • Event-driven microservices that publish domain events lean towards Kafka.
    • Background jobs with retries and priorities lean towards RabbitMQ.
    • Managed services, such as Amazon MSK (Managed Streaming for Apache Kafka) or CloudAMQP, change the operating cost.

    Go to the module

  412. How does RabbitMQ route messages?

    Kafka Kafka vs RabbitMQ Mid-level Concept

    Show answer

    A producer publishes to an exchange with a routing key; it never writes to a queue directly. Bindings connect queues to exchanges. A direct exchange matches the key exactly, a topic exchange matches patterns such as order.eu.*, a fanout exchange copies to every bound queue, and a headers exchange matches message headers. Each matching queue gets its own copy, and its consumers compete for the messages in it.

    • One queue with several consumers spreads work; one queue per service broadcasts.
    • A message that matches no binding is dropped, unless it is marked mandatory or an alternate exchange is set.
    • A dead letter exchange catches rejected or expired messages.

    Go to the module

  413. How do Kafka and RabbitMQ scale consumers differently?

    Kafka Kafka vs RabbitMQ Mid-level Comparison

    Show answer

    RabbitMQ uses competing consumers: any number can read one queue, each message goes to one of them, and prefetch limits how many unacknowledged messages each holds. So you just add workers, and order is not kept across them. Kafka assigns whole partitions to consumers of a group, so parallelism stops at the partition count, but each partition keeps its order.

    • Kafka trades flexible scaling for ordering per partition.
    • RabbitMQ prefetch, often 10 to 100, balances throughput and fairness.
    • Kafka share groups, new in Kafka 4, bring queue-like consumption to Kafka.

    Go to the module

  414. How do Kafka and RabbitMQ make sure a message is not lost?

    Kafka Kafka vs RabbitMQ Mid-level Comparison

    Show answer

    Both need cooperation from both ends. In Kafka, the producer uses acks=all on a topic with replication factor 3 and min.insync.replicas=2, and the consumer commits after processing. In RabbitMQ, the producer uses publisher confirms with durable, replicated quorum queues and persistent messages, and the consumer acknowledges manually after processing. Both then deliver at least once, so consumers must be idempotent.

    • RabbitMQ auto-ack deletes on delivery, so a crash loses the message.
    • Quorum queues replicate with Raft, as KRaft does for Kafka metadata.
    • Unacknowledged RabbitMQ messages are redelivered when the consumer's channel closes.

    Go to the module

  415. What is a poison pill in Kafka, and how do you handle it?

    Kafka Errors, retries and Dead Letter Topic Mid-level Concept

    Show answer

    A poison pill is a record that fails every time it is processed, typically because it cannot be deserialized or breaks a validation rule. Since a consumer commits positions, not single messages, retrying it forever blocks its whole partition. Handle it by catching deserialization errors with ErrorHandlingDeserializer, classifying such errors as not retryable, and sending the record to a Dead Letter Topic (DLT) at once, with an alert.

    • Lag growing on one partition while others are fine is the typical sign.
    • Retries are for transient failures; a poison pill is permanent.
    • Schemas and a schema registry stop many poison pills at the producer.

    Go to the module

  416. What are retry topics, and when do you use them instead of blocking retries?

    Kafka Errors, retries and Dead Letter Topic Mid-level Comparison

    Show answer

    Blocking retries repeat the failed record in place, with a back-off, so the partition waits. That keeps order, but one slow dependency stalls everything behind the record. Retry topics move the failed record to topics such as orders-retry-1000 and orders-retry-2000, consumed after a delay, and commit it in the main topic, which keeps flowing. The cost: records of the same key can now be processed out of order.

    • Spring Kafka creates the retry topics and the DLT from @RetryableTopic.
    • By default the suffixes carry the delay, such as -retry-1000, and the DLT ends in -dlt.
    • Use blocking retries when order per key matters, retry topics when throughput does.

    Go to the module

  417. What is a Dead Letter Topic, and what do you do with the records in it?

    Kafka Errors, retries and Dead Letter Topic Mid-level Concept

    Show answer

    A Dead Letter Topic (DLT) holds records that could not be processed after the allowed attempts, or that can never succeed. Each record keeps its key and value, plus headers with the exception, the original topic, partition and offset. Someone must own it: alert when records arrive, find the cause, fix the code or the data, then republish the records to the original topic, or discard them deliberately.

    • Keep DLT retention longer than the source, so nothing expires before someone looks.
    • Replaying from the DLT needs idempotent consumers.
    • A DLT that nobody watches is just a slower way to lose data.

    Go to the module

  418. How does Spring Kafka handle an exception thrown by a listener?

    Kafka Errors, retries and Dead Letter Topic Mid-level Concept

    Show answer

    The listener container passes it to its CommonErrorHandler, by default the DefaultErrorHandler. It seeks the partition back so the record is redelivered, up to 10 deliveries with no delay by default, then logs it and moves on. Give it a back-off and a DeadLetterPublishingRecoverer to publish to a DLT instead. Exceptions such as DeserializationException are not retried. @RetryableTopic switches to non-blocking retries through retry topics.

    • Spring Boot applies a CommonErrorHandler bean to the auto-configured listener container.
    • addNotRetryableExceptions marks your own permanent errors.
    • The recoverer runs after the last failed attempt, then the offset is committed.

    Go to the module

  419. Why use a schema registry with Kafka?

    Kafka Schemas and evolution (Avro, Schema Registry) Senior Concept

    Show answer

    Kafka stores bytes and checks nothing, while producers and consumers are deployed by different teams at different times. A schema registry stores every version of each topic's schema, in Avro, Protobuf or JSON Schema, and rejects a new version that breaks the compatibility rule. Records carry only a small schema ID, so they stay compact, and consumers fetch the writer's schema to decode them. Contract breaks fail in continuous integration (CI), not in production.

    • Schemas are grouped by subject, by default the topic name plus -key or -value.
    • The serializer prefixes each record with a magic byte and a 4-byte schema ID.
    • Clients cache schemas, so the registry is not called per record.

    Go to the module

  420. What is the difference between backward and forward compatibility?

    Kafka Schemas and evolution (Avro, Schema Registry) Senior Comparison

    Show answer

    Backward compatible means consumers on the new schema can read data written with the old one, so you upgrade consumers first; it is the registry's default. Forward compatible means consumers on the old schema can read data written with the new one, so producers can upgrade first. Full means both. The transitive variants check against every earlier version, not just the latest, which matters when old data is replayed.

    • Adding a field with a default is safe both ways.
    • Removing a field is backward compatible but breaks old readers that need it, unless it had a default.
    • Renaming a field breaks both, unless the new schema declares the old name as an alias.

    Go to the module

  421. What are Kafka Streams and Kafka Connect for?

    Kafka Kafka Streams and Kafka Connect Senior Comparison

    Show answer

    Kafka Streams is a Java library for processing data inside your own application: it reads topics, filters, maps, joins, aggregates and windows them, keeps state in local stores backed by changelog topics, and writes results to topics, with exactly-once if enabled. Kafka Connect is a separate runtime that moves data between Kafka and other systems through configured connectors: sources such as Debezium for change data capture, sinks such as Elasticsearch or S3 (Simple Storage Service).

    • Streams needs no cluster of its own; it scales by running more instances with the same application ID.
    • Connect replaces hand-written import and export code with configuration.
    • Single message transforms adjust records in Connect; real processing belongs in Streams.

    Go to the module

  422. What is the difference between a KStream and a KTable?

    Kafka Kafka Streams and Kafka Connect Senior Comparison

    Show answer

    A KStream reads a topic as a sequence of independent events: every record is a new fact, so two records for alice are two deposits, and aggregating sums them. A KTable reads it as a changelog: each record replaces the value for its key, and a null value, a tombstone, deletes it, so alice holds her latest balance. Joining a stream with a table enriches each event with the current value for its key.

    • Aggregating a KStream produces a KTable.
    • A KTable topic is usually compacted, since only the latest value per key matters.
    • A GlobalKTable copies the whole table to every instance and needs no co-partitioning.

    Go to the module

  423. What is the difference between a container and a virtual machine?

    Docker and Kubernetes Containers vs virtual machines Junior Comparison

    Show answer

    A VM (virtual machine) virtualizes hardware: a hypervisor runs several VMs, and each boots its own guest kernel and operating system, so it is strongly isolated but weighs gigabytes and starts in tens of seconds. A container virtualizes the operating system: it is an ordinary process on the host's kernel, isolated by namespaces and limited by cgroups, packaged with only its app and libraries. So it starts in about a second, weighs megabytes and packs densely, with a thinner wall, since all containers share one kernel.

    • VMs are isolated by the hypervisor, each with its own kernel; containers share the host kernel.
    • Namespaces decide what a container sees; cgroups decide how much CPU, memory and processes it gets.
    • Containers are lighter and faster, so you run more per machine and redeploy in seconds.
    • In the cloud, containers usually run inside VMs, combining both.

    Go to the module

  424. What actually isolates a container from the host and from other containers?

    Docker and Kubernetes Containers vs virtual machines Junior Concept

    Show answer

    Two Linux kernel features. Namespaces give the process its own view: the PID (process ID) namespace its own process tree, the network namespace its own interfaces and ports, the mount namespace its own filesystem, plus UTS for the hostname, IPC and user namespaces. cgroups, control groups, limit and account resources: memory, CPU time, process count and disk I/O. A container runtime sets both up and starts the process inside them; there is no other magic.

    • Namespaces limit what a process can see.
    • cgroups limit what a process can use, and report usage for docker stats.
    • Capabilities, seccomp and read-only filesystems narrow what a root process may do.

    Go to the module

  425. Is a container as secure as a VM? How would you harden one?

    Docker and Kubernetes Containers vs virtual machines Junior Scenario

    Show answer

    No. Every container makes system calls to the same kernel, so a kernel bug or a misconfiguration can let one escape to the host and its neighbors; a VM's guest kernel and hypervisor are a much smaller shared surface. Harden a container by running it as a non-root user, dropping capabilities, using a read-only root filesystem and the default seccomp profile, never using --privileged or mounting the Docker socket, and keeping images small and patched.

    • Root in a container is root on the kernel, minus what capabilities remove.
    • Rootless Docker and user namespaces map container root to an unprivileged host user.
    • For untrusted code, add a stronger sandbox, such as gVisor or Kata Containers.

    Go to the module

  426. Docker, containerd, runc, OCI. Who actually runs a container?

    Docker and Kubernetes Containers vs virtual machines Junior Concept

    Show answer

    A layered stack. The docker CLI (command-line interface) talks to dockerd, the Docker daemon, which hands containers to containerd, a container runtime that pulls images and supervises containers. containerd starts runc, the low-level runtime that creates the namespaces and cgroups and starts the process. The OCI (Open Container Initiative) standardizes the image format and the runtime, so an image built by Docker runs on containerd, CRI-O or Podman alike.

    • Kubernetes talks to containerd or CRI-O through the CRI (Container Runtime Interface).
    • Kubernetes 1.24 removed dockershim, so Docker Engine is no longer a Kubernetes runtime, but Docker-built images still run.
    • Podman runs the same images without a daemon.

    Go to the module

  427. Can you run a Windows container on a Linux host, or a Linux container on Windows?

    Docker and Kubernetes Containers vs virtual machines Junior Concept

    Show answer

    Not directly, because a container uses the host's kernel and makes its system calls. A Linux container needs a Linux kernel, and a Windows container a Windows kernel. Docker Desktop on Windows and macOS runs Linux containers inside a small Linux VM. The CPU architecture must match too: an arm64 image does not run on an amd64 host without emulation, which is why images are published for several platforms.

    • Image, kernel and CPU architecture must agree.
    • Multi-platform images hold one variant per architecture, and the runtime picks the right one.
    • docker buildx build --platform linux/amd64,linux/arm64 builds both.

    Go to the module

  428. When would you still choose a VM over a container?

    Docker and Kubernetes Containers vs virtual machines Junior Design

    Show answer

    When the workload needs what a shared kernel cannot give: another operating system or kernel version, custom kernel modules, or strong isolation between tenants who do not trust each other, such as running customer code. Also for legacy software that expects a whole machine, with init systems, many processes and local state. For packaging and running your own stateless services, containers win on density, speed and portability.

    • Different OS or kernel means a VM.
    • Hostile multi-tenancy means a VM boundary, or a micro-VM per container.
    • In practice it is both, containers inside VMs.

    Go to the module

  429. What is the difference between a Docker image and a container?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Comparison

    Show answer

    An image is a read-only template: a stack of layers holding a filesystem, built from a Dockerfile, plus metadata such as the command to run. A container is a running instance of an image: the runtime adds a thin writable layer on top and starts the process in its own namespaces. Many containers can run from one image and share its layers. Delete a container and its writable layer goes with it, so data that must survive belongs in a volume.

    • Image is to container as class is to object.
    • Layers are content-addressed and shared between images and containers.
    • Images are immutable; build a new image instead of changing a running container.
    • Tags name an image and can move; a digest pins one exact image.

    Go to the module

  430. How do image layers and the build cache work?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Concept

    Show answer

    Each Dockerfile instruction that changes files, such as RUN, COPY and ADD, adds a layer. When building, the builder reuses a cached layer if the step before it was cached and the instruction is unchanged; for COPY and ADD the copied files' checksums must match too. The first step that misses runs again, and so does every step after it. So order instructions from least to most often changed: base image, dependencies, then source.

    • A cache miss cascades to every later instruction.
    • RUN apt-get update alone is cached forever; combine it with the install in one RUN.
    • .dockerignore keeps target/, .git/ and secrets out of the context and the cache key.

    Go to the module

  431. What is a multi-stage build, and why use one?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Concept

    Show answer

    A Dockerfile with several FROM lines. Earlier stages hold the build tools: a JDK (Java Development Kit), Maven and the source, which compile the jar. The last stage starts from a small runtime base, such as a JRE, and copies only the artifact with COPY --from. Only the last stage becomes the image, so it is several times smaller, has fewer packages to patch and no source code or build secrets, while the build itself stays reproducible in one file.

    • Name stages with AS and copy from them by name.
    • docker build --target build stops at a stage, for tests or debugging.
    • BuildKit builds independent stages in parallel and skips unused ones.

    Go to the module

  432. What makes a good Docker image for a Java service?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Design

    Show answer

    A multi-stage build that ships a JRE, not a JDK, from a small, maintained base with a pinned version. Order layers for the cache, with dependencies before code, or use Spring Boot's layered jar. Run as a non-root user, start java with the exec form of ENTRYPOINT so it receives SIGTERM, and size the heap with -XX:MaxRAMPercentage rather than a fixed -Xmx. Keep secrets out of the image, scan it for CVEs (Common Vulnerabilities and Exposures), and deploy by digest.

    • Buildpacks, with mvn spring-boot:build-image, or Jib build a good image without a Dockerfile.
    • A HEALTHCHECK or Kubernetes probes, backed by the Actuator health endpoint.
    • Distroless or Alpine bases shrink the image; jlink can build a custom, smaller JRE.

    Go to the module

  433. What is the difference between CMD and ENTRYPOINT?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Comparison

    Show answer

    ENTRYPOINT is the executable the container runs; CMD gives its default arguments, or the whole default command when there is no ENTRYPOINT. Arguments after the image name in docker run replace CMD, while ENTRYPOINT is only replaced with --entrypoint. Write both in exec form, a JSON array, so the process is PID (process ID) 1 and gets signals; the shell form wraps it in /bin/sh -c.

    • ENTRYPOINT java -jar app.jar with CMD --spring.profiles.active=prod gives a fixed program with overridable flags.
    • COPY copies local files; ADD also fetches URLs and unpacks archives, so prefer COPY.
    • RUN runs at build time; CMD and ENTRYPOINT run when the container starts.

    Go to the module

  434. Why should production not deploy the latest tag?

    Docker and Kubernetes Images, layers and the Dockerfile Junior Scenario

    Show answer

    Because a tag is a movable name. latest, or even 1.4, can point to a different image tomorrow, so two nodes pulling the same tag may run different code, and a rollback to latest rolls back nothing. Tag every build with an immutable version, such as the Git commit or a release number, and pin deployments to that tag or, better, to the image digest, sha256:..., which identifies exactly one image.

    • A digest is a hash of the image manifest; it cannot change.
    • Kubernetes pulls a latest tag on every start by default, an imagePullPolicy of Always.
    • Base images in FROM can be pinned by digest too, with a bot to update them.

    Go to the module

  435. How do you persist data in Docker, given that containers are disposable?

    Docker and Kubernetes Volumes, ports and networks Junior Concept

    Show answer

    Keep it out of the container's writable layer, which is deleted with the container. Mount storage instead. A named volume is managed by Docker, lives outside any container and survives removal and image upgrades, so it suits databases. A bind mount maps a host directory into the container, which suits local configuration and source code during development. A tmpfs mount keeps files in memory only. In production, managed databases and object storage often replace local volumes altogether.

    • Writable layer for scratch files only; it dies with docker rm.
    • Named volumes for data the app owns, such as a database's files.
    • Bind mounts tie a container to the host's paths, fine on a laptop, fragile in production.
    • docker rm -v or docker volume prune deletes volumes; plain docker rm keeps named ones.

    Go to the module

  436. What does -p 8080:80 do, and how is it different from EXPOSE?

    Docker and Kubernetes Volumes, ports and networks Junior Comparison

    Show answer

    -p 8080:80 publishes the container's port 80 on port 8080 of the host: Docker sets up NAT (network address translation) rules so traffic to the host's port 8080 reaches the container. The first number is the host port, the second the container port. EXPOSE in a Dockerfile only documents which port the app listens on; it publishes nothing. Containers on the same network reach each other on container ports without any mapping.

    • -p 127.0.0.1:5432:5432 publishes only to the host itself, not the whole network.
    • -P publishes every exposed port on a random host port.
    • Two containers can both use port 80 inside; only host ports must be unique.

    Go to the module

  437. How do two containers talk to each other?

    Docker and Kubernetes Volumes, ports and networks Junior Concept

    Show answer

    Put them on the same user-defined network, created with docker network create or by Compose. Docker gives that network an embedded DNS (Domain Name System) server, so each container is reachable by its name, or a network alias, on its container port: orders connects to postgres:5432. The default bridge has no name resolution, so containers there must use IP addresses, which change. Containers on different networks cannot reach each other at all unless one joins both.

    • Use the container port, not the published host port.
    • Networks isolate groups of containers, such as a frontend network and a backend network.
    • The host network mode shares the host's network stack; none disables networking.

    Go to the module

  438. A service works from your IDE but fails in a container with "Connection refused" to localhost:5432. Why?

    Docker and Kubernetes Volumes, ports and networks Junior Scenario

    Show answer

    Because a container has its own network namespace. From the IDE, localhost is your machine, where the database's published port 5432 listens. Inside the container, localhost is the container itself, and nothing listens on 5432 there. Run both containers on one user-defined network and point the service at the database container's name and container port, postgres:5432, passed through an environment variable such as SPRING_DATASOURCE_URL.

    • Published ports are for the host and outside callers, not for container-to-container traffic.
    • Keep connection details in configuration, so one image runs everywhere.
    • Check with getent hosts or nslookup from inside the container.

    Go to the module

  439. What is Docker Compose for, and where does it stop being the right tool?

    Docker and Kubernetes Docker Compose Junior Concept

    Show answer

    Compose runs a multi-container application on one host from a single declarative file, compose.yaml: the services, their images or builds, ports, environment, volumes, networks and start order. One command, docker compose up, creates the project network and volumes and starts everything; docker compose down removes it. It shines for local development, CI (continuous integration) and small single-host deployments. It does not schedule across machines, replace failed nodes or roll out updates; that is Kubernetes' job.

    • Each project gets its own default network, so services reach each other by service name.
    • Named volumes keep data across down and up; down -v deletes them.
    • The same file can run a whole local stack for a new teammate in one command.
    • Override files and profiles adapt one file to local, CI and demo setups.

    Go to the module

  440. What is the difference between depends_on and a healthcheck in Compose?

    Docker and Kubernetes Docker Compose Junior Comparison

    Show answer

    depends_on sets the start order: Compose starts the dependency before the service, and by default it only waits until the dependency's container has started. A healthcheck is a command Docker runs inside a container, such as pg_isready, that marks it healthy once it passes. Combined, with depends_on and condition: service_healthy, Compose waits until the dependency is actually ready. The app should still retry connections, because a dependency can restart later.

    • Conditions are service_started, the default, service_healthy and service_completed_successfully.
    • service_completed_successfully waits for a one-off job, such as a migration, to exit 0.
    • Kubernetes has no depends_on; readiness probes and retries do this job there.

    Go to the module

  441. In Compose, how do services find each other, and where does their data go?

    Docker and Kubernetes Docker Compose Junior Concept

    Show answer

    Compose creates a network for the project, named after its folder, such as shop_default, and attaches every service to it. Docker's embedded DNS (Domain Name System) resolves each service name, so orders connects to postgres:5432 on the container port. Data goes in named volumes declared under volumes:, created once per project as shop_pgdata and kept across down and up. Ports listed under ports: are published to the host only for outside callers.

    • Scaled services, docker compose up --scale orders=3, share one name that resolves to every replica.
    • Container names are generated, so address services by service name.
    • Bind mounts in compose.yaml use paths relative to the file.

    Go to the module

  442. Docker Compose or Kubernetes, when would you use each?

    Docker and Kubernetes Docker Compose Junior Comparison

    Show answer

    Compose describes containers on one host and starts them; when that host dies, everything dies. It is ideal for development, CI and small internal tools. Kubernetes runs containers across a cluster and keeps a desired state: it reschedules failed pods, scales replicas, rolls out new versions, load balances through Services and injects configuration and secrets. That power costs complexity, so a single small service rarely needs it, while a fleet of microservices usually does.

    • Compose has no self-healing across machines, no rolling updates and no autoscaling.
    • Many teams use Compose locally and Kubernetes in staging and production.
    • Kompose converts a Compose file to Kubernetes manifests as a starting point only.

    Go to the module

  443. What are the components of the Kubernetes control plane, and what does each one do?

    Docker and Kubernetes Kubernetes architecture Mid-level Concept

    Show answer

    Four main ones. The API server is the front door: every client and component talks to it, and it validates and stores objects. etcd is the consistent key-value store that holds the whole cluster state; only the API server touches it. The scheduler assigns new Pods to nodes, by their resource requests and constraints. The controller manager runs control loops, Deployment, ReplicaSet, node and others, that keep the actual state matching the desired one. A cloud controller manager adds load balancers and volumes from the cloud provider.

    • Components never call each other; they watch the API server and write back to it.
    • etcd is the only stateful part; back it up, or the cluster forgets everything.
    • Production runs three or five control plane members so etcd keeps a majority if one fails.
    • Managed services such as EKS (Elastic Kubernetes Service), AKS (Azure Kubernetes Service) and GKE (Google Kubernetes Engine) run the control plane for you.

    Go to the module

  444. What runs on every worker node?

    Docker and Kubernetes Kubernetes architecture Mid-level Concept

    Show answer

    Three components besides your Pods. The kubelet, the node agent, watches the API server for Pods bound to its node, has the container runtime start them, runs their liveness and readiness probes and reports status. The container runtime, containerd or CRI-O, pulls images and runs containers through the CRI (Container Runtime Interface). kube-proxy programs iptables or IPVS rules so Service IPs reach ready Pods. A CNI (Container Network Interface) plugin gives every Pod its own IP.

    • The kubelet restarts failed containers locally, without asking the control plane.
    • DaemonSets run one Pod per node, for log shippers, monitoring agents and the network plugin.
    • Nodes report their capacity and conditions, such as memory pressure, through the kubelet.

    Go to the module

  445. What happens, step by step, when you run kubectl apply -f deployment.yaml?

    Docker and Kubernetes Kubernetes architecture Mid-level Scenario

    Show answer

    kubectl sends the manifest to the API server, which authenticates you, authorizes the request with RBAC (role-based access control), runs admission controllers, validates it and stores the Deployment in etcd; kubectl prints created. Then watchers react. The Deployment controller creates a ReplicaSet, and the ReplicaSet controller creates the Pods. The scheduler binds each Pod to a node. The kubelet on that node has the runtime pull the image and start the containers, then reports Running and Ready.

    • created means stored, not running; follow with kubectl rollout status.
    • Each step is a separate component reacting to a change it watches.
    • kubectl get events shows each step as it happens.

    Go to the module

  446. Kubernetes is called declarative. What does that mean in practice?

    Docker and Kubernetes Kubernetes architecture Mid-level Concept

    Show answer

    You describe the desired state, 3 replicas of this image with these resources, and the cluster works out how to get there and keeps it there. Each controller runs a reconciliation loop: observe the actual state, compare it with the desired one, act to close the gap, repeat. Kill a Pod and the ReplicaSet controller creates another; lose a node and its Pods are recreated elsewhere. You never say start this container on that machine.

    • Desired state lives in objects; actual state is reported in their status fields.
    • Loops are level-based, not event-based, so a missed event is fixed on the next pass.
    • Operators extend the same pattern to your own resources, such as a PostgreSQL cluster.

    Go to the module

  447. What is etcd, and what happens if you lose it?

    Docker and Kubernetes Kubernetes architecture Mid-level Concept

    Show answer

    etcd is a distributed, strongly consistent key-value store that holds every Kubernetes object: Deployments, Pods, Services, ConfigMaps, Secrets and the nodes themselves. It replicates with the Raft protocol and needs a majority of its members to accept writes. Lose quorum and the API server can no longer change anything; lose its data without a backup and the cluster forgets every workload, even though containers may still run on the nodes for a while.

    • Back up etcd with etcdctl snapshot save, and test the restore.
    • Secrets are stored base64-encoded unless encryption at rest is enabled.
    • Large or chatty objects slow etcd and the whole control plane.

    Go to the module

  448. The whole control plane goes down for ten minutes. What happens to your running application?

    Docker and Kubernetes Kubernetes architecture Mid-level Scenario

    Show answer

    It keeps serving. Running containers belong to the kubelets and the runtime on each node, and existing Service routing rules stay in place, so traffic flows. What stops is change: no deployments, no scaling, no scheduling of new Pods, and no rescheduling if a node dies. A crashed container is still restarted by its own kubelet. When the control plane returns, controllers reconcile whatever drifted in the meantime.

    • The data plane, nodes and Pods, keeps running without the control plane.
    • The autoscaler cannot react, so a traffic spike is not absorbed.
    • Managed control planes run on several zones to avoid this outage.

    Go to the module

  449. What is the difference between a Pod and a container?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Comparison

    Show answer

    A container is one isolated process from one image. A Pod is the smallest thing Kubernetes schedules: a group of one or more containers that always run together on the same node and share a network namespace, so one IP address and localhost, plus the volumes the Pod declares. Usually a Pod holds one application container, sometimes with helpers, such as an init container that runs first or a sidecar that ships logs or proxies traffic. Pods are disposable; controllers replace them.

    • Containers in a Pod reach each other on localhost and must not share a port.
    • Kubernetes schedules, scales and restarts Pods, not single containers.
    • A Pod gets a new IP every time it is recreated, so callers use a Service.
    • Scale an app by adding Pods, not containers inside one Pod.

    Go to the module

  450. What is the difference between a Deployment and a ReplicaSet?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Comparison

    Show answer

    A ReplicaSet does one thing: keep a given number of identical Pods, matched by a label selector, running. A Deployment manages ReplicaSets to add rollouts. When you change its Pod template, such as the image tag, it creates a new ReplicaSet and shifts Pods from the old one to the new one step by step, keeping old ReplicaSets at zero replicas so you can roll back. You create Deployments; you almost never create a ReplicaSet yourself.

    • The ReplicaSet name carries a hash of the Pod template, orders-56fff5d9f5.
    • Scaling a Deployment changes the replicas of its current ReplicaSet.
    • revisionHistoryLimit, 10 by default, sets how many old ReplicaSets are kept.

    Go to the module

  451. When would you use a StatefulSet instead of a Deployment?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Comparison

    Show answer

    When each replica needs an identity of its own: databases, Kafka brokers, ZooKeeper or Elasticsearch nodes. A StatefulSet names its Pods db-0, db-1, db-2 and keeps those names across restarts, gives each its own PersistentVolumeClaim from volumeClaimTemplates that follows it to any node, gives each a stable DNS (Domain Name System) name through a headless Service, and starts, updates and stops them in order. Stateless services, where any replica can serve any request, belong in a Deployment.

    • Scale-down removes the highest ordinal first and keeps its PVC (PersistentVolumeClaim).
    • Pod management policy Parallel drops the ordered start when it is not needed.
    • A StatefulSet does not replicate data; the application or an operator must.

    Go to the module

  452. What are init containers and sidecar containers?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Concept

    Show answer

    Init containers run one after another, each to completion, before the app containers start: waiting for a dependency, running a migration or fetching configuration into a shared volume. If one fails, the kubelet retries it and the app never starts. Sidecars run beside the app for its whole life, sharing its network and volumes: log shippers, service mesh proxies, metrics adapters. Since Kubernetes 1.29 a sidecar is declared as an init container with restartPolicy: Always, so it starts first and stops last.

    • Init containers keep setup tools out of the application image.
    • Native sidecars do not block a Job from completing.
    • Every container in the Pod counts toward its resource requests.

    Go to the module

  453. You delete a Pod that belongs to a Deployment. What happens?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Scenario

    Show answer

    The Pod is sent SIGTERM, given its grace period, 30 seconds by default, and removed. Meanwhile its ReplicaSet controller sees one Pod fewer than desired and creates a replacement at once; the scheduler places it, possibly on another node. The new Pod has a new name, a new IP and an empty filesystem, apart from volumes it mounts. To really remove it, scale the Deployment down or delete the Deployment.

    • Deleting Pods by hand is a quick restart; kubectl rollout restart does it for all Pods, gradually.
    • Anything written inside the old container is lost.
    • The Service stops sending traffic to the old Pod as soon as it starts terminating.

    Go to the module

  454. Besides Deployments and StatefulSets, which workload types does Kubernetes offer, and when do you use them?

    Docker and Kubernetes Pods, ReplicaSets and Deployments Mid-level Concept

    Show answer

    A DaemonSet runs one Pod on every node, or every matching node, for node agents such as log collectors, monitoring exporters and the network plugin. A Job runs Pods until a task completes successfully, with retries, such as a migration or a batch import. A CronJob creates Jobs on a schedule, such as a nightly report. A bare Pod is for experiments only, because nothing recreates it.

    • Jobs set completions, parallelism and backoffLimit.
    • CronJobs need concurrencyPolicy to avoid overlapping runs.
    • DaemonSets follow new nodes automatically.

    Go to the module

  455. What is the difference between ClusterIP, NodePort and LoadBalancer Services?

    Docker and Kubernetes Services and Ingress Mid-level Comparison

    Show answer

    Each builds on the previous one. ClusterIP, the default, gives a set of Pods a stable virtual IP and DNS name reachable only inside the cluster, for service-to-service calls. NodePort also opens the same port, from 30000 to 32767, on every node, so outside clients can reach the Service through any node's IP. LoadBalancer also asks the cloud provider for an external load balancer with a stable IP that forwards to those node ports, one per Service.

    • All three select Pods by label and send only to ready ones.
    • port is what callers use, targetPort where the container listens.
    • For many HTTP services, an Ingress or Gateway shares one load balancer.
    • ExternalName maps a name to an outside DNS name, and headless Services, clusterIP None, return Pod IPs directly.

    Go to the module

  456. What is an Ingress, and why does it need an Ingress controller?

    Docker and Kubernetes Services and Ingress Mid-level Concept

    Show answer

    An Ingress is a set of HTTP routing rules: for host shop.example.com, send /api/orders to the Service orders and / to web, with TLS from this Secret. The object does nothing alone. An Ingress controller, such as ingress-nginx, Traefik or a cloud provider's, is a set of Pods behind one LoadBalancer that watches Ingress objects and configures itself to apply them. The newer Gateway API splits the same job into GatewayClass, Gateway and HTTPRoute objects.

    • ingressClassName picks which controller handles an Ingress.
    • The controller usually sends traffic straight to Pod IPs from the EndpointSlices.
    • Annotations configure controller-specific behavior, such as timeouts and rewrites.

    Go to the module

  457. How does a request from the internet reach a Pod?

    Docker and Kubernetes Services and Ingress Mid-level Scenario

    Show answer

    DNS resolves the public host name to a cloud load balancer, created by the ingress controller's LoadBalancer Service. The load balancer forwards to the ingress controller's Pods, usually through node ports. The controller terminates TLS, matches the Ingress rule by host and path and picks the backend Service. It sends the request to one of that Service's ready endpoints, a Pod IP and targetPort; inside the cluster, kube-proxy's rules do the same for calls to a Service IP.

    • Only Pods passing their readiness probe are endpoints.
    • Pod IPs are routable across nodes thanks to the CNI (Container Network Interface) plugin.
    • Each hop can fail independently: DNS, load balancer, Ingress rule, selector, readiness, port.

    Go to the module

  458. Pods already have IP addresses. Why do you need a Service?

    Docker and Kubernetes Services and Ingress Mid-level Concept

    Show answer

    Because Pod IPs are not stable. Pods are replaced on every deploy, crash or reschedule, each time with a new IP, and there are several of them. A Service gives the group one stable virtual IP and DNS name, keeps an up-to-date list of the ready Pods matching its selector, in EndpointSlices, and spreads connections across them. Callers depend on the name orders, never on which Pods exist right now.

    • The selector decides membership; readiness decides who receives traffic.
    • A Service balances connections, not requests, so long-lived connections can stick to one Pod.
    • Changing Pods never changes the Service's IP.

    Go to the module

  459. How does one service find another inside the cluster?

    Docker and Kubernetes Services and Ingress Mid-level Concept

    Show answer

    Through cluster DNS, CoreDNS. Every Service gets the name name.namespace.svc.cluster.local, and each Pod's resolver searches its own namespace first, so a Pod in shop calls http://orders, and a Pod in another namespace calls http://orders.shop. The name resolves to the Service's virtual IP, or for a headless Service to the Pod IPs. No registry such as Eureka is needed; Spring Boot just reads the URL from configuration.

    • Cross-namespace calls need the namespace in the name.
    • StatefulSet Pods get their own names, db-0.db.shop.svc.cluster.local.
    • Kubernetes also injects ORDERS_SERVICE_HOST variables, but only for Services that existed first.

    Go to the module

  460. Calls to a Service fail although its Pods are running. How do you debug it?

    Docker and Kubernetes Services and Ingress Mid-level Scenario

    Show answer

    Work from the Service to the Pods. kubectl get endpointslices for the Service: if it lists no addresses, either the selector does not match the Pods' labels, compare with kubectl get pods --show-labels, or the Pods are not Ready, so read their readiness probe in kubectl describe pod. If addresses are listed, check that targetPort is the port the container listens on, then call a Pod IP directly from a debug Pod to split network problems from app problems.

    • Empty endpoints mean selector or readiness, almost always.
    • A wrong targetPort gives connection refused with endpoints present.
    • Network policies can block traffic that everything else allows.

    Go to the module

  461. How do you inject configuration into an application running on Kubernetes?

    Docker and Kubernetes ConfigMaps and Secrets Mid-level Concept

    Show answer

    Keep it out of the image and put it in ConfigMaps, for plain settings, and Secrets, for credentials. A Pod consumes them in two ways: as environment variables, one key with valueFrom or all keys with envFrom, read once when the container starts; or as a volume, where each key becomes a file that the kubelet updates within about a minute of an edit. Spring Boot binds both: SPRING_DATASOURCE_URL by relaxed binding, files through spring.config.import=configtree:.

    • One image for every environment; only the ConfigMaps and Secrets differ.
    • Variables need a rollout to change; files update in place, but the app must reread them.
    • Files mounted with subPath never update.
    • Command-line arguments in the Pod spec can also reference variables, as $(VAR).

    Go to the module

  462. Are Kubernetes Secrets encrypted?

    Docker and Kubernetes ConfigMaps and Secrets Mid-level Concept

    Show answer

    Not by default. A Secret's values are base64-encoded, which anyone can decode, and stored in etcd as they are. Protection comes from elsewhere: enable encryption at rest in the API server, ideally with a KMS (key management service) provider, restrict who can get Secrets with RBAC, and keep them out of Git. Many teams keep the real values in an external store, such as Vault or a cloud secret manager, synced by the External Secrets Operator or mounted by the Secrets Store CSI driver.

    • Anyone allowed to create a Pod in a namespace can mount its Secrets.
    • Secret volumes are tmpfs, so values are not written to the node's disk.
    • Managed clusters often encrypt etcd at rest, but base64 is still all the API returns.

    Go to the module

  463. You changed a ConfigMap, but the running service still uses the old value. Why, and what do you do?

    Docker and Kubernetes ConfigMaps and Secrets Mid-level Scenario

    Show answer

    If the service reads it from environment variables, they were copied when its containers started and never change, so it needs new Pods: kubectl rollout restart. To make changes roll out by themselves, version the ConfigMap, orders-config-v8, mark it immutable and reference the new name from the Deployment, or add a checksum of the config as a Pod template annotation, as Helm charts do. Either changes the template, so a rollout starts, and rollback restores the old config.

    • Immutable ConfigMaps and Secrets also reduce load on the API server.
    • Mounted files do update, but most apps read configuration once at startup.
    • A change through a rollout is gradual, and a bad value fails readiness instead of the whole fleet.

    Go to the module

  464. What is the difference between a ConfigMap and a Secret?

    Docker and Kubernetes ConfigMaps and Secrets Mid-level Comparison

    Show answer

    Both are key-value objects that Pods consume as variables or files. A Secret is meant for sensitive data: it is base64-encoded, can be encrypted at rest, is kept in memory, on tmpfs, when mounted, has typed variants for TLS (Transport Layer Security) certificates and registry credentials, and is usually locked down by RBAC more tightly. A ConfigMap holds plain settings and is readable by anyone with access to the namespace. Each is limited to 1 MiB.

    • kubernetes.io/tls and kubernetes.io/dockerconfigjson are common Secret types.
    • stringData accepts plain text and the API stores it base64-encoded.
    • Neither is meant for large files or binaries; use a volume or object storage.

    Go to the module

  465. What is the difference between liveness, readiness and startup probes?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Comparison

    Show answer

    They answer different questions and trigger different actions. Liveness asks whether the container is broken beyond repair; failing it, the kubelet restarts the container. Readiness asks whether it can serve traffic now; failing it, the Pod leaves its Service's endpoints, and nothing restarts. Startup asks whether a slow app has finished starting; until it passes, the other two do not run, so liveness cannot kill a booting JVM. Each can be an HTTP, TCP (Transmission Control Protocol), gRPC or command check.

    • Liveness checks the app itself, never a database or another service.
    • Readiness may include dependencies, so an outage only stops traffic.
    • Spring Boot exposes /actuator/health/liveness and /actuator/health/readiness for exactly this.
    • Tune periodSeconds and failureThreshold so one slow check does not trigger an action.

    Go to the module

  466. What is the difference between resource requests and limits?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Comparison

    Show answer

    A request is what the scheduler reserves for the container on a node: a Pod only lands where the requests fit, and the HPA measures utilization against them. A limit is the most it may use, enforced by cgroups at run time. Past its CPU limit a container is throttled; past its memory limit it is killed, OOMKilled. Requests and limits together set the QoS (quality of service) class, which decides who is evicted first when a node runs short.

    • Guaranteed QoS, requests equal to limits, is evicted last.
    • Memory limit equal to the request avoids surprise kills from overcommitted nodes.
    • CPU limits often cause throttling at peaks; many teams set only a CPU request.

    Go to the module

  467. A Pod shows OOMKilled with exit code 137. What does it mean, and how do you fix it?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Scenario

    Show answer

    The container's processes used more memory than its limit, and the kernel's OOM (out of memory) killer ended them with SIGKILL, so 128 plus 9 is 137; the kubelet then restarts it. It is not a Java OutOfMemoryError, which is thrown inside a JVM whose heap is full. For a JVM, the usual cause is a heap sized near the limit, leaving no room for metaspace, threads and direct buffers. Size the heap with -XX:MaxRAMPercentage, around 75, or raise the limit.

    • kubectl describe pod shows Last State Terminated, Reason OOMKilled.
    • A node under memory pressure can also evict Pods, which looks different, as Evicted.
    • Native Memory Tracking shows where the non-heap memory goes.

    Go to the module

  468. How does the Horizontal Pod Autoscaler decide how many replicas to run?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Concept

    Show answer

    Every 15 seconds the HPA (Horizontal Pod Autoscaler) reads a metric, usually average CPU use as a percent of the Pods' requests, from the metrics API served by metrics-server. It computes desired replicas as current replicas times current value divided by target, rounded up, ignores changes within a 10 percent tolerance, clamps the result between minReplicas and maxReplicas, and updates the Deployment. Scaling down waits through a 5-minute stabilization window, so short dips do not remove Pods.

    • Without CPU requests on the Pods, CPU utilization cannot be computed.
    • Custom or external metrics, such as queue length, scale on demand directly; KEDA builds on this.
    • The cluster autoscaler adds nodes when new Pods do not fit.

    Go to the module

  469. What should you watch out for when running a JVM in a container?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Concept

    Show answer

    Memory and CPU sizing. JVMs since JDK 10 and 8u191 read the cgroup limits, but the default heap is a quarter of the limit, so set -XX:MaxRAMPercentage, typically 75, leaving room for metaspace, threads and buffers. The CPU count comes from the CPU limit and sizes GC (garbage collection) threads; under 2 CPUs or about 1.8 GB the JVM falls back to the Serial collector. Start java as PID (process ID) 1 so it receives SIGTERM.

    • Never set -Xmx equal to the memory limit; the JVM (Java Virtual Machine) needs room beyond its heap.
    • -XX:ActiveProcessorCount overrides the CPU count when limits mislead the JVM.
    • JVM startup and warm-up interact with probes and autoscaling; use a startup probe.

    Go to the module

  470. How would you design the probes for a Spring Boot service that depends on PostgreSQL and Kafka?

    Docker and Kubernetes Probes, resources and autoscaling Mid-level Design

    Show answer

    Liveness on /actuator/health/liveness, which reflects only the application's own state, so a dependency outage never restarts it. Readiness on /actuator/health/readiness, including the database if requests cannot be served without it, so an outage takes Pods out of rotation. A startup probe with enough failureThreshold to cover the slowest cold start. Keep checks cheap, with timeouts below periodSeconds, and do not make readiness depend on something every replica shares unless you accept all of them leaving together.

    • Kafka consumers keep working without traffic, so readiness matters less for them.
    • All replicas unready at once means the Service has no endpoints, a deliberate trade-off.
    • Test probes by killing dependencies in staging.

    Go to the module

  471. What is the difference between a rolling update, a blue/green deployment and a canary release?

    Docker and Kubernetes Deployment strategies Mid-level Comparison

    Show answer

    A rolling update, the Deployment default, replaces Pods a few at a time, bounded by maxSurge and maxUnavailable, so it needs little extra capacity but v1 and v2 serve together for a while. Blue/green runs the new version as a full second copy, tests it, then switches all traffic at once; rollback is switching back, at the cost of double capacity. A canary sends a small share of traffic to the new version, checks its metrics, and widens step by step, so a bad release reaches few users.

    • All three need readiness probes, so traffic only reaches Pods that can serve.
    • Recreate stops all old Pods first, with downtime, for versions that must never overlap.
    • Every strategy shares the database, so schema changes must suit both versions.
    • Canary and blue/green need extra tooling, such as Argo Rollouts, Flagger or a service mesh.

    Go to the module

  472. A release goes wrong in production. How do you roll back on Kubernetes?

    Docker and Kubernetes Deployment strategies Mid-level Scenario

    Show answer

    Fastest is kubectl rollout undo: the Deployment keeps old ReplicaSets, up to revisionHistoryLimit, 10 by default, and scales the previous one back up as a rolling update, with no rebuild. With Helm, helm rollback to an earlier revision. With GitOps, revert the commit, and the controller applies the old version, which keeps Git the source of truth; an undo done by hand would be overwritten at the next sync. Rollback only works if the database schema still suits the old version.

    • kubectl rollout history shows revisions; annotate change-cause to make them readable.
    • A rollout that stalls fails after progressDeadlineSeconds, 600 by default, but is not undone automatically.
    • Expand-and-contract schema changes keep every release reversible.

    Go to the module

  473. What are Helm and GitOps, and how do they fit together?

    Docker and Kubernetes Deployment strategies Mid-level Concept

    Show answer

    Helm is a package manager for Kubernetes: a chart is a set of templated manifests, values files fill them per environment, and each install or upgrade is a numbered release you can roll back. GitOps is an operating model: the desired state of the cluster lives in Git, and an agent in the cluster, such as the continuous delivery tools Argo CD or Flux, continuously pulls it and reconciles the cluster to match. They combine well: Argo CD can render Helm charts from Git.

    • With GitOps, every change is a reviewed commit, and rollback is git revert.
    • The CI (continuous integration) pipeline needs no cluster credentials; the agent pulls instead.
    • Drift, a change made by hand, is reported or undone automatically.

    Go to the module

  474. How do you make a rolling update of a Spring Boot service truly zero-downtime?

    Docker and Kubernetes Deployment strategies Mid-level Design

    Show answer

    Traffic must only reach Pods that can serve and must drain from Pods that stop. Give it a readiness probe, so new Pods get traffic only once started; maxUnavailable 0 and maxSurge 1, so capacity never drops; graceful shutdown with a preStop sleep of a few seconds, so endpoints update before the app stops; and a PodDisruptionBudget for node drains. Keep APIs and database schemas backward compatible, since old and new versions serve side by side.

    • A startup probe protects a slow JVM (Java Virtual Machine) start from liveness kills.
    • minReadySeconds catches Pods that crash right after turning ready.
    • Watch the error rate during the rollout and stop it if it climbs.

    Go to the module

  475. What is the difference between IaaS, PaaS, SaaS and serverless?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Comparison

    Show answer

    They differ in how much of the stack the provider runs. With IaaS you rent virtual machines, networks and disks, and you install, patch and scale everything on them. With PaaS you hand over your app, a jar or an image, and the platform runs the OS (operating system), runtime and instances. With SaaS you use finished software and manage only your data and users. Serverless, or FaaS, runs your code per event, scales to zero and bills per call. More provider work means less control and more lock-in.

    • Draw the stack, from network to data, and show where each model draws the line.
    • IaaS gives the most control and the most operations; SaaS the least of both.
    • Serverless means no servers to manage and pay per use, not no servers at all.
    • Data and access are the customer's in every model.
    • Name one product per model, such as EC2 (Elastic Compute Cloud), App Service, Lambda and Microsoft 365.

    Go to the module

  476. What is the shared responsibility model?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Concept

    Show answer

    The split of security duties between provider and customer. The provider secures the cloud itself: data centers, hardware, the hypervisor and the software of the managed services. The customer secures what they put in the cloud: identities and permissions, data and its encryption, network rules, and, on IaaS, the guest OS, runtime and app. The line moves up as you move from IaaS to SaaS, but identities and data always stay with the customer.

    • Security of the cloud is the provider's; security in the cloud is yours.
    • Most cloud breaches are customer misconfigurations, such as public buckets and leaked keys.
    • Compliance is shared too: the provider's audit reports cover only its half.

    Go to the module

  477. What does serverless really mean? Is it only functions?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Concept

    Show answer

    Serverless means you never manage, size or patch servers: the platform allocates capacity per request, scales to zero when idle and bills for actual use. Functions, such as AWS (Amazon Web Services) Lambda, are the best-known kind, but serverless containers such as Cloud Run, serverless databases such as DynamoDB or Aurora Serverless, and managed queues follow the same model. The servers exist; they are simply the provider's.

    • Scale to zero and pay per use are the defining traits.
    • Limits come with it, such as cold starts, execution time caps and vendor-specific events.
    • Best for spiky or event-driven work; steady high load is often cheaper on containers.

    Go to the module

  478. A team of four must ship a Spring Boot API in a month. Which service model would you pick?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Design

    Show answer

    A managed platform: PaaS or serverless containers, such as App Service, Cloud Run or Elastic Beanstalk, with a managed database. Four people cannot also run patching, scaling and monitoring for virtual machines, and the platform gives health checks, rolling deploys and autoscaling for free. I would move down to IaaS only for a hard need: special hardware, an OS-level agent, or a cost at scale that a platform cannot match.

    • Start from the team's operational capacity, not from maximum control.
    • Package the app as a container image, so moving between platforms stays cheap.
    • Revisit the choice when load, cost or compliance needs change.

    Go to the module

  479. Moving up the stack reduces operations but increases lock-in. How do you limit lock-in?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Scenario

    Show answer

    Keep the expensive-to-move parts portable and accept lock-in where it pays. Package services as standard container images, use open protocols and engines, such as PostgreSQL, Kafka and OpenTelemetry, and keep provider SDKs (software development kits) behind your own interfaces, as in hexagonal architecture. Write the infrastructure as code. Then a managed queue or function is a contained choice: the business logic does not know which cloud runs it.

    • Lock-in is a cost to weigh, not a rule to avoid every managed service.
    • Data gravity, egress fees and identity integration lock you in more than compute does.
    • Multi-cloud for its own sake usually doubles the work and keeps the weakest common features.

    Go to the module

  480. A critical OpenSSL vulnerability is published. Who patches it on IaaS, on PaaS and on SaaS?

    Cloud Service models: IaaS, PaaS, SaaS, FaaS Junior Scenario

    Show answer

    It depends on where OpenSSL lives. On IaaS the guest OS is yours: you patch the image and roll the instances. On PaaS or FaaS the platform patches the OS and runtime it provides, often without you doing anything. On SaaS the provider patches everything. But a copy bundled inside your own artifact, such as in a container image or a jar, is yours in every model, so you still rebuild and redeploy.

    • Find the layer first, then the owner.
    • Container images carry their own OS libraries, so you patch them even on managed platforms.
    • Automate it with image scanning and regular rebuilds.

    Go to the module

  481. What is the difference between a region and an availability zone?

    Cloud Regions, zones and high availability Junior Comparison

    Show answer

    A region is a geographic area, such as Frankfurt or Ireland, with its own independent copy of the provider's services. An availability zone is one or more data centers inside a region, with separate power, cooling and network, a few kilometers from the others and linked by fast, low-latency connections. Spreading a service over two or three zones survives a data center failure with synchronous replication; surviving the loss of a whole region needs a second region.

    • Zones in a region are close enough for synchronous replication, around a millisecond apart.
    • Regions are far apart and independent, so copies between them are asynchronous.
    • Pick a region for latency to users, data residency law, price and the services it offers.
    • Most managed services are zonal or regional; know which, because it decides what a failure takes down.

    Go to the module

  482. What is the difference between high availability and disaster recovery?

    Cloud Regions, zones and high availability Junior Comparison

    Show answer

    HA (high availability) keeps a service running through common failures, such as a crashed instance, a failed disk or a lost zone, automatically and within seconds to a minute, with redundancy across zones. DR (disaster recovery) restores service after a rare, large loss, such as a whole region, a corrupted database or a deleted account, within agreed targets, from backups or replicas in another region. HA is measured in uptime; DR in RTO and RPO.

    • HA is automatic and continuous; DR is a plan you trigger and rehearse.
    • Replication is not a backup; a bad delete replicates instantly, so DR needs point-in-time backups too.
    • A DR plan that was never tested is a hope, not a plan.

    Go to the module

  483. What are RTO and RPO, and how do they drive the design?

    Cloud Regions, zones and high availability Junior Concept

    Show answer

    The RTO (recovery time objective) is the longest downtime the business accepts after a disaster; the RPO (recovery point objective) is the most data, measured in time, it accepts to lose. RPO decides how data is copied: nightly backups give up to 24 hours, continuous asynchronous replication seconds, synchronous replication zero. RTO decides how ready the second site is: rebuilt from scratch, prepared, or already serving.

    • Lower targets cost more, so set them per service with the business, not one for everything.
    • RPO is about data copies; RTO about ready infrastructure and a rehearsed runbook.
    • Measure both in a game day; the real numbers are usually worse than the plan.

    Go to the module

  484. What disaster recovery strategies exist, from cheapest to most resilient?

    Cloud Regions, zones and high availability Junior Concept

    Show answer

    Four, in order of cost. Backup and restore: copy backups to another region and rebuild there, hours of RTO. Pilot light: replicate the data continuously and keep the infrastructure as code ready but scaled to zero, tens of minutes. Warm standby: a small, running copy of the whole stack, scaled up on failover, minutes. Multi-site active-active: every region serves traffic all the time, near-zero RTO and RPO, but with multi-region writes and the highest cost.

    • Match the strategy to each service's RTO and RPO, not to the most critical one.
    • Infrastructure as code makes the cheaper strategies fast, because rebuilding is a script.
    • Active-active needs data designed for it, such as conflict-free writes or a global database.

    Go to the module

  485. VMs, managed containers, managed Kubernetes or functions. How do you choose?

    Cloud Compute options Mid-level Comparison

    Show answer

    By how much I must control against how much I want to operate. VMs (virtual machines) give a full OS and bill every hour, with patching and scaling on me. Managed Kubernetes runs the control plane, but workloads, node pools and upgrades stay mine; it pays off for many services and a platform team. Managed containers, such as Cloud Run, take an image and scale it, even to zero. Functions run code per event, idle for free, within hard limits. I pick the most managed option the workload fits.

    • Name the trade-off, control against operations work and idle cost.
    • Map each option to a product, such as EC2 (Elastic Compute Cloud), Cloud Run, EKS (Elastic Kubernetes Service) and Lambda.
    • Containers are the portable middle; the same image runs on Cloud Run, Kubernetes or a VM.
    • State function limits, such as a 15-minute cap on Lambda, cold starts and payload size.

    Go to the module

  486. What is a cold start, and why does it hurt Java the most?

    Cloud Compute options Mid-level Concept

    Show answer

    A cold start is the delay when a request finds no ready instance, so the platform must create one: start a micro-VM or container, start the runtime, and run the app's initialization before the handler. It happens on scale-out and after idle periods with scale to zero. The JVM (Java Virtual Machine) adds class loading and interpreted code before the JIT warms up, and frameworks such as Spring build a context at startup, so seconds are common.

    • Warm requests reuse the environment and skip all of it.
    • Fixes are snapshots such as SnapStart, native images, lighter frameworks, more memory or a minimum warm instance.
    • Measure the p99, because the average hides cold starts.

    Go to the module

  487. Which workloads fit functions badly?

    Cloud Compute options Mid-level Design

    Show answer

    Long-running jobs past the time cap, 15 minutes on Lambda; steady high traffic, where per-call billing costs more than containers; latency-critical paths that cannot absorb cold starts; work needing local state, large memory, GPUs or long-lived connections such as WebSockets; and high-concurrency calls into a relational database, where each copy opens its own connections and exhausts the pool. They fit short, stateless, event-driven and spiky work.

    • Put a connection proxy, such as RDS (Relational Database Service) Proxy, between many function copies and a database.
    • Split long jobs into steps, or run them as container jobs.
    • Watch fan-out costs, since retries and recursive triggers multiply invocations.

    Go to the module

  488. How does managed Kubernetes differ from a managed container service such as Cloud Run or Fargate?

    Cloud Compute options Mid-level Comparison

    Show answer

    Both run your container images. Managed Kubernetes gives the full Kubernetes API: you write manifests, run controllers and operators, manage node pools or pay for an autopilot mode, plan version upgrades and own the security of what runs on the cluster. A managed container service hides the cluster: you deploy an image with a few settings, such as CPU, memory, concurrency and scaling limits, and the provider runs everything else. Less flexibility, far less to operate.

    • Kubernetes wins on ecosystem, portability and fine control over scheduling and networking.
    • Managed containers win on time to production and operations cost for few services.
    • Both bill differently, nodes against CPU-seconds, so compare at your real load.

    Go to the module

  489. A Spring Boot function on Lambda takes 6 seconds on its first request. What do you try, in order?

    Cloud Compute options Mid-level Scenario

    Show answer

    First measure Init Duration in the REPORT log. Then the cheap fixes: more memory, since it also buys CPU; fewer dependencies and lazy initialization; tier-1 JIT through JAVA_TOOL_OPTIONS; clients built once in static fields. Then SnapStart, which restores an initialized snapshot in well under a second. If that is not enough, provisioned concurrency, a container with a warm minimum instance, or a GraalVM native image, each with its own cost.

    • Measure before changing anything, and track p99 after each change.
    • SnapStart needs published versions and care with uniqueness after restore.
    • Provisioned concurrency removes cold starts but bills for idle capacity.

    Go to the module

  490. How do the four compute options bill you, and how does that change the design?

    Cloud Compute options Mid-level Concept

    Show answer

    VMs bill per second or hour while running, whatever the load, so you right-size, autoscale and reserve capacity for the baseline. Managed Kubernetes bills its nodes plus a control plane fee, so bin-packing Pods onto fewer nodes matters. Managed containers bill CPU and memory per second of request handling, often scaling to zero. Functions bill per invocation and per millisecond of memory, so idle is free but every retry and every slow dependency costs money.

    • Steady load favors reserved or committed capacity; spiky load favors pay per use.
    • Egress, load balancers and logs can cost more than the compute itself.
    • Tag resources and review the bill per service; cost is a design input.

    Go to the module

  491. What is the difference between vertical and horizontal scaling? Which do you prefer for a web service?

    Cloud Scalability and load balancing Mid-level Comparison

    Show answer

    Vertical scaling gives one machine more CPU and memory; horizontal scaling adds more identical machines behind a load balancer. Vertical is simple and needs no code change, but it has a ceiling, usually a restart per resize, and stays a single point of failure. Horizontal scales almost without limit and survives an instance failure, but only if the service is stateless. For a web service I scale horizontally, and use vertical scaling for what resists it, such as a primary database.

    • Horizontal needs stateless instances, a load balancer and health checks.
    • Autoscaling adds and removes instances between a minimum and a maximum, on a metric.
    • The bottleneck moves downstream, usually to the database, when instances multiply.
    • Databases scale vertically first, then with read replicas, caching and sharding.

    Go to the module

  492. What does it mean for a service to be stateless, and why does it matter for scaling?

    Cloud Scalability and load balancing Mid-level Concept

    Show answer

    A stateless service keeps nothing between requests in its own memory or disk that a later request needs: no in-memory sessions, carts, uploaded files or local caches it relies on. All such state lives in shared stores, such as a database, Redis or object storage. Then any instance can serve any request, so the load balancer can spread traffic freely and the platform can add, replace or remove instances at any time without losing data.

    • Stateless does not mean no state; it means the state lives outside the instance.
    • Local caches are fine if losing them only costs speed, not correctness.
    • Stateless instances also make rolling deploys and crash recovery trivial.

    Go to the module

  493. How does auto-scaling work, and which metric would you scale on?

    Cloud Scalability and load balancing Mid-level Concept

    Show answer

    An auto-scaling group keeps between a minimum and a maximum number of identical instances. A policy watches a metric and adds instances when it passes a target and removes them when it falls, with cooldowns so it does not flap. Target tracking on average CPU is the default, but for I/O-bound Java services I prefer requests per instance, queue depth for workers, or latency, because CPU can stay low while requests pile up.

    • Scaling takes minutes, so add scheduled or predictive scaling before known peaks.
    • Keep the minimum at two or more, spread over zones, for availability.
    • New instances must pass a readiness check before getting traffic.

    Go to the module

  494. What is the difference between a layer 4 and a layer 7 load balancer?

    Cloud Scalability and load balancing Mid-level Comparison

    Show answer

    A layer 4 load balancer works on TCP (Transmission Control Protocol) or UDP connections: it sees IP addresses and ports and forwards whole connections, so it is very fast, keeps the client IP and handles any protocol. A layer 7 load balancer terminates HTTP and TLS and reads each request: it routes by host, path, header or cookie, rewrites and redirects, and balances each request, not each connection. Web APIs usually sit behind layer 7; gRPC, databases and extreme throughput behind layer 4.

    • Layer 7 adds features, such as path routing, TLS termination, a web application firewall and sticky cookies.
    • Layer 4 balances long-lived connections once, which can leave load uneven.
    • Behind layer 7, read the client IP from X-Forwarded-For.

    Go to the module

  495. What are sticky sessions, and why are they a problem?

    Cloud Scalability and load balancing Mid-level Concept

    Show answer

    Sticky sessions, or session affinity, make the load balancer send every request from one client to the same instance, usually with a cookie, so a session kept in that instance's memory keeps working. The problem is that the state still lives on one instance: scale-in, a deploy or a crash loses those sessions, load becomes uneven when heavy users stick to one instance, and new instances take traffic slowly. Prefer a shared session store or tokens.

    • Stickiness hides statefulness; it does not remove it.
    • Spring Session with Redis, or signed tokens such as JWTs (JSON Web Tokens), make instances interchangeable.
    • Use affinity only as a performance hint, never for correctness.

    Go to the module

  496. How does a load balancer decide which instance gets a request, and when to stop sending it traffic?

    Cloud Scalability and load balancing Mid-level Concept

    Show answer

    It sends traffic only to targets that pass health checks, a regular HTTP or TCP probe, and removes a target after several failures in a row. Among healthy targets it applies an algorithm: round robin, least outstanding requests or connections, weighted, or a hash of the client for affinity. Least outstanding requests suits services with uneven request costs. In Spring Boot, point the check at the readiness endpoint, not at a check of every dependency.

    • A deep health check that fails on a slow database removes every instance at once.
    • Slow start ramps traffic to a new instance while its JVM warms up.
    • Health checks decide traffic; the auto-scaling group decides replacement.

    Go to the module

  497. What is the difference between object, block and file storage?

    Cloud Storage and managed databases Mid-level Comparison

    Show answer

    Object storage, such as S3 (Simple Storage Service), keeps whole objects under keys in a flat namespace, reached over HTTP: practically unlimited, durable across zones and cheap, but you replace objects rather than edit them in place. Block storage, such as EBS (Elastic Block Store), is a raw disk attached to one machine, formatted with a filesystem: lowest latency, for boot disks and self-run databases. File storage, such as EFS (Elastic File System), is a shared network filesystem that many machines mount at once.

    • Object storage fits uploads, backups, logs, static sites and data lakes.
    • A block volume lives in one zone and attaches to one VM (virtual machine) at a time, as a rule.
    • File storage fits legacy apps that need a shared POSIX directory, at a higher price.
    • Cost and throughput differ by tier, such as standard against archive classes, or IOPS (input/output operations per second) for disks.

    Go to the module

  498. When would you choose a NoSQL database over a relational one?

    Cloud Storage and managed databases Mid-level Comparison

    Show answer

    Relational databases give a schema, joins, constraints and ACID (atomicity, consistency, isolation, durability) transactions, and answer queries nobody planned; they are the right default for business data such as orders and accounts. I choose NoSQL when the access pattern is known and simple, such as reading a cart or a session by key, at a scale or latency where one relational primary struggles, or when the data is naturally a document or a time series. You design NoSQL tables around queries, not entities.

    • Key-value and document stores scale horizontally by partition key.
    • A bad partition key creates hot partitions that throttle.
    • Many systems use both, such as PostgreSQL for orders and DynamoDB or Redis for carts.

    Go to the module

  499. What are read replicas, and what do you have to watch out for?

    Cloud Storage and managed databases Mid-level Concept

    Show answer

    Read replicas are copies of a primary database that receive its changes asynchronously and serve read-only queries, so reads scale out while all writes still go to the primary. They suit reports, searches and read-heavy pages. The catch is replica lag: a replica may be seconds behind, so a user who just wrote may not see their own change. Route reads that need fresh data to the primary, and monitor lag.

    • Replicas scale reads, not writes; writes need a bigger primary, sharding or another store.
    • In Spring, route readOnly transactions with a routing data source behind a lazy connection proxy.
    • A replica can be promoted on failover, but with asynchronous lag it may lose the last writes.

    Go to the module

  500. What does a managed database such as RDS give you, and what stays your job?

    Cloud Storage and managed databases Mid-level Concept

    Show answer

    RDS (Relational Database Service) and its equivalents run the hardware, install and patch the engine, take automated backups with point-in-time recovery, replace failed hosts, fail over to a standby in another zone and add read replicas on request. You still design the schema and indexes, tune queries, size the instance and connections, choose the maintenance window, control network access and users, encrypt data, and test restores.

    • Point-in-time recovery restores to any second in the retention window.
    • A restore creates a new instance, so the app needs a new endpoint or a DNS (Domain Name System) switch.
    • Slow queries remain your problem on any managed service.

    Go to the module

  501. What is a VPC, and how would you lay one out for a typical web service?

    Cloud Networking: VPC, subnets and security Mid-level Design

    Show answer

    A VPC is your own isolated private network in a region, with an address range such as 10.0.0.0/16 split into subnets, one set per availability zone. For a web service I use three tiers: public subnets with only the load balancer and NAT gateways, private app subnets for the instances or containers, and private data subnets for databases with no route out. Route tables decide what is public; security groups allow only named callers between tiers.

    • Spread every tier over at least two zones for availability.
    • Choose a range that will not overlap other VPCs or offices you may connect later.
    • Reach managed services privately with VPC endpoints instead of over the internet.
    • Peering or a transit gateway connects VPCs; a VPN connects offices.

    Go to the module

  502. What makes a subnet public or private?

    Cloud Networking: VPC, subnets and security Mid-level Concept

    Show answer

    Only its route table. A public subnet has a route for 0.0.0.0/0 to an internet gateway, so resources in it with a public IP can be reached from the internet and reach it directly. A private subnet has no such route: its resources have only private addresses, and to call out they route through a NAT (network address translation) gateway, which sits in a public subnet and lets replies back in but never new inbound connections.

    • Public is a routing property, not a firewall setting.
    • NAT gateways are per zone and cost money per hour and per gigabyte; endpoints can save traffic.
    • An ALB (Application Load Balancer) faces the internet and terminates TLS (Transport Layer Security), so the instances do not have to.

    Go to the module

  503. What is a security group, and how does it differ from a network ACL?

    Cloud Networking: VPC, subnets and security Mid-level Comparison

    Show answer

    A security group is a stateful firewall attached to each network interface: you write allow rules only, and replies to an allowed connection are let back in automatically. Rules can name another security group as the source, such as "5432 from the app group", so they follow instances as they scale. A network ACL (access control list) is stateless and applies to a whole subnet, with numbered allow and deny rules and both directions written out, including ephemeral reply ports.

    • Most designs rely on security groups and leave ACLs at their default.
    • Reference groups instead of IP ranges between tiers.
    • Default to deny inbound; open only the ports a caller needs.

    Go to the module

  504. How does an app in a private subnet reach the internet and managed services such as S3 or a secrets store?

    Cloud Networking: VPC, subnets and security Mid-level Concept

    Show answer

    For the internet, through a NAT gateway in a public subnet: the private route table sends 0.0.0.0/0 to it, and the external service sees the NAT's public IP, which is handy for allowlists. For managed services such as S3 (Simple Storage Service) or Secrets Manager, through VPC endpoints: traffic stays on the provider's network, needs no NAT, avoids its data charges and can be limited with an endpoint policy.

    • Gateway endpoints for S3 and DynamoDB are free; interface endpoints cost per hour.
    • Without a route out, a private subnet cannot reach a managed API at all.
    • Keep egress rules narrow, such as port 443 only.

    Go to the module

  505. What is the principle of least privilege, and how do you apply it in the cloud?

    Cloud IAM, least privilege and secrets Mid-level Concept

    Show answer

    Every identity, person or workload, gets only the permissions its job needs, on only the resources it touches, for only as long as it needs them. In practice: one role per service, with policies naming specific actions and resource ARNs (Amazon Resource Names) instead of wildcards; no shared users; temporary credentials from roles instead of long-lived keys; separate accounts for production; and regular reviews that remove permissions nobody used. Then a compromised service can only do a small amount of damage.

    • Start from nothing and add what the service needs; IAM denies by default.
    • Use access logs and the provider's unused-permission reports to tighten policies over time.
    • Guardrails such as organization policies and permission boundaries cap even administrators.
    • Least privilege applies to networks and databases too, not only to IAM.

    Go to the module

  506. What is the difference between an IAM user and a role? Which should an application use?

    Cloud IAM, least privilege and secrets Mid-level Comparison

    Show answer

    A user is a long-lived identity with a password or access keys that never expire unless rotated. A role has no credentials of its own: a trusted principal, such as an EC2 (Elastic Compute Cloud) instance, a Kubernetes service account, a pipeline through OIDC (OpenID Connect) or a person through single sign-on, assumes it and receives temporary credentials from STS (Security Token Service) that expire within hours. Applications should always use roles, so there is no key to leak or rotate.

    • The trust policy says who may assume a role; the permission policies say what it may do.
    • Azure's managed identities and GCP (Google Cloud Platform) service accounts with workload identity play the same part.
    • Keep users, if any, for people behind multi-factor sign-in.

    Go to the module

  507. Where should an application's secrets live, such as database passwords and API keys?

    Cloud IAM, least privilege and secrets Mid-level Design

    Show answer

    In a managed secrets store, such as AWS Secrets Manager, Azure Key Vault or GCP Secret Manager, encrypted with a key from a KMS (key management service). The app reads them at startup or through a cached client, authorized by its own role, so nothing secret sits in the repository, the image or plain environment files. The store gives access policies per secret, audit logs and rotation. Better still, remove secrets entirely: roles for cloud APIs, IAM authentication for databases.

    • Never commit secrets; scan every push for them.
    • Rotation works only if the app rereads the secret, so cache with a refresh.
    • Kubernetes Secrets are base64, not encryption; sync from a store with an operator.

    Go to the module

  508. A role has an Allow and a Deny that both match a request. What happens, and why?

    Cloud IAM, least privilege and secrets Mid-level Concept

    Show answer

    The request is denied. IAM starts from an implicit deny, so nothing is allowed until a statement allows it. It then checks every applicable policy: an explicit Deny anywhere wins over every Allow; otherwise one matching Allow is enough. A statement matches only if the action and the exact resource fit, so s3:ListBucket on a bucket needs the bucket's ARN, while object actions need bucket/*.

    • Explicit deny, then allow, then the default deny.
    • Organization policies and permission boundaries can only narrow what a policy allows.
    • Resource policies, such as a bucket policy, add another place where a Deny can come from.

    Go to the module

  509. What is the difference between a queue and a topic?

    Cloud Managed messaging Mid-level Comparison

    Show answer

    A queue is point-to-point: producers put messages in, and competing consumers take them out, each message processed by one consumer and then deleted. It spreads work and buffers bursts. A topic is publish-subscribe: each message is copied to every subscriber, so several services react to one event without the producer knowing them. Often you combine them: a topic fans out to a queue per subscriber, so each service gets every message and keeps it while it is down.

    • Queue means work distribution; topic means event notification.
    • Consumers of a queue scale by adding instances; subscribers of a topic are different services.
    • Delivery is usually at least once, so consumers must be idempotent.
    • Products include SQS (Simple Queue Service) and SNS (Simple Notification Service), Service Bus, and GCP (Google Cloud Platform) Pub/Sub.

    Go to the module

  510. SQS and SNS, Pub/Sub or Service Bus, or managed Kafka. How do you choose?

    Cloud Managed messaging Mid-level Comparison

    Show answer

    Managed queues and topics are serverless: no capacity to plan, pay per message, built-in dead-letter queues, delays and filters, and messages deleted once consumed. They suit commands, jobs and event notifications. Managed Kafka, such as MSK (Managed Streaming for Apache Kafka), Event Hubs or Confluent Cloud, is a retained, partitioned log: high throughput, ordering per key, replay and stream processing, with partitions and consumer groups to design. Choose Kafka when consumers need history or very high volume.

    • Service Bus adds sessions, transactions and duplicate detection, closer to a traditional broker.
    • Kafka keeps data after reading; queues forget it.
    • Cost differs, per request against cluster hours or throughput units.

    Go to the module

  511. How do managed queues handle a consumer that crashes in the middle of a message?

    Cloud Managed messaging Mid-level Concept

    Show answer

    A received message is not deleted, only hidden for a visibility timeout, or locked on Service Bus. The consumer deletes or completes it when done. If it crashes or the timeout passes, the message becomes visible again and is redelivered, so delivery is at least once. After a set number of attempts, the maxReceiveCount on SQS, the message moves to a DLQ (dead-letter queue), so one poison message does not block or loop forever.

    • Set the visibility timeout above the longest processing time, or extend it while working.
    • FIFO (first in, first out) queues keep order per message group and remove duplicates within five minutes.
    • Alarm on dead-letter queue depth and redrive after fixing the bug.

    Go to the module

  512. Why put a queue behind each subscription of a topic instead of subscribing services directly?

    Cloud Managed messaging Mid-level Design

    Show answer

    Because a topic pushes and does not store. If an HTTP subscriber is down or slow, the topic retries for a while and then drops or dead-letters the message, and a burst hits every subscriber at full speed. A queue per subscriber keeps that service's copy until it is ready, lets it consume at its own pace and scale workers on queue depth, and gives each service its own retries and dead-letter queue, isolated from the others.

    • The producer publishes once; adding a subscriber is adding a queue and a subscription.
    • Subscription filters send each queue only the messages its service wants.
    • Each queue's consumer still must be idempotent.

    Go to the module

  513. What are the stages of a CI/CD pipeline for a Java service, from commit to production?

    Cloud CI/CD and infrastructure as code Mid-level Design

    Show answer

    On every push: compile, unit tests and static analysis, the fastest feedback. Then build one container image, tag it with the commit hash, scan it and push it to a registry. Deploy that exact image to a test environment for integration and contract tests, and plan any infrastructure change for review. After the merge, promote the same image to staging, then to production behind an approval or automatically, with a canary or rolling deploy, smoke tests and a ready rollback.

    • Order the stages by speed so failures surface early.
    • Build once, promote the same artifact; never rebuild per environment.
    • Configuration differs per environment, the artifact does not.
    • Rollback means redeploying the previous tag, which must stay available.

    Go to the module

  514. What is Terraform, and how does it work?

    Cloud CI/CD and infrastructure as code Mid-level Concept

    Show answer

    Terraform is an IaC (infrastructure as code) tool: you declare resources, such as networks, databases and queues, in HCL (HashiCorp Configuration Language) files, and providers translate them into cloud API calls. It keeps a state file mapping your code to real resources. terraform plan compares code, state and reality and shows what would be added, changed or destroyed; terraform apply makes it so. State lives in a shared, locked backend, and modules package reusable pieces.

    • Declarative, so you describe the end state, not the steps.
    • Works across providers, unlike CloudFormation or Bicep, which are tied to one cloud.
    • Review the plan in the pull request and apply from the pipeline only.

    Go to the module

  515. What is immutable infrastructure?

    Cloud CI/CD and infrastructure as code Mid-level Concept

    Show answer

    Servers and containers are never changed after they are deployed: no SSH fixes, no in-place upgrades, no hand-edited config. To change anything, you build a new image or version from code and replace the old instances with new ones. Every environment then runs exactly what was tested, drift cannot build up, a bad change is rolled back by redeploying the previous image, and any instance can be destroyed and recreated at will.

    • Containers and machine images make it natural; configuration management on live servers is the mutable opposite.
    • State lives outside the instances, in databases and storage, which are changed through migrations.
    • It pairs with blue/green, canary and rolling deploys.

    Go to the module

  516. What is the difference between continuous integration, continuous delivery and continuous deployment?

    Cloud CI/CD and infrastructure as code Mid-level Comparison

    Show answer

    CI (continuous integration) is merging small changes into the main branch often, each one built and tested automatically, so integration problems appear within minutes. CD (continuous delivery) goes further: every change that passes the pipeline is releasable, and production is one approved click away. Continuous deployment removes the click: every passing change goes to production automatically, which requires strong tests, monitoring, feature flags and automated rollback.

    • CI is about the main branch staying healthy.
    • Delivery keeps a human decision; deployment trusts the pipeline.
    • Feature flags separate deploying code from releasing a feature.

    Go to the module

  517. What is a cloud-native application?

    Cloud Twelve-Factor App and cloud native Mid-level Concept

    Show answer

    An application designed to run on elastic, automated infrastructure rather than on a few long-lived servers. In practice it is split into services packaged as containers, runs as stateless, disposable processes that scale out, gets its config from the environment, uses managed backing services, is deployed by an automated pipeline, and is observable through logs, metrics and traces. The Twelve-Factor App, written by Heroku engineers, is the classic checklist for the application side of it.

    • Cloud native is about how the app is built and run, not about which cloud it runs on.
    • Assume any instance can disappear at any time, and design so that it does not matter.
    • Automation, from tests to infrastructure as code, is part of the definition.
    • Spring Boot fits it well, with embedded servers, external config, Actuator and graceful shutdown.

    Go to the module

  518. Which of the twelve factors matter most, and why?

    Cloud Twelve-Factor App and cloud native Mid-level Concept

    Show answer

    Config in the environment, so one artifact serves every environment and no secret sits in code. Build, release, run, so production runs exactly what was tested and rolls back by release. Stateless processes, so instances can scale and be replaced freely. Disposability, so deploys and scale-in drop no requests. Logs as event streams, so the platform collects them. Backing services as attached resources, so a database moves by changing a URL. The others support these six.

    • Each factor answers a concrete failure, such as lost sessions, drifting environments or full disks.
    • Map each to Spring Boot, such as external config, embedded server, graceful shutdown and stdout logging.
    • Newer practice adds telemetry, security and API-first design to the list.

    Go to the module

  519. Why should configuration live in the environment instead of the code? How does Spring Boot support it?

    Cloud Twelve-Factor App and cloud native Mid-level Concept

    Show answer

    Because the same artifact must run in every environment: building one per environment means production runs something never tested, and credentials in the repository leak. So the code holds safe defaults, and each environment provides URLs, credentials and flags as environment variables, mounted files or a config service. Spring Boot reads them in a fixed precedence, with environment variables above application.properties, and relaxed binding maps SPRING_DATASOURCE_URL to spring.datasource.url.

    • The test is whether the code could be open-sourced without leaking anything.
    • Secrets come from a secrets store, injected at run time.
    • Profiles are fine for defaults, but not as the place where production values live.

    Go to the module

  520. What do stateless processes and disposability mean for a Spring Boot service in practice?

    Cloud Twelve-Factor App and cloud native Mid-level Scenario

    Show answer

    Stateless means no instance keeps anything another request needs: HTTP sessions go to Spring Session with Redis or become tokens, uploads go to object storage, and scheduled jobs use a lock such as ShedLock so only one replica runs them. Disposable means it starts in seconds and stops cleanly: server.shutdown=graceful stops new requests and finishes the open ones on SIGTERM, and consumers stop polling and commit before exit. Then the platform may kill any instance at any time.

    • Test it by killing instances during a load test.
    • Long-running work belongs in queues with retries, not in a request thread.
    • Startup time matters for scale-out and recovery, so keep the context lean.

    Go to the module