← All topics
Start ▶
Design patterns
Singleton, Factory, Strategy, Builder and other patterns.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is a design pattern, and why does a developer need one?
A pattern is a proven template for a problem that comes up again and again. It isn't ready-made code, but an idea ("in this situation, structure the code like this") and a shared vocabulary for the team.
2
Which three groups are the GoF patterns divided into? Give one example of each.
Question / Examples — Creational: Who creates the object, and how? / Singleton, Factory Method, Abstract Factory, Builder, Prototype; Structural: How do classes fit together? / Adapter, Decorator, Proxy, Facade, Composite, Bridge, Flyweight; Behavioral: Who does what, who notifies whom? / Strategy, Observer, Template…
3
What's the simplest thread-safe way to write a Singleton in Java?
The simplest way is eager initialization: a private static final field is created when the class is loaded, and the constructor is private. Because the JVM loads a class only once, this is thread-safe.
4
Why do many people consider an enum the most reliable option for a Singleton?
A Singleton written as an enum can't be turned into a second instance through reflection or through serialization, and the JVM guarantees that. The code also fits on one line.
5
When a constructor gets too many parameters, how does the Builder pattern help?
A Builder lets you assemble an object step by step through named methods. Instead of a confusing 8-parameter constructor, you get code that's easy to read and hard to get wrong.
6
What code does Lombok's @Builder annotation actually generate?
@Builder creates a static inner XxxBuilder class inside the class, a setter-style method for every field with the same name, a build() method and a static builder() method. build() calls the all-args constructor.
7
What is the Factory Method pattern, and how does it differ from a plain `new` call?
Factory Method moves object creation into a separate method: the caller doesn't know the concrete class, it only gets the interface. new ties the caller tightly to a concrete class.
8
What advantage do static factory methods like `List.of()` and `Integer.valueOf()` have over constructors?
A static factory method has a name, doesn't have to create a new object every time (it can return one from a cache), and can return an interface or a subclass. A constructor can do none of these.
9
What is the Strategy pattern? Explain it with payment methods.
Strategy puts several ways of doing one job into separate classes and swaps them through a common interface. The main code doesn't know which way was chosen, it just calls the interface.
10
How does the Observer pattern work? Give a real-life example.
When one object (the subject) changes, the other objects subscribed to it (the observers) get notified automatically. The subject doesn't know them specifically: it just tells each one on the list "something happened".
11
What problem does the Adapter pattern solve?
An Adapter connects two interfaces that don't fit together: it "wraps" an existing class in the interface you expect, without changing the class. It's the same idea as a socket adapter.
12
Explain the Decorator pattern using Java I/O classes as the example.
A Decorator wraps an object in another object with the same interface and adds new behavior to it. In Java I/O, BufferedInputStream(new FileInputStream(...)) is exactly that: each layer adds one capability.
13
What is the Facade pattern and when is it useful?
A Facade puts one simple entry point on top of a complex subsystem. The caller works with one method instead of ten classes, and the internal details stay hidden.
14
What is the Proxy pattern? What kinds are there?
A Proxy stands in for the real object and has the same interface, but does its own work before or after passing the call on: checking access, lazy loading, caching or a remote call.
15
What is the Template Method pattern? Show it with a simple example.
In Template Method, the skeleton of an algorithm is written in a final method of the parent class, and some steps are abstract for the subclasses to fill in. The sequence stays fixed, only certain steps change.
16
What is the Command pattern and where is it used?
Command turns a request into an object: "what to do" is gathered into one class. That makes it easy to queue an action, run it later, log it or undo it.
17
What is the Iterator pattern, and how does Java's for-each loop relate to it?
An Iterator gives you a way to walk through a collection's elements one by one without exposing its internal structure. In Java, for-each calls Iterable.iterator() and works through hasNext()/next().
18
Spring beans are singletons by default. Is that the same thing as the GoF Singleton?
No. The GoF Singleton means the class itself enforces a single instance inside the JVM (more precisely, the classloader). A Spring singleton means "one bean per ApplicationContext"; the class itself is ordinary, and you can create as many objects of it as you like with new.
19
What is the "god object" anti-pattern and how do you recognize it?
A god object is one huge class that knows everything and does everything. It has thousands of lines and dozens of dependencies, and any change touches that class.
20
What does the "composition over inheritance" principle mean?
To reuse behavior, instead of inheriting from a class it's better to hold the object you need as a field and delegate to it. Composition makes coupling looser and lets you swap things at runtime.
21
What is wrong with the following lazy Singleton, and how do you fix it?
Two threads can pass the instance == null check at the same time and create two objects. The fixes: the holder idiom, an enum, or double-checked locking with volatile.
22
Decorator and Proxy look very much alike. What is the difference?
Their structure is almost the same: both wrap an object with the same interface. The difference is in intent: a Decorator adds new functionality and is usually assembled as a chain, while a Proxy controls access to the real object (lazy, permissions, cache, remote).
23
How do you tell Adapter and Facade apart? They both "wrap", after all.
An Adapter fits one existing interface to a different, expected interface, and its goal is compatibility. A Facade builds a new, simpler interface on top of a complex system made of several classes, and its goal is simplicity.
24
How can the Strategy pattern be simplified with lambdas in Java 8+, and when do you still need a separate class?
If the Strategy interface has a single abstract method, it's a functional interface, and you can supply the strategy as a lambda or a method reference. But if the strategy has its own state, dependencies or complex logic, a separate class is easier to read and test.
25
How do you prevent required fields from being forgotten when you use a Builder?
The simplest way is to validate in build() and throw an exception with a clear message if something is missing. Stronger options: make the required fields arguments of builder(...), or enforce them at compile time with a "step builder".
26
How can the Observer pattern cause a memory leak?
The subject keeps a strong reference to its listeners. If a listener isn't removed from the list when it's done, the GC can't collect it (or anything it holds). This is called the "lapsed listener" problem.
27
Why does a classic Singleton make code hard to test?
An object obtained through a static getInstance() can't be swapped in a test, its state persists between tests, and the tests affect each other. Because the dependency is hidden, it also isn't visible from the class signature.
28
What is the difference between Factory Method and Abstract Factory?
Factory Method creates one product, and a method (often in a subclass) decides which class it is. Abstract Factory gives an interface that creates a whole family of products that fit together.
29
What is the Prototype pattern, and what traps come with doing it through `clone()` in Java?
Prototype creates a new object by copying an existing sample instead of building it from scratch. clone() in Java makes a shallow copy by default: inner lists and objects stay shared between the two copies.
30
Explain the Chain of Responsibility pattern using the servlet Filter.
A request passes through a series of handlers one after another; each does its own job and then passes it on, or stops the chain itself. Servlet Filters work exactly like this: each filter either calls chain.doFilter() or doesn't.
31
In Spring, how do you inject several strategies through a `Map` and pick one without if-else?
Spring can inject all implementations of one interface as a List<T> or a Map<String, T>; the Map key is the bean name. An even cleaner way is for each strategy to have a method that returns its own type, and to build a map keyed by an enum in the constructor.
32
What is the difference between `@EventListener` and `@TransactionalEventListener` in Spring?
@EventListener runs as soon as the event is published, on the same thread and inside the same transaction. @TransactionalEventListener is tied to the transaction state: by default it's called only after the commit succeeds.
33
Which pattern do the "Template" names in `JdbcTemplate`, `RestTemplate` and `TransactionTemplate` come from, and how do they work?
It's the Template Method idea, but done with a callback instead of inheritance: the template handles the fixed part (opening and closing the resource, translating exceptions), and you supply only the variable step as a lambda.
34
Why isn't `@Transactional` working in this code? Which pattern is it related to?
@Transactional works through a Spring proxy. The call this.saveAll() bypasses the proxy and goes straight to the object itself, so no transaction is opened. This is a natural limitation of the Proxy pattern.
35
Order statuses have multiplied and the code is full of `switch`es. How does the State pattern help here?
The State pattern moves each state into its own class, and that class itself decides which actions are allowed in that state. Then the switch (status) in every method disappears, and invalid transitions are controlled in one place.
36
How is the filter chain in Spring Security structured, and which pattern does it match?
Spring Security plugs in as a single servlet filter (DelegatingFilterProxy → FilterChainProxy), and inside it finds the SecurityFilterChain matching the URL and runs its filters one after another. That's Chain of Responsibility, and the outer hookup is Proxy/Delegate.
37
Which creational pattern are Spring's `@Bean` method and the `FactoryBean` interface examples of, and how do they differ?
Both are Factory: they move the logic for creating a bean out of the container and into your code. A @Bean method is simple and enough in most cases; FactoryBean is for reusable, framework-level, complex creation logic.
38
What is an anemic domain model, and why is it sometimes called an anti-pattern?
In an anemic model, entities are just data boxes with getters/setters, and all the business rules live in services. The problem is that the rules get scattered and an object can easily end up in an invalid state. But in plain CRUD systems it's often a perfectly fine choice.
39
What is the difference between Service Locator and Dependency Injection? Why is calling `applicationContext.getBean()` everywhere a bad habit in Spring?
With a Service Locator, the class asks a central registry for what it needs; with DI, the dependencies are supplied from outside, usually through the constructor. With getBean() a class gets a hidden dependency and it's hard to swap in a test.
40
What is the Null Object pattern? Compare it with `Optional`.
Null Object means returning a real implementation that "does nothing" instead of null, so the caller can keep calling methods without a check. Optional openly shows in the type itself that a value may be absent, and forces the caller to deal with that case.
41
When does Spring AOP create a proxy with a JDK dynamic proxy and when with CGLIB, and what does it affect in practice?
In Spring Boot 2+ the default is proxyTargetClass=true, meaning CGLIB: a subclass of the class is created. A JDK proxy works only through an interface. CGLIB can't wrap a final class or final methods, while a JDK proxy won't let you inject the bean by its concrete class type.
42
Why must the field be `volatile` in double-checked locking? What exactly breaks without it?
instance = new X() is not atomic: allocating memory, running the constructor and writing the reference can be reordered. Without volatile, another thread may see a non-null but not yet fully constructed object and start using it.
43
What happens if a prototype-scoped bean is injected into a singleton bean, and what's the right way to get a new instance each time?
The injection happens only once, when the singleton is created, so the prototype bean effectively becomes a single one too. To get a fresh one on every call, use ObjectProvider<T>, a @Lookup method or a scoped proxy.
44
You need to add a Decorator to a ready-made Spring bean without changing it. What ways do you have to do that?
The simplest is to wrap the original implementation in your own @Bean method and mark it @Primary. To wrap library beans, or many beans the same way, you use a BeanPostProcessor; for cross-cutting concerns an AOP aspect is more convenient.
45
When you use the Command pattern for background jobs, the commands are stored in the database. What problems do you run into and how do you solve them?
A command is no longer in memory: it's stored as JSON and executed at another time, perhaps by a different version of the code. The main problems: the serialization format changing, repeated side effects on re-execution (idempotency), retries on failure, and two workers picking up the same job.
46
Template Method and Strategy often solve the same problem. When does an inheritance-based Template Method become a problem?
Template Method works through inheritance, Strategy through composition. When the hierarchy gets deep, subclasses become tied to the parent class's internal order, and combining two independently varying axes leads to a combinatorial explosion, and that's when you should move to Strategy.
47
In what situations does a classic Singleton still end up as two or more instances?
Uniqueness is only guaranteed within a single classloader. Different classloaders (an app server, hot reload, a plugin system), serialization without readResolve, reflection and a cluster (several JVMs): each of these produces a second instance.
48
What new problems appear when you make an event listener `@Async`?
The listener runs on another thread: the caller's transaction, security context and MDC log context don't carry over, and exceptions don't go back to the publisher. When the application stops, pending events can be lost, and the thread pool can fill up.
49
In Spring Data JPA, how do you write a search with many optional filters using the Specification pattern, and what are its limits?
Specification turns each filter condition into a separate, reusable object and combines them with and/or. In Spring Data, JpaSpecificationExecutor and Specification<T> provide this on top of the Criteria API; you don't need a separate repository method for every combination.
50
How do you tell that a codebase has too many patterns, and how do you remove excess abstraction?
The signs: interfaces with a single implementation, factories that create only one thing, having to open 6–7 files for a simple change, and layers added "because we'll need it in the future". Remove them by inlining in small steps, with tests as a safety net.
51
How do the Unit of Work and Identity Map patterns work in Hibernate's persistence context, and what do they mean in practice?
The session keeps exactly one instance of each entity it loaded, per id (Identity Map), and writes changes to the database not immediately but as one batch at flush time (Unit of Work). That is why a change gets saved even if you never call save(), and why memory grows in a big batch.
52
What patterns is Spring MVC's `DispatcherServlet` built on, and where does knowing that help you?
DispatcherServlet is a front controller: every request comes in through one place. Inside, finding the handler (HandlerMapping), invoking it (HandlerAdapter), and converting arguments and the response (resolvers, HttpMessageConverter) are swappable strategies. You extend Spring MVC through exactly those points.
53
What is the Flyweight pattern, where is it used in the JDK, and what trap does it lead to?
Flyweight saves memory by sharing identical, immutable state among many objects: the object isn't created again, it's returned from a cache. In the JDK, the Integer.valueOf cache, string literals and enums work this way. The trap is that comparing such objects with == works sometimes and fails other times.
54
What patterns is SLF4J built on, and what happens when two logging libraries clash on the classpath?
SLF4J is a facade: your code knows only its API, and Logback or Log4j2 does the actual writing. Bridges like jul-to-slf4j and log4j-to-slf4j are adapters that route other logging APIs into SLF4J. If a bridge and a provider are paired wrongly, logs disappear or an infinite loop appears.
55
How would you write the Composite pattern for a category tree, and where does it show up in Spring itself?
In Composite, a single element and a group of elements are used through the same interface: the caller doesn't care whether it's dealing with a leaf or a whole branch. In Spring, CompositeCacheManager is built this way, and in Micrometer, CompositeMeterRegistry.
56
How do Publisher/Subscriber in Reactive Streams differ from the classic Observer pattern?
In classic Observer, the subject pushes events as fast as it likes, even if the listener can't keep up. In Reactive Streams, the subscriber says how many items it is ready to take with request(n), which is backpressure. On top of that, stream completion and errors are part of the contract.
57
Now that Java 21 has sealed interfaces and `switch` pattern matching, do we still need the Visitor pattern?
In most cases no: a switch over a sealed hierarchy does what Visitor does, a separate operation per type plus compiler-checked exhaustiveness, with less code. Visitor is still the right choice when the hierarchy can't be changed, such as in a library, or when the traversal logic is complex.
58
What is wrong with this value object, and how does it show up in a `Set` or a cache?
A record's equals calls BigDecimal.equals, which also compares the scale: 10.0 and 10.00 are not equal. As a result, the same amount becomes two different keys. You need to normalize the scale in the compact constructor.
59
Two services call each other and you have a circular dependency. How would you resolve it with a mediator or events?
First, I won't hide it with allow-circular-references. Usually I move the shared part of the two services into a third class, or write a use case class (a mediator) that coordinates both. If one side only needs to say "something happened", I break the dependency with an event.
60
You logged the request body in a filter and now the controller gets an empty body. How would you fix it using a decorator?
An InputStream can be read only once. You wrap the request with HttpServletRequestWrapper to build a decorator that keeps the body in memory, or you use Spring's ContentCachingRequestWrapper.
61
What problems come up when you put Lombok's `@Builder` on a JPA entity?
@Builder generates an all-args constructor and removes the no-args constructor, which Hibernate needs. On top of that, the builder leaves collection fields as null and ignores default values set on fields.
62
How do the Repository and DAO patterns differ, and when you write only an interface in Spring Data, where does the implementation come from?
A DAO is a low-level CRUD layer close to the table. A Repository is a collection-like abstraction for domain objects (aggregates). At startup, Spring Data creates a JDK dynamic proxy for your interface, backed by SimpleJpaRepository and by queries derived from method names.
63
Why does Spring Boot provide `RestClient.Builder` as a bean, and what do you lose if you create a client with `RestClient.create()`?
Boot auto-configures the builder and, through customizers, adds message converters, observation (metrics and tracing) and your shared settings to it. The static RestClient.create() or RestClient.builder() bypasses all of that, so outgoing requests show up in neither metrics nor traces.
64
How do you use the Test Data Builder and Object Mother patterns to create objects in tests?
An Object Mother gives you ready-made samples: Orders.paidOrder(). A Test Data Builder starts from sensible defaults, and the test changes only the field that matters to it. I prefer the builder, because the test shows only what it is actually checking.
65
Why wrap an external payment provider's SDK in an adapter, and what happens if you use it directly?
An adapter hides the SDK behind your own interface. Then, if the provider changes or the SDK version changes, only the adapter gets rewritten; the domain and the tests don't know about the SDK classes.
66
How do you notice that a facade service is turning into a god class, and what do you do about it?
The signs: more than 8-10 dependencies in the constructor, a thousand-line class, and this file changes in every PR. A facade should only coordinate; once business rules start piling up inside it, you split it up by responsibility.
67
What is the difference between `Collections.unmodifiableList(list)` and `List.copyOf(list)`, and which pattern is it related to?
unmodifiableList is a read-only proxy (view) wrapped around the original list: you can't modify it, but if the owner of the original list changes it, the change is visible. List.copyOf creates an independent, immutable copy and doesn't accept null elements.
68
A servlet `Filter`, a `HandlerInterceptor` and an AOP aspect all wrap a call. Which job goes where?
A filter works at the servlet level, for every HTTP request, and can wrap and replace the request and response. An interceptor lives inside Spring MVC and knows which controller method will be called. An aspect is independent of HTTP and wraps any bean method.
69
What is wrong with this Spring bean, and how does it show up under load?
In a singleton bean, mutable fields (SimpleDateFormat and currentUser) are shared by all threads. Under parallel requests, dates get formatted wrongly and one user may end up with another user's data.
70
What problems does a Hibernate lazy proxy cause with `equals`, `getClass()` and `instanceof`?
A lazy reference isn't the entity itself but a subclass of it generated by Hibernate. getClass() returns the proxy class, so an equals written with getClass() != o.getClass() says the same row is not equal to itself; in a hierarchy, instanceof misleads you too.
71
If you wrap an external HTTP client with decorators for retry, circuit breaker, timeout and metrics, how does their order matter?
Order changes behavior: if retry is inside the circuit breaker, the breaker counts each attempt separately; if it's outside, retries keep hitting an open breaker. Whether the timeout applies to each attempt or to the total time also comes from the order.
72
When do Spring's in-process events stop being enough, and when do you move to Kafka or an outbox?
In-process events live inside one JVM: if the service dies they are lost, other services don't see them, and there is no backpressure. When losing an event is costly, or when another team's service needs to listen, I move to a broker and an outbox.
73
You need to switch the pricing algorithm at runtime with a feature flag. How do you design the Strategy and roll it out safely?
Both algorithms implement one interface, and a selector returns the strategy based on the flag on each request. First I run the new algorithm in shadow mode and compare results, then I turn it on by percentage.
74
The number of discount rules grew from 5 to 60. Do you choose Strategy, Chain of Responsibility or a rules engine?
If only one rule runs at a time, Strategy. If the rules are applied one after another and affect each other, a chain or pipeline. If the business needs to change rules without a developer, a rules engine or data-driven rules.
75
When is the object pool pattern useful on today's JVM, and when is it harmful?
It is useful for external resources that are expensive to create and limited in number: DB connections, threads, large direct buffers. Pooling ordinary Java objects is usually slower and more error-prone with a modern GC.
76
In code with lots of proxies, decorators and interfaces, what can't the JIT optimize, and how do you measure it?
If a call site has one or two implementations, the JIT inlines it. With many implementations (a megamorphic call site) or calls through reflection, inlining stops. But this difference usually disappears against I/O, so measure with a profiler first.
77
How do you build a state machine for a long-running business process: Spring Statemachine or your own code?
Most of the time I write it myself: the state is a database column, the transition table is in code, and every transition is protected by an optimistic lock. Spring Statemachine makes sense when you need complex hierarchical states, but persisting it and debugging it is harder.
78
How do you choose between orchestration and choreography for a saga, and which classic patterns do they resemble?
Orchestration: a central coordinator commands each step (command + state machine). Choreography: services react to each other's events (observer). With many steps and an order that matters, I choose orchestration; with 2-3 independent reactions, choreography.
79
You put a caching decorator on top of a repository. What can go wrong in production, and how do you prevent it?
The main risks: a stale value staying in the cache because of a transaction rollback or a read before the commit, hundreds of requests hitting the database at once when a popular key expires (a stampede), and a caller mutating a mutable object held in the cache. The fixes are evicting after commit, a single loader, and caching immutable DTOs.
80
What does hexagonal architecture (ports and adapters) look like in a Spring Boot project in practice, and when is it overkill?
The domain and use cases are in the center, and they know only their own interfaces (ports); Spring, JPA, Kafka and HTTP are outer adapters. It pays off in a complex domain and a long-lived system; in a simple CRUD service it just doubles the number of files.
81
How do you design extension points in an internal platform library used by ten teams?
I offer extension through small interfaces (SPIs), each with a clear contract and a default implementation, not through inheritance. To keep teams from depending on internal classes, I keep the public API narrow and close off the rest.
82
How do you compare Java's `ServiceLoader` with Spring Boot auto-configuration for a plugin architecture?
ServiceLoader doesn't depend on any framework and is simple, but it has no DI, conditional loading or ordering. Spring auto-configuration gives you conditions, properties and bean override, but it ties the plugin to Spring.
83
What problems come up when microservices share domain classes through a common "common-model" jar, and how do you get out of it?
A shared jar couples services at the deploy level: if one field changes, every service has to be updated together. The way out is for each service to keep its own model, and for the contract to be shared through a schema (OpenAPI, Avro/Protobuf).
84
When you split up a large monolith with the strangler fig approach, what roles do a proxy and a facade play?
A routing proxy (gateway) goes in front of the monolith, and endpoints are redirected to the new service one by one. Inside the monolith, a facade is the single entry point to the part being extracted: the code is first gathered behind that facade, then moved out.
85
When do you need an anti-corruption layer, and what does it cost?
When an external or legacy system's model differs sharply from your domain and you can't influence it, an ACL translates that model into your own language. The cost is an extra layer, mapping code, and constantly keeping an eye on the differences between the two models.
86
In a large codebase, is it better to handle cross-cutting concerns with AOP or with explicit composition (decorators, interceptors)?
For things that are the same everywhere and don't affect business logic (tracing, metrics, transaction boundaries), AOP is convenient. For things that change behavior (retry, caching, permission checks), I prefer explicit composition: whoever reads the code should see what is happening.
87
When you use the observer pattern at the system level (event-driven architecture), how do you evolve the event schema without breaking consumers?
An event is a public contract, and you don't fully know who is listening. So you make only backward-compatible changes (a new optional field), the schema registry checks compatibility in CI, and a breaking change ships as a new event type or version.
88
When should you actually apply CQRS, and when is it needless complexity?
CQRS pays off when read and write loads, models or scale differ sharply. In plain CRUD, two models, synchronization and eventual consistency only add more bugs.
89
You have 6 pods in a cluster, but the daily settlement job must run in only one place. How do you build a "distributed singleton", and what are the risks?
The options: a lock in the database (ShedLock), leader election (Kubernetes Lease, ZooKeeper), or moving the job to a separate scheduler. The main risk is the lock expiring and two instances running at once, so the job itself must be idempotent too.
90
How does building the Bulkhead pattern with thread pools change in the era of virtual threads?
The classic bulkhead gives each external dependency its own thread pool. With virtual threads, since threads are cheap, you limit the number of concurrent calls with a semaphore instead of a pool: the isolation idea stays, the tool changes.
91
Feature flags have piled up over the years and the code now has hundreds of `if (flags.isOn(...))`. How do you manage this debt across several teams?
When a flag is created, you record its type (release, experiment, ops kill switch, permission), its owner and an expiry date. Expired release flags automatically produce a ticket and a warning, and in code the flag check is gathered at a strategy selection point instead of being scattered through business logic.
92
What do you do so that the architecture rules the team agreed on (layers, patterns) don't erode over time?
I enforce rules in tests, not in documents: with ArchUnit, layer dependencies, naming and forbidden imports are checked in CI. The document (an ADR) answers the question "why".
93
In a multi-tenant system, if you choose a separate database per tenant with `AbstractRoutingDataSource`, what risks do you run into?
The tenant is usually kept in a ThreadLocal, and it can be lost in async calls or leak into the wrong tenant. On top of that, the connection is chosen once at the start of a transaction, and each tenant's own pool multiplies the total number of connections.
94
Should things like retry, mTLS and tracing be done with a decorator inside the library, or through a sidecar/service mesh?
A sidecar is independent of language and framework, and the platform team manages it from one place. A library knows the business context: which request is idempotent, which error is transient. I leave the transport level (mTLS, connections, basic metrics) to the mesh, and semantic decisions (retry, fallback) to the application.
95
What signs tell you your system has turned into a "distributed monolith", and how do you get out of it?
The signs: one feature requires deploying several services together, services call each other in synchronous chains, one service going down stops everything, and there is a shared database or a shared model jar. The way out is redrawing the service boundaries, and sometimes merging services.
96
What patterns are Spring's extension mechanisms (BeanPostProcessor, BeanFactoryPostProcessor, ImportSelector) built on, and what do you learn from them when designing your own framework?
The Spring container gives hooks at specific points in the lifecycle: changing bean definitions (BeanFactoryPostProcessor), wrapping or replacing a finished bean (BeanPostProcessor), and conditionally loading configuration (ImportSelector). The main lesson is that the core stays small and features are added through these hooks.
97
In a payment API, a client times out and resends the request. How do you design idempotency so the money isn't charged twice?
The client gives each operation a unique Idempotency-Key. The server stores the key together with a hash of the request and the result: the first request is executed, repeats get the stored response, and a concurrent repeat waits or gets a 409. The key and the business record are saved in one transaction.
98
Why is writing to the database and then sending a message to Kafka (dual write) unreliable, and what options are there besides a transactional outbox?
You can't write atomically to two systems: if the database commits and Kafka fails, the message is lost; in the opposite case, a message goes out about data that isn't in the database. An outbox turns the two into a single database transaction; the alternatives are CDC directly from the table, or making the event the primary source.
99
You need to add a new field to the following public library class. To avoid breaking the code of everyone who uses the library, do you choose a constructor, a builder or a static factory?
Adding a parameter to a public constructor breaks previously compiled code with a NoSuchMethodError. Adding a new optional field to a builder or a static factory is binary and source compatible, so for a library API I choose those.
100
In a design review, what criteria do you use to answer "do we need a pattern here?"
I start not from the pattern's name but from the axis of change: in which direction and how often the code changes, who changes it, and what a mistake costs. If the pattern makes that change cheaper, I add it; if not, the simple code stays and gets refactored later.
Sign up — studied questions get marked and your progress is saved.