Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at Elm

New

Interview Q&A

17 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Compare TCP and UDP in terms of reliability, ordering, connection setup, and appropriate use cases?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

TCP and UDP are both transport protocols on top of IP, but they make opposite trade-offs. TCP gives you a reliable, ordered byte stream and pays for it with connection setup, per-packet overhead, and head-of-line blocking. UDP gives you datagrams with almost no machinery, and pushes reliability, ordering, and congestion control onto the application if it wants them.

DimensionTCPUDP
ReliabilityEvery byte is acknowledged. Lost segments are retransmitted until delivered or the connection fails.No acknowledgements, no retransmission. A datagram can be lost, duplicated, or arrive corrupted (checksum catches some corruption) and the sender never knows.
OrderingSequence numbers let the receiver reassemble bytes in order. Out-of-order segments are buffered until the gap fills.No sequence numbers. Datagrams arrive in whatever order the network delivers them, or not at all.
Connection setupThree-way handshake before data: SYN, SYN-ACK, ACK. That costs 1 RTT before the first byte, plus state on both ends.None. First datagram goes out immediately. No connection state in the kernel.
Overhead20-byte header minimum, up to 60 with options. ACKs, window updates, congestion control traffic.8-byte header. Nothing else unless the app adds it.
Flow and congestion controlSliding window limits in-flight data; congestion control (CUBIC, BBR) backs off when the network drops packets.None. The sender can flood a bottleneck and cause loss for itself and others.

How TCP actually delivers those guarantees

The handshake is the visible part:

Client                                   Server
  | --- SYN, seq=1000 -----------------> |
  | <--- SYN-ACK, seq=5000, ack=1001 --- |
  | --- ACK, ack=5001 -----------------> |
  | --- data, seq=1001, len=1460 ------> |
  | <--- ACK, ack=2461 ----------------- |

After that, each segment carries a sequence number. The receiver ACKs the next byte it expects. If segment 2461 to 3920 never arrives, the receiver keeps ACKing 2461, the sender's retransmission timer fires (or three duplicate ACKs trigger fast retransmit), and the gap is filled. The application only ever reads a clean stream, because the kernel holds back bytes after the gap.

That buffering is also the main failure mode. One lost segment stalls everything behind it, even if those packets arrived fine. On a 100 ms RTT link with 1% loss, a bulk transfer can collapse to a few Mbps because the congestion window keeps shrinking. That is head-of-line blocking, and it is why latency-sensitive protocols moved away from TCP.

A concrete cost comparison

Take 1 MiB (1,048,576 bytes) over a 1500-byte MTU. TCP leaves 1460 bytes of payload per segment after 20 bytes of IPv4 and 20 bytes of TCP headers, so it needs 719 data segments, plus ACKs roughly every other segment, plus the handshake RTT. UDP leaves 1472 bytes of payload per datagram after 20 bytes of IPv4 and 8 bytes of UDP headers, so it needs 713 datagrams, with zero ACK traffic, but if 1% are lost the application sees holes it must fill itself. For a file download that trade is obviously worth it. For a 20 ms voice packet, waiting for a retransmit means the audio is already stale, so the receiver would rather conceal the loss and play the next packet.

Choosing between them

Use TCP when every byte matters and a small delay is acceptable: HTTP and HTTPS traffic, database connections, SSH, file transfer, payment APIs, anything where a missing or reordered record corrupts state. The kernel handles retries, ordering, and congestion fairness for you.

Use UDP when timeliness matters more than completeness, or when you want to build your own reliability on top: DNS lookups (one small request, retry if no answer in a few seconds), VoIP and video calls (a late packet is useless, so drop it), online games (position updates supersede old ones), live streaming, DHCP, and SNMP. QUIC, which powers HTTP/3, is the interesting middle case: it runs over UDP to escape TCP's head-of-line blocking and to allow 0-RTT resumption, then reimplements reliability, ordering per stream, and congestion control in user space.

The interview follow-up is usually about that last point. UDP does not mean an unreliable application. It means the protocol does not decide for you. If you pick UDP for a use case that needs delivery guarantees, you own sequence numbers, ACKs, retransmission timers, and congestion control, and you will end up reinventing a large part of TCP. Pick it when that control is the point, not when you are hoping the network behaves.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2Can you explain the keyword "volatile" in Java and when it is used?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

volatile is a field modifier that gives you visibility and ordering guarantees from the Java Memory Model, without the mutual exclusion of synchronized. Every write to a volatile field happens-before every subsequent read of that field, so a thread that reads it sees the latest value written by another thread. It also prevents the compiler and CPU from reordering reads and writes around it. It does not make compound operations atomic.

That distinction decides almost every interview follow-up. Use it for a single writer publishing state that other threads only read, or for a stop flag. Do not use it for counter++.

Java
// Java 17, checked against JLS 17 section 17.4
class Worker {
    private volatile boolean running = true;
    private volatile int lastProcessedId = 0;

    void run() {
        while (running) {
            lastProcessedId = processNext();
        }
    }

    void stop() {
        running = false; // visible to run() on another thread
    }
}

Without volatile, the loop above can spin forever. The JIT can hoist running into a register because, from that thread's view, nothing in the loop writes it. The write in stop() may sit in a CPU cache or be reordered with other writes, and the reading thread has no guarantee of ever seeing it. With volatile, the read in while (running) must go to main memory semantics defined by the JMM, and the write in stop() is flushed before any later read can return the old value.

What it guarantees, and what it does not

PropertyvolatilesynchronizedAtomicInteger
Visibility of writesYes, for that fieldYes, for all shared state in the blockYes
Ordering around the accessYes, prevents reordering across itYesYes, for the atomic operation
Atomicity of x++NoYes, inside the blockYes, via incrementAndGet()
Blocking / mutual exclusionNoYesNo

Trace the failure for a counter:

Java
volatile int count = 0;
// Thread A: count++  compiles to read, add, write
// Thread B: count++  compiles to read, add, write

Both threads can read 0, both add 1, both write 1. Final value is 1, not 2. volatile made each individual read and write visible. It did not make the three-step sequence atomic. The fix is AtomicInteger.incrementAndGet() or a lock, depending on whether you need the lock to cover other fields too.

When I would use it in production code

  1. A shutdown or pause flag read in a tight loop, as above. Cheap, no lock contention.
  2. Publishing an immutable object safely. If a field is volatile and points to a fully constructed immutable object, readers see the object as constructed. This is the safe publication pattern.
  3. Double-checked locking for lazy initialisation. The volatile on the holder field prevents a thread from seeing a partially constructed object, which was the classic bug before Java 5.
  4. A status or metrics field written by one thread and polled by a monitor thread, where a slightly stale value is acceptable but an invisible update is not.

When I would not

If two or more fields must change together, volatile on each field does not give you a consistent snapshot. A reader can see the new value of field A and the old value of field B. Use a lock, or publish a new immutable holder object through a single volatile reference so the pair moves atomically.

If the operation is read-modify-write, use Atomic* classes or synchronized. If contention is high and the critical section is short, AtomicInteger usually beats a lock. If the section touches several fields or calls out to other code, a lock is clearer and safer.

One more limit worth naming: volatile applies to fields only. You cannot declare a local variable volatile, and it does not make a non-thread-safe collection safe. A volatile reference to an ArrayList still lets two threads corrupt the list if both mutate it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3What are the core principles of OOP, such as inheritance and polymorphism, and how do you implement them effectively?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

The four principles are encapsulation, abstraction, inheritance, and polymorphism. In practice I treat the first two as the goal and the last two as tools, because inheritance is the one that causes most production damage when it is used as a code-reuse shortcut.

Encapsulation means an object owns its invariants and exposes behaviour, not raw state. Abstraction means callers depend on a narrow interface that hides how that behaviour is implemented. Polymorphism means the same call site works for different implementations behind that interface. Inheritance means a subclass reuses and specialises a parent implementation, and it only works safely when the subclass honours the parent contract.

How I implement it

I start from the interface, not the class hierarchy. In Java 17, for example:

Java
public interface PaymentMethod {
    Money charge(Money amount);
}

public final class CardPayment implements PaymentMethod {
    private final CardGateway gateway;

    public CardPayment(CardGateway gateway) { this.gateway = gateway; }

    @Override
    public Money charge(Money amount) {
        if (amount.isNegative()) throw new IllegalArgumentException("amount");
        return gateway.authorise(amount);
    }
}

public final class Checkout {
    private final PaymentMethod method;
    public Checkout(PaymentMethod method) { this.method = method; }
    public Money pay(Money total) { return method.charge(total); }
}

Checkout never knows whether it holds a card, wallet, or bank transfer. Adding a new method is a new class, not a change to Checkout. That is polymorphism through an interface, and it is testable with a fake that records calls.

For reuse I prefer composition over inheritance. A DiscountPolicy interface composed into OrderService is easier to swap and test than a deep hierarchy of Order, DiscountedOrder, TaxedOrder. Inheritance couples every subclass to every change in the parent, including constructors and protected fields. That coupling is the fragile base class problem: a seemingly safe change to the parent, such as adding a validation step in a setter, silently breaks subclasses that override it.

ApproachReuseCouplingWhen I use it
Interface + compositionBehaviour shared by delegationLow, one interfaceDefault choice for services and strategies
InheritanceImplementation inherited directlyHigh, parent changes rippleA true is-a relationship with a stable contract
Abstract class with template methodShared skeleton, subclass fills stepsMediumFramework code where the flow is fixed and steps vary

Where it breaks

Three failure modes come up in reviews. First, an Liskov substitution violation: a subclass that throws where the parent does not, or that narrows accepted inputs. Callers then cannot trust the interface, and polymorphism stops being safe. I check this by asking whether every subclass can be dropped into every test written against the parent type.

Second, leaky encapsulation: public fields, or getters and setters for every attribute. The object can then be put into an invalid state from outside, for example a negative balance, and the invariant code never runs. I keep fields private, expose intent-revealing methods, and make invalid states unrepresentable where the language allows it, such as returning a Money value object instead of a raw amount.

Third, inheritance used for reuse instead of specialisation. If the honest description is "has a", not "is a", I compose. A Manager that inherits from Employee to reuse a name field but adds reporting behaviour usually ends up with a hierarchy that cannot model a manager who is also an engineer.

In short: design the interface first, implement polymorphism against it, keep state private behind behaviour, and reserve inheritance for the rare case where a subclass genuinely is a subtype and can honour the parent contract in full.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4How does Spring transaction management work in a multi-threaded environment?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

Spring does not make a transaction thread-safe by locking the transaction. It binds the transaction to the current thread. When a @Transactional method is entered, the interceptor asks the PlatformTransactionManager to start a transaction, gets a JDBC Connection from the pool, and stores it in a ThreadLocal held by TransactionSynchronizationManager. Every JdbcTemplate, JpaTransactionManager or EntityManager call on that thread then finds that same connection. Commit or rollback happens when the outermost transactional method exits, and the connection is returned to the pool and the ThreadLocal cleared.

That design is why a transaction cannot cross threads. A second thread has its own ThreadLocal, so it sees no transaction and gets its own connection. If you start work in one thread and continue it in another, the second thread is outside the transaction, even if you pass the service bean around.

Java
@Service
public class OrderService {
  private final JdbcTemplate jdbc;

  @Transactional
  public void placeOrder(long customerId, long amount) {
    jdbc.update("INSERT INTO orders(customer_id, amount) VALUES (?, ?)",
        customerId, amount);
    auditService.record(customerId); // joins this transaction by default
  }
}

auditService.record runs with REQUIRED propagation by default, so it reuses the connection already bound to this thread. No new connection is taken from the pool.

Trace: two threads, one pool of 20

TimeThread AThread BConnection
------------
t0placeOrder starts, tx beginsidleA takes conn 7, bound to A
t1INSERT orders on conn 7placeOrder starts, tx beginsB takes conn 8, bound to B
t2auditService.record reuses conn 7INSERT orders on conn 8no sharing
t3method returns, commit, conn 7 releasedthrows, rollback, conn 8 releasedboth ThreadLocals cleared

If B had been spawned from A with an Executor to do the audit write in parallel, B would not see conn 7. It would take conn 8 and commit independently. A could then roll back while the audit row stays committed. That split is the most common multi-threaded bug I see with @Transactional.

What the interceptor actually controls

@Transactional is a proxy. The call must go through the Spring bean proxy, so self-invocation from inside the same class bypasses it. The interceptor reads the annotation, resolves propagation and isolation, and applies rollback rules: unchecked exceptions roll back, checked exceptions do not unless you set rollbackFor. Read-only hints and timeouts are passed to the transaction manager, which for JDBC sets the connection read-only flag and setQueryTimeout where the driver supports it.

Propagation decides what happens on a nested call:

PropagationNested call behaviourUse case
REQUIREDjoins existing tx, or starts onedefault, audit inside the order
REQUIRES_NEWsuspends current tx, starts a new one on a new connectionaudit that must survive order rollback
MANDATORYfails if no tx existsenforce a caller contract
NOT_SUPPORTEDsuspends tx, runs non-transactionallybulk read that should not hold a connection

REQUIRES_NEW is the usual escape hatch for logging or metrics that must not be lost on rollback. It costs a second pooled connection for the duration, so with a pool of 20 and many concurrent orders you can exhaust the pool faster than the outer transaction count suggests.

Failure modes to name in the interview

  1. Async boundary. @Async, CompletableFuture.supplyAsync, or a @Scheduled method starts with no transaction context. The ThreadLocal is empty in the new thread. Fix it by making the async method its own transactional entry point, or by passing data explicitly and starting a new transaction there. Do not try to propagate the ThreadLocal manually.

  2. Connection leak on thread reuse. If a transaction is not completed, for example an exception escapes a filter that started it manually, the connection stays bound to a pooled servlet thread. The next request on that thread inherits it. Spring clears the binding in a finally block in the interceptor, which is why declarative transactions are safer than manual TransactionTemplate code scattered across threads.

  3. Isolation surprises. Default isolation comes from the database, READ_COMMITTED on PostgreSQL and Oracle, REPEATABLE_READ on MySQL InnoDB. Two threads updating the same row can still deadlock. Spring translates the deadlock into CannotAcquireLockException or a DeadlockLoserDataAccessException subclass, and the whole transaction rolls back. Retrying blindly at the thread level often recreates the deadlock, so retries need backoff and a cap.

  4. Virtual threads. On Spring Boot 3.2+ with Java 21 virtual threads, each virtual thread still gets its own ThreadLocal binding, so the model holds. The risk shifts to pool sizing: a virtual thread per request can create far more concurrent transactions than a 20-connection pool can serve, and threads block waiting for a connection. That shows up as pool wait time in Hikari metrics before it shows up as errors.

In short: one thread, one transaction, one connection, bound through TransactionSynchronizationManager. Anything that moves work to another thread moves it outside that transaction unless you deliberately start a new one.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Can you describe the lifecycle of a Spring Bean?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

A Spring bean goes through instantiation, dependency injection, aware callbacks, initialisation callbacks, and finally destruction when the context closes. The container controls the order, and proxies are usually created around initialisation. Knowing the order tells you when a dependency is safe to use and when a method will run on a proxy rather than the raw object.

For a singleton in an ApplicationContext, the sequence is:

Instantiation -> Populate properties -> Aware callbacks ->
BeanPostProcessor (before) -> Initialisation ->
BeanPostProcessor (after) -> Ready for use -> Destruction

Instantiation and population. Spring resolves the bean definition and creates the raw instance through a constructor or factory method. Constructor injection happens here. Then Spring populates properties: setter and field injection, @Value placeholders, and @Autowired on fields and methods. Annotation based @Autowired processing is implemented by a BeanPostProcessor, but conceptually it belongs to this populate step, before initialisation callbacks run. A singleton is created eagerly during context refresh unless @Lazy is set. A prototype is created on each lookup.

Aware callbacks. If the bean implements an aware interface, Spring calls it in a fixed order: BeanNameAware.setBeanName, BeanFactoryAware.setBeanFactory, then ApplicationContextAware.setApplicationContext. Environment and resource loader callbacks sit in the same group. This is where a bean can look up other beans or configuration without declaring them as constructor dependencies.

Before initialisation. Every BeanPostProcessor gets postProcessBeforeInitialization. Spring uses this hook for annotation processing and for common initialisation. If a processor returns a different object, the remaining lifecycle applies to the returned object.

Initialisation. Three mechanisms run in this order: a method annotated with @PostConstruct, then InitializingBean.afterPropertiesSet(), then a custom init-method declared in @Bean(initMethod = "...") or XML. At this point dependencies have been injected, so collaborators are safe to use. Calling a collaborator that itself depends on initialisation inside a constructor or setter is unsafe, because the bean is not yet initialised and may not yet be in the singleton registry in a usable form.

After initialisation. postProcessAfterInitialization runs. This is where the final proxy is usually created for transactions, async, caching, and security. The object injected into other beans is often this proxy, not the raw instance. That explains why self-invocation bypasses @Transactional: this.method() calls the target directly and never passes through the proxy.

PhaseCallbackTypical use
Populatesetters, @Autowired fields and methodswiring collaborators
AwaresetApplicationContextlookup, config access
Before initpostProcessBeforeInitializationvalidation, wrapping
Init@PostConstruct, afterPropertiesSet, initMethodload config, open resources, validate state
After initpostProcessAfterInitializationproxy for tx, security, cache
Destroy@PreDestroy, destroy(), destroyMethodclose pools, flush, deregister

Destruction. On context close, Spring calls postProcessBeforeDestruction, then @PreDestroy, then DisposableBean.destroy(), then the custom destroy method. Prototype beans are the exception. The container creates them and hands ownership to the caller, so it does not call destruction callbacks for them. A prototype holding a connection or file handle must clean up itself.

Java
@Component
public class OrderService {

    private final OrderRepository repo;

    public OrderService(OrderRepository repo) {
        this.repo = repo; // constructor injection at instantiation
    }

    @PostConstruct
    void init() {
        // repo is safe to use here
    }

    @PreDestroy
    void shutdown() {
        // called for singletons on context close, not for prototypes
    }
}

Failure modes I watch for. An exception in @PostConstruct or afterPropertiesSet fails context refresh and the application does not start. That is preferable to starting half initialised, but it means external calls in init, such as a database check or remote config fetch, make startup depend on that system. Circular references between singletons are prohibited by default since Spring Boot 2.6, which sets spring.main.allow-circular-references=false. That applies to constructor, setter, and field injection alike, and fails with BeanCurrentlyInCreationException. Re-enabling circular references is not a fix I would ship. Breaking the cycle with a @Lazy proxy, an ObjectProvider, or splitting the beans keeps the failure visible at design time. Another trap: a bean that needs the fully proxied version of itself during init will get the raw instance, because the proxy is created after init. Injecting a lazy proxy or splitting the bean avoids that.

Scope changes the timing. A @RequestScope bean in a web app is a proxy that creates a real instance per request, so its init callbacks run per request, not at startup. A lazy singleton defers all of this until first use, which moves failures from startup to the first request. I keep singletons eager by default and use lazy only for expensive or rarely used beans, because I would rather fail fast on deploy than on a customer call.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6What are the differences between various injection types in Spring Boot?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

Spring Boot has three ways to get a dependency into a bean: constructor injection, setter injection, and field injection. I use constructor injection by default, setter injection only for genuinely optional or mutable dependencies, and I avoid field injection in new code.

Java
// Constructor injection: preferred in Spring Boot 3.x
@Service
public class OrderService {
    private final PaymentClient payments;
    private final OrderRepository orders;

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

Since Spring 4.3, if a class has exactly one constructor, Spring injects it without needing @Autowired. That is the normal case in Boot 3.2+ with Java 17. The fields can be final, the object is fully constructed or not created at all, and a unit test is just new OrderService(mockPayments, mockOrders) with no reflection or Spring context.

ConstructorSetterField
TimingAt construction, before any method runsAfter construction, via a method callAfter construction, via reflection
ImmutabilityFields can be finalFields are mutable, can be re-setFields are mutable, hidden from caller
Missing beanContext fails to start, fail fastFails at injection time unless required=falseFails at injection time
Circular dependencyFails with BeanCurrentlyInCreationExceptionOften succeeds, which can hide a design problemOften succeeds, same problem
TestabilityPlain new in a unit testPlain new plus setter callsNeeds reflection or Spring test context
VisibilityExplicit in the constructor signatureExplicit, but easy to overlookInvisible in the API

Setter injection earns its place for optional dependencies. If a cache client is nice to have and the service must start without it, a setter with required=false expresses that honestly:

Java
@Autowired(required = false)
public void setCache(CacheClient cache) {
    this.cache = cache;
}

The trade-off is that the bean exists in a partially wired state between construction and the setter call. If another thread gets the bean in that window, it can see a null cache. In practice Spring completes injection before the bean is handed to callers, but the design still allows a caller to invoke the setter later and change behaviour at runtime. I keep setters rare and document them as optional.

Field injection with @Autowired on a field works, and you will see it in a lot of legacy Boot code, but it hides dependencies. The class signature does not show what it needs, you cannot make the field final, and a plain unit test cannot set it without reflection. It also makes circular dependencies harder to spot, because Spring can inject a partially constructed proxy and the cycle only surfaces as odd runtime behaviour instead of a clear startup failure.

Annotation differences interviewers follow up on. @Autowired is Spring's own annotation and supports required, @Qualifier, and injection on constructors, setters, and fields. @Inject is JSR-330 from Jakarta, it is by type only, has no required attribute, and is a good choice if you want the code to stay portable across frameworks. @Resource is Jakarta Annotation, it looks up by name first (the name attribute) and falls back to type, which made sense for JNDI lookups and is rarely the right default in Boot. @Value is a separate case: it injects configuration properties, not beans, and I use it for simple values while keeping structured config in @ConfigurationProperties.

Failure modes I watch for. Multiple beans of the same type cause NoUniqueBeanDefinitionException at startup. The fix is @Qualifier at the injection point or @Primary on the default bean, and I prefer @Qualifier because it makes the choice visible where it is used. A circular dependency between two services fails fast with constructor injection, which I treat as a signal to extract a third component rather than switching to setter injection to paper over it. For tests, constructor injection lets me write a fast unit test with hand-written fakes and reserve @SpringBootTest for the few cases that genuinely need the context, which keeps the suite fast enough to run on every commit.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-7How would you approach scaling a distributed system?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would start by asking what is actually saturating, because "scale it" hides four different problems. Is traffic growing, is one resource exhausted, is latency rising under load, or is a single hot key or shard overloaded? I would state my assumptions up front: a read-heavy service, say 12,000 requests per second at peak, with a small write path, running on stateless app servers behind a load balancer and a managed database. Then I scale in this order: remove state from the app tier, add instances horizontally, cache and shed load where safe, and shard or partition data only when a single node demonstrably cannot hold the working set or write rate.

The reason for that order is cost and risk. Horizontal instances are cheap to add and easy to roll back. Sharding changes every query, transaction and backup, so it is the last resort, not the first move.

Worked arithmetic, labelled as an example

Assume one app instance sustains 800 rps at 60% CPU with p99 latency of 180 ms. At 12,000 rps peak I need 15 instances at that utilisation, which leaves no headroom for a node loss or a deploy. Targeting 50% utilisation for headroom gives 24 instances. Little's Law checks the downstream: at 180 ms latency and 12,000 rps, the service holds about 2,160 requests in flight (12,000 x 0.18). If each request holds one database connection for 40 ms of that time, the pool needs roughly 480 concurrent connections across the fleet. A pool of 20 per instance across 24 instances gives 480, so it is exactly at the edge. That is the failure I would expect first: not CPU, but pool saturation, queueing, and p99 climbing while average latency still looks fine.

BottleneckSignal I would checkFirst moveWhen that stops working
App CPU or event loopCPU above 70% at peak, p99 rising with rpsAdd stateless instances, autoscale on CPU and queue depthA single request does expensive work, such as a full scan or large serialisation
Database connectionsPool wait time, active sessions at maxReduce per-request hold time, add PgBouncer in transaction mode, cap poolsConnection count is fine but queries queue on locks or one hot row
Database CPU or I/OBuffer cache hit rate falling, disk wait risingAdd read replicas for reads, index the slow query, cache hot readsWrites exceed one primary, or replicas lag beyond the read-your-writes tolerance
One hot key or shardOne node at 95% while others idleCache the key, split the hot partition, queue writes per keyThe key is inherently serial, such as a single account balance
Downstream dependencyTimeouts and retries multiplying trafficCircuit breaker, timeout budget, backoff with jitter, load sheddingRetries from clients and internal callers amplify a partial outage

A trace I would walk through

A popular product page is cached with a 60 second TTL. At expiry, 400 concurrent requests miss at once and all hit the database. The database slows, app threads block on connections, the load balancer health check still passes because the process is alive, and autoscaling adds instances that make the stampede worse. The fix is not more instances. It is request coalescing or a probabilistic early refresh, so one request rebuilds the cache while others serve stale data for a few seconds, plus a per-instance connection cap so a slow dependency cannot consume the whole fleet.

For autoscaling I would use a concrete policy rather than a vague promise. In Kubernetes terms, scale on request queue and CPU together, with a floor sized for one availability zone loss:

YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: orders-api
spec:
  minReplicas: 8
  maxReplicas: 40
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          averageUtilization: 55
    - type: External
      external:
        metric:
          name: http_requests_waiting
        target:
          averageValue: "20"

Failure modes I would name before being asked

Cache stampede and stale reads after a write, where a replica returns old data and the user sees a cancelled order as active. Retry storms, where a 5 second timeout with immediate retries turns 12,000 rps into 36,000 rps against an already struggling dependency. Hot partitions after sharding by a poorly distributed key, such as sequential IDs. And split brain during a network partition if I had chosen multi-primary writes, which is why I would keep one primary per shard and accept the write availability trade-off.

I would close by saying how I would prove it: a load test at 1.5 times peak, a chaos test that kills a zone and a cache node, and dashboards for p99 by dependency, pool wait time, replica lag in seconds, and per-shard request share. If those hold, the design scales. If not, the numbers tell me which row of the table I am actually in.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8Can you explain how to optimize slow database queries and identify bottlenecks?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I start by finding which queries actually hurt, not by tuning the one someone pasted into a ticket. In Postgres I check pg_stat_statements ordered by total_exec_time and by mean_exec_time, then I run EXPLAIN (ANALYZE, BUFFERS) on the top offenders. That tells me whether the cost is rows scanned, rows returned, sorting, locking, or waiting on something else. Only then do I change the query or the schema, and I re-run the same plan to prove the change helped.

Assume a typical service backend: Postgres behind an API, a few hundred requests per second at peak, and a report that the orders page is slow. The workflow below is what I would do in the first hour.

1. Rank the pain

SQL
SELECT query, calls, round(mean_exec_time::numeric, 2) AS mean_ms,
       round(total_exec_time::numeric, 2) AS total_ms,
       rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

A query that runs 50,000 times a day at 80 ms costs more than one that runs twice at 2 s, even though the second one feels worse in a demo. I also check pg_stat_user_tables for seq scans and pg_stat_database for deadlocks and rollbacks, because a slow query is sometimes a symptom of lock contention or a bloated table after missed vacuuming.

2. Read the plan, not the query text

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT o.id, o.total, c.name
FROM orders o JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '7 days'
  AND o.status = 'OPEN'
ORDER BY o.created_at DESC
LIMIT 50;

A bad plan I have seen in production looks like this (figures from a staging copy, labelled as an example):

Limit  (cost=0.43..98412.55 rows=50 width=40) (actual time=412.118..412.204 rows=50 loops=1)
  Buffers: shared hit=1820 read=940
  ->  Sort  (cost=0.43..98412.55 rows=50 width=40) (actual time=411.900..412.100 rows=50 loops=1)
        Sort Key: created_at DESC
        ->  Hash Join  (cost=18420.00..97000.00 rows=184203 width=40) (actual time=38.200..398.700 rows=184203 loops=1)
              Hash Cond: (c.id = o.customer_id)
              ->  Seq Scan on orders o  (cost=0.00..18420.00 rows=1000000 width=32) (actual time=0.080..210.400 rows=184203 loops=1)
                    Filter: (status = 'OPEN'::text AND created_at >= ...)
                    Rows Removed by Filter: 815797
              ->  Hash  (cost=0.00..210.00 rows=9200 width=24) (actual time=12.100..18.300 rows=9200 loops=1)
                    ->  Seq Scan on customers c  (cost=0.00..210.00 rows=9200 width=24) (actual time=0.050..9.800 rows=9200 loops=1)

The numbers reconcile: the seq scan examined 1,000,000 rows, removed 815,797 by filter, and returned 184,203 rows to the join. The diagnosis is concrete: 210 ms spent in the seq scan alone, then a sort over 184,203 rows to return 50. The fix is a composite index that matches the filter and the ordering:

SQL
CREATE INDEX CONCURRENTLY idx_orders_open_created
  ON orders (status, created_at DESC) INCLUDE (total, customer_id);

After that, the same plan typically becomes an index scan returning 50 rows in under 5 ms on similar hardware. CONCURRENTLY matters because a plain CREATE INDEX on a busy table takes a lock that blocks writes.

3. Look for the patterns that indexes alone do not fix

PatternHow I spot itFix that usually works
N+1 queriescalls in pg_stat_statements jumps by the page size; logs show one query per rowJoin or batch load, or use a single query with WHERE id = ANY($1)
SELECT * on a wide tablerows returned far exceeds columns the API serialisesProject only needed columns; move large text or JSON blobs to a side table
Function on the indexed columnPlan shows seq scan despite an index existing, e.g. WHERE date(created_at) = ...Rewrite as a range: created_at >= day AND created_at < day + 1
Deep OFFSET paginationEXPLAIN shows rows removed growing with page numberKeyset pagination on (created_at, id)
Lock waitspg_stat_activity shows wait_event_type = 'Lock'; p99 spikes while mean stays flatFind the blocking transaction, shorten it, never hold a transaction open across an HTTP call

4. Check the layer around the database

If the plan is fast in psql but slow through the app, I look at connection pool saturation. With a pool of 20 connections and each query holding one for 200 ms, throughput caps at 100 queries per second no matter how good the indexes are. Queueing then shows up as latency, not as CPU. I compare mean_exec_time from pg_stat_statements with end-to-end latency from the app metrics. A large gap points at the pool, DNS, TLS, or a chatty ORM issuing extra round trips.

I also check for missing statistics after bulk loads. ANALYZE not having run can make the planner pick a nested loop for a table that actually has millions of rows. That is a one command fix that people overlook.

What I would not do first

I would not add a cache in front of a query I have not profiled, and I would not denormalise a table to fix a single endpoint. Both hide the plan problem and create a consistency problem I then own. The order is measure, fix the plan or the access pattern, measure again, and only then consider caching with a clear invalidation story.

In an interview follow-up I would expect to be asked how I would verify in production. My answer: deploy the index with CONCURRENTLY, watch pg_stat_statements for the same query fingerprint, and compare p50 and p99 before and after over a full traffic cycle, not just the first five minutes.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9How do you handle database migrations in a production environment?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I treat a migration as a code change with two deployments, not one. The schema change has to work with the code running before it and the code running after it, because during a rolling deploy both versions are live at once. That means expand, migrate, contract.

Expand: add the new column or table as nullable, with no NOT NULL and no constraint that old code would violate. Deploy the new code that writes both the old and new fields. Migrate: backfill the new field from the old one in small batches. Contract: only after every instance runs the new code and the backfill is verified, add the NOT NULL, the unique index, or drop the old column in a separate migration.

If a migration cannot be split that way, I do not run it in the deploy. I run it as a separate, reviewed step with a maintenance window or a feature flag.

What that looks like in practice

Say we are splitting orders.customer_name into orders.customer_id referencing customers. One migration that adds the column, backfills 12 million rows, adds a foreign key and drops the old column will lock the table, time out, and break the old code the moment the column disappears.

Split it:

SQL
-- V20260112_1__expand_orders_customer_id.sql  (deploy 1, with new code)
ALTER TABLE orders ADD COLUMN customer_id BIGINT NULL;
CREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders(customer_id);
-- no foreign key yet, no NOT NULL yet
SQL
-- V20260112_2__backfill_orders_customer_id.sql  (run after deploy 1)
-- run in batches from the app or a job, not one UPDATE
UPDATE orders SET customer_id = c.id
FROM customers c
WHERE c.name = orders.customer_name
  AND orders.id BETWEEN :lo AND :hi
  AND orders.customer_id IS NULL;
SQL
-- V20260112_3__contract_orders_customer_id.sql  (deploy 2, weeks later)
ALTER TABLE orders ADD CONSTRAINT fk_orders_customer
  FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT fk_orders_customer;
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL;
-- drop customer_name only after reads have moved off it

New code writes customer_id and customer_name together during expand. Old code ignores the new column. Reads during migrate prefer customer_id when present and fall back to customer_name. That dual write is the price of zero downtime, and I remove it in contract.

PhaseSchema stateCode stateRisk if it fails
ExpandNew column nullable, index built concurrentlyNew code dual writesOld code unaffected, new column may be empty
MigrateBackfill in progressReads fall back to old fieldPartial data, safe to rerun the batch
ContractNOT NULL, FK validated, old column droppedOld code gone, dual write removedIrreversible, so verify counts first

Backfill arithmetic and locking

A single UPDATE orders SET ... over 12 million rows in Postgres holds row locks, bloats the WAL, and can run for minutes. I batch it: 10,000 rows per transaction, with a short sleep between batches. At 20 batches per minute that is 1,200 batches and about 60 minutes for 12 million rows, with replication lag staying under a second. I watch pg_stat_replication lag and pause the job if it passes 2 seconds.

For DDL, the lock matters more than the data. ALTER TABLE ... ADD COLUMN with a default is instant in Postgres 11 and later, but a plain CREATE INDEX takes a SHARE lock on the table. That blocks writes (INSERT, UPDATE, DELETE) for the whole build while still allowing reads. CREATE INDEX CONCURRENTLY avoids that at the cost of taking longer and needing to run outside a transaction block, which Flyway and Liquibase both need explicit configuration for. In MySQL 8, ALGORITHM=INPLACE, LOCK=NONE is the equivalent check, and I verify it on a replica first.

Failure modes I plan for

A migration that fails halfway leaves the schema version table marked applied or not, depending on the tool. Flyway, for example, records a failed migration and blocks the next run until you repair it. I test every migration against a production-sized snapshot, not an empty database, and I test the rollback path. Rollback for expand is usually to do nothing, since the column is unused. Rollback for contract is a new migration that re-adds the dropped column, which is why I keep the old column for at least one full release cycle.

The other failure is drift between environments. If someone edits a migration after it has run in production, checksums diverge and deploys fail in staging. Migrations are immutable once merged. A fix is a new migration.

Tooling choice

I use versioned migrations (Flyway, Liquibase, Alembic, Django migrations) rather than auto-generated schema sync for anything shared. Versioned files give me review, ordering, and a checksum. I run them from the deploy pipeline before the new code starts, with a timeout and a lock so two instances do not race. If the migration takes longer than the deploy window, it runs as a standalone job, not inline.

The test I apply before approving one: can I deploy the code, run the migration, roll the code back, and still serve traffic? If not, the migration is not ready.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10What strategies do you use to ensure data consistency across microservices?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I start by refusing the premise that we need one consistency model for everything. Inside a service I want strong consistency from its database. Across services I accept eventual consistency and make it safe, because a 2PC or XA transaction across services couples availability and latency to the slowest participant and is hard to operate at scale. The question then becomes: for each cross-service workflow, what invariant must hold, how quickly must it converge, and what happens if a step fails halfway.

In practice that gives me four tools, chosen per workflow.

  1. Single-writer ownership. Each fact has one owning service. Others keep a read replica or a cached copy, never write it directly. If Order owns order status, Payment cannot update it. It publishes PaymentCaptured and Order decides what that means.
  2. Transactional outbox plus idempotent consumers. A service writes its state change and the event to publish in the same local transaction. A relay publishes from the outbox. Consumers deduplicate on event ID. This removes the dual-write bug where the database commits and the broker publish fails, or vice versa.
  3. Saga for multi-step workflows. A sequence of local transactions, each with a compensating action if a later step fails. I use it for order placement across Order, Payment and Inventory. I do not use it where I need atomicity, for example debiting two accounts in one operation. That stays in one service or one database.
  4. Reconciliation for the gaps. Events can be lost, delayed, or consumed out of order despite the above. A periodic job compares the owning service against replicas and downstream state, and raises an alert or repairs drift. If I cannot reconcile it, I do not trust eventual consistency for that data.
PatternGuaranteeCostUse it when
Local transactionStrong, within one serviceLowThe invariant lives in one aggregate
Outbox + eventsAt-least-once delivery, eventualRelay and dedup storageOther services need to react reliably
SagaEventual, with compensationCompensation logic, intermediate states visibleA workflow spans services and can be undone
2PC / XAStrong across servicesAvailability and latency coupling, operational complexityRarely. Small, low-traffic systems where atomicity is mandatory

Worked trace: place order

POST /orders in Order service, in one transaction: insert order(id=42, status=PENDING), insert outbox row OrderCreated(order_id=42, event_id=e_991). Commit. Relay publishes OrderCreated to Kafka and marks the outbox row sent.

Inventory consumes e_991, reserves stock with INSERT ... ON CONFLICT keyed by order_id, so a redelivery is a no-op, then publishes StockReserved. Payment consumes it, charges the card with the order ID as the idempotency key at the provider, publishes PaymentCaptured. Order consumes both, moves to CONFIRMED, publishes OrderConfirmed.

If Payment declines, it publishes PaymentFailed. Order runs the compensation: cancel the reservation by publishing ReleaseStock(order_id=42), Inventory releases it idempotently, Order moves to CANCELLED. The customer sees PENDING briefly, then a terminal state. No step assumes the previous step succeeded.

Outbox sketch, Java / Spring

Java
@Transactional
public Order create(CreateOrder cmd, String idempotencyKey) {
    Order order = orders.insert(new Order(cmd, OrderStatus.PENDING));
    outbox.insert(new OutboxEvent(
        UUID.randomUUID(), "OrderCreated",
        json(order), Instant.now()));
    return order;
}

// Relay: SELECT ... FOR UPDATE SKIP LOCKED, publish, mark sent.
// Consumer: INSERT INTO processed_events(event_id) ON CONFLICT DO NOTHING;
// If the insert affected 0 rows, skip the handler.

Failure modes I design for

Dual write without an outbox: DB commits, publish fails, downstream never learns. Detected by outbox lag and by reconciliation counts per topic.

Duplicate delivery: Kafka gives at-least-once. Without dedup, a retried PaymentCaptured charges twice. Detected by duplicate event_id in processed_events and by provider idempotency keys.

Compensation that itself fails: ReleaseStock consumer is down. The order sits in PENDING past its timeout. I set a deadline on saga state, alert on expired sagas, and make compensations retryable and idempotent so recovery is just redelivery.

Out-of-order events: PaymentCaptured arrives before StockReserved. Handlers check current state and park or reject unexpected transitions instead of applying them blindly. A state machine per aggregate, not free-form updates, makes this checkable.

The trade-off I state in interviews: strong consistency across services is possible, but you pay for it in availability during partitions and in latency on every commit. For most order, notification and reporting flows, eventual consistency with an outbox, idempotent handlers, sagas where undo is meaningful, and reconciliation where it is not, gives a system I can actually operate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11How do you approach solving a problem when you have limited documentation?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I treat missing documentation as missing evidence, not as permission to guess. I state what I know, what I am assuming, and what would change my mind, then I run the smallest experiment that can prove one of those assumptions wrong. I keep a short log of hypotheses and results so a teammate can pick up the work without reconstructing my reasoning.

My order is: reproduce the problem, read the code and tests that already encode behaviour, probe the running system, and only then ask the owner or vendor. Documentation is one source among several, and often not the most reliable one.

How I run it in practice

First, I pin down the exact symptom. Input, expected output, actual output, environment, and the smallest case that still fails. If I cannot reproduce it, I say so and ask for a failing request, a log line, or a recording. Vague reports waste the first hour.

Second, I mine the codebase. Tests are usually the best spec that exists. I search for the function name, the error string, the endpoint path, and recent commits touching them. I check git blame for the last change to that logic and look for feature flags, config defaults, and dead code paths that hint at intended behaviour.

Third, I probe the system as a black box. I send controlled requests and record status codes, headers, and payloads. For an undocumented endpoint, a small script beats manual clicking:

Python
# probe.py, Python 3.12, run against staging only
import requests

BASE = "https://staging.internal/orders"
for payload in [{"id": "o_1"}, {"id": "o_1", "version": 2}, {}]:
    r = requests.post(BASE + "/lookup", json=payload, timeout=5)
    print(payload, r.status_code, r.headers.get("content-type"), r.text[:200])

The point is not the script. It is that each run tests one variable and leaves a trace I can paste into a ticket.

SourceWhat it provesHow it misleads
Tests and fixturesBehaviour someone once assertedTests can be stale or test the mock, not the system
Code and configWhat the deployed build actually doesDead branches and flags make the path unclear
Logs and metricsWhat happened in productionLogs show symptoms, rarely intent
Live probingCurrent response to a known inputStaging may differ from production data and config
Owner or vendorIntent and known limitsAnswers from memory drift from the shipped version

A worked trace

Say a webhook from a payment provider starts returning 401s after a deploy, and the provider docs only describe the old signature scheme. I do not start by rewriting the verifier. I check the code: it reads a header named X-Signature and compares an HMAC. I check tests: they use a fixed secret and a fixed timestamp. I check logs: the 401s began at 14:03, the same minute the deploy finished, and the provider header in the log changed from X-Signature to X-Signature-V2. I replay one captured payload against staging with the old scheme and get 401, then with the v2 scheme and a timestamp inside the tolerance window and get 200. That gives me a hypothesis I can test in a branch: accept v2, keep v1 during a transition window, log which scheme matched. I write that up with the replay results before I ask the provider anything, so the question becomes "is the tolerance 5 minutes or 10?" instead of "why is this failing?"

When I escalate

I escalate with evidence after two failed hypotheses or about two hours of focused probing, whichever comes first. The message contains the minimal repro, the hypotheses I already ruled out, and the one decision I need from the owner. If the fix touches money, auth, or data deletion, I stop earlier and get a second pair of eyes before merging, because an undocumented edge case there is expensive to undo. I also leave a note in the ticket or README describing what I found, so the next person inherits the documentation we wished we had.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-12Can you explain the trade-offs between different data structures for a specific use case?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would start from the operations the workload needs, not from a favourite structure. Take an in-memory session store for 10 million active users. Almost every request does get(sessionId). Login and refresh do put. Once a minute we need the sessions that are expiring, and we need to evict when memory fills.

That points to a hash table for lookup, plus a separate expiry queue. A tree map gives ordering, but I would pay O(log n) on every hot lookup for a property I only need once a minute.

StructureLookup by keyOrdered scanWhen I would pick it
Hash table (HashMap)O(1) averageNoPoint lookup is the hot path
Tree map (TreeMap)O(log n)Yes, by keyRange or sorted iteration is the hot path
Array listO(n) by value, O(1) by indexInsertion orderAccess is by position, not by id
Linked listO(n)Insertion orderRarely, mainly for cheap insert and delete at ends

Why not just use the tree everywhere

With 10 million entries, a tree lookup follows about 24 levels of pointers. A hash lookup computes a hash, probes one bucket, and usually compares one key. The tree also uses more memory per entry because each node stores child and parent pointers plus a colour flag, and those pointer hops tend to miss cache. The hash table has its own costs: worst case degrades toward O(n) if many keys collide, and resizing rehashes the whole table and can pause requests. I would size it for the expected peak and watch the load factor.

The hash table cannot answer "what expires in the next minute" without scanning all 10 million entries. So I keep expiry separate:

Java
// Java 17, sketch. Concurrent version uses ConcurrentHashMap.
Map<String, Session> byId = new HashMap<>();
DelayQueue<Expirable> expiry = new DelayQueue<>();

Session s = byId.get(sessionId);   // hot path
if (s != null && !s.expired()) return s;
byId.put(sessionId, fresh);
expiry.offer(new Expirable(sessionId, fresh.expiresAt()));

Trace for one sweep: the sweeper polls the queue, gets the 3,000 sessions due this minute, removes each from byId only if the stored expiry still matches, so a refreshed session is not evicted by its old queue entry. That check matters, because the queue can hold stale entries.

Failure modes I would name

Collisions: if keys are attacker controlled, many keys landing in one bucket slows lookups. Generating session ids server side as random values avoids handing that control to clients.

Stale expiry entries: handled by the expiry check above.

Memory growth: the queue and the map both hold a reference per session, so I would cap total entries and evict oldest first rather than let the store grow until the JVM swaps.

If the main query changed to "all sessions for a region, sorted by last activity", I would flip the choice and make the sorted structure primary. The structure follows the query pattern.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13What are the common security vulnerabilities in web applications and how do you mitigate them?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would work from the OWASP Top 10 (2021) and tie each class to an attack I can reproduce in a Spring Boot service, plus the control I would ship and the test that proves it. The recurring failures are injection, broken access control, XSS, CSRF and authentication flaws, and SSRF. They need different controls, and picking the wrong variant creates its own problems.

Injection. Untrusted input becomes code. The classic case is a query built by concatenation:

Java
// Vulnerable
String sql = "SELECT * FROM orders WHERE customer_id = '" + id + "'";
// id = ' OR '1'='1 returns every row

// Parameterised: input stays data
jdbcTemplate.query("SELECT * FROM orders WHERE customer_id = ?", rowMapper, id);

Parameterised queries, JPA or JDBC with bound arguments, are the primary control. A WAF in front can catch crude payloads, but I would not rely on it as the main defence. It misses encoded and second-order injection, and tuning it to avoid false positives on legitimate text tends to weaken it. The same reasoning applies to command injection, where ProcessBuilder should take an argument list rather than a shell string, and to NoSQL injection, where operators from JSON input must be stripped before they reach the query. Least-privilege database accounts limit damage if something slips through, since a web user account should not be able to drop tables or read other schemas.

Broken access control. Authentication passes, authorization is missing. GET /orders/{id} returns any order to any logged-in user. The fix is an ownership check in the service layer: load the order, compare order.customerId with the current principal, and return 404 or 403 if they differ. Spring Security annotations such as @PreAuthorize help at the method boundary, but they cannot express object-level rules on their own, so I keep the check in domain code and test it with two users. Unguessable IDs reduce casual guessing, yet they are not a control. If an ID leaks in a log or a referrer header, the endpoint is still open.

XSS. Stored XSS through a display name is the damaging variant because it runs in other users' browsers. Default escaping in Thymeleaf or React handles most cases. The trade-off appears with rich text. Rendering raw HTML with th:utext or dangerouslySetInnerHTML is sometimes needed for formatted content, and then I would sanitize with a library such as OWASP Java HTML Sanitizer against an allowlist of tags, accepting that sanitizers can be bypassed if the policy is too permissive. A Content-Security-Policy adds a second layer. A nonce-based policy works well for server-rendered pages where I control each response, while a hash-based policy breaks when scripts are generated dynamically, so I choose based on rendering style. HttpOnly, Secure and SameSite=Lax cookies limit what a successful script can steal.

CSRF and authentication. CSRF works because the browser attaches cookies automatically. Spring Security's synchronizer token is the standard control for browser sessions. For a stateless API using bearer tokens in an Authorization header, CSRF tokens add little, since the token is not sent automatically, and SameSite cookies plus CORS restrictions cover the residual risk. That distinction matters, because applying session-oriented controls to token APIs adds complexity without reducing exposure. For passwords, BCrypt or Argon2id with a work factor that keeps login near 100 ms on production hardware. Rate limiting login protects against credential stuffing, but aggressive lockout can be turned into a denial of service against a known account, so I prefer throttling by IP and device fingerprint with a short backoff over permanent lockout. MFA for privileged accounts, short-lived access tokens, and refresh token rotation complete the picture.

SSRF and deserialization. SSRF occurs when the server fetches a user-supplied URL, for example an image import feature. An attacker points it at http://169.254.169.254/latest/meta-data/ to reach cloud instance metadata. An allowlist of hosts and schemes is the strongest control, but it fails for features that must fetch arbitrary webhooks. In that case I resolve DNS first, reject private, loopback and link-local ranges, disable redirects to internal addresses, and route egress through a proxy that enforces the same rules. Blocklists alone are brittle because DNS rebinding can return a public address first and a private one later. Deserialization is similar in spirit: Java native serialization and Jackson default typing can instantiate arbitrary classes from untrusted data, so I use explicit DTOs and disable polymorphic default typing.

RiskPrimary controlCredible alternativeWhen the alternative is the better choice
SQL injectionParameterised queriesWAF rulesOnly as a supplement, never as the sole control
XSSContext-aware encodingCSP with noncesWhen rendering raw HTML, encoding alone is insufficient
CSRFSynchronizer tokenSameSite cookiesToken APIs with bearer auth, where cookies are absent
SSRFHost allowlistIP range blocking after DNS resolutionOpen webhook fetchers that cannot use an allowlist
Credential stuffingRate limiting plus MFAAccount lockoutLockout only with a recovery path, since it enables targeted lockout attacks

Transport and headers are baseline rather than optional: TLS with HSTS, X-Content-Type-Options: nosniff, and no sensitive data in logs or error responses. I would also patch dependencies promptly and keep Spring Actuator endpoints authenticated or disabled, since exposed actuator endpoints have leaked environment variables in real incidents. Each control above gets a test that sends the attack payload, such as ' OR '1'='1, a cross-user order ID, or a metadata URL, and asserts the request fails. A control without that test tends to regress quietly.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14Explain a time you encountered a race condition in a Spring application and how you resolved it?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

In a Spring Boot order service, we had a classic check-then-act race on stock. The controller read an item, checked stock > 0 in Java, decremented it, and saved. Under load two requests passed the check for the last unit and both created orders. We fixed it by moving the check into the database as a single atomic update, and we added a unique constraint and a metric so we would see it immediately if it happened again.

The code looked like this, simplified:

Java
// Before: two separate steps, no lock held between them
Item item = itemRepo.findById(id).orElseThrow();
if (item.getStock() <= 0) throw new OutOfStockException();
item.setStock(item.getStock() - 1);
itemRepo.save(item);

That works in a single-threaded test. In production Tomcat runs 200 request threads by default, and each request gets its own transaction. Nothing stops two transactions interleaving between the read and the write.

Worked trace

Stock for SKU A-100 is 1. Two buyers, T1 and T2, arrive at the same time.

TimeT1T2Stock in DB
1SELECT stock FROM item WHERE id=... returns 11
2SELECT ... returns 11
3Java check passes, sets stock to 01
4Java check passes, sets stock to 01
5UPDATE item SET stock=0 commits0
6UPDATE item SET stock=0 commits0

Both orders succeed. We oversold by one and the database still shows a plausible value, so no constraint fires. That is why this bug survived for weeks. It only showed up as a customer complaint and a warehouse count mismatch on a Friday evening flash sale, when concurrency on that SKU went from about 2 requests per minute to over 40.

The fix

Replace read-modify-write with one conditional update. The database decides, atomically, whether a unit is available:

Java
@Modifying
@Query("""
    update Item i set i.stock = i.stock - 1
    where i.id = :id and i.stock >= 1
    """)
int decrementStockIfAvailable(@Param("id") Long id);
Java
@Transactional
public Order placeOrder(Long itemId, Long customerId) {
    int updated = itemRepo.decrementStockIfAvailable(itemId);
    if (updated == 0) throw new OutOfStockException();
    return orderRepo.save(new Order(itemId, customerId));
}

Now T1 and T2 both run the UPDATE. The second one blocks on the row lock until the first commits, then re-evaluates stock >= 1 against the new value of 0 and updates zero rows. One order is created, the other gets a 409. No Java lock, no synchronized, and it works across multiple application instances behind a load balancer, which a JVM lock would not.

Alternatives I considered, and when I would pick them

ApproachHow it worksWhen it fitsCost
Atomic conditional updateUPDATE ... WHERE stock >= 1Single-row counter like stock, balance, seatsOne round trip, row lock held briefly
Pessimistic lockSELECT ... FOR UPDATE then update in same transactionYou need to read several fields and decide based on all of themHolds the lock longer, more contention, deadlock risk if you lock rows in different orders
Optimistic lock with @VersionJPA throws OptimisticLockException on concurrent write, you retryLow contention, read-heavy entities like a profile or a documentRetry loop under contention, wasted work

I picked the atomic update because the decision only needed one column. If the rule had been "reserve stock only if the customer has credit and the item is in their region", I would have used SELECT ... FOR UPDATE inside one transaction and locked rows in a fixed order, by id, to reduce deadlocks.

How we detected it and how we would catch it next time

Detection was reconciliation, not logs. A nightly job compared sum(order_items.quantity) against the initial stock minus current stock. The gap appeared only on high-traffic SKUs. After the fix we added two things: a CHECK (stock >= 0) constraint so a bug cannot drive stock negative silently, and a counter incremented whenever decrementStockIfAvailable returns 0, alerted when the out-of-stock rate jumps suddenly. That turns a silent oversell into a visible 409 spike.

The lesson I took from it: if a check and a write are in different statements, assume they will interleave. Put the condition in the same statement as the write, or hold a database lock across both, and never rely on a single JVM instance to serialise requests.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15Compare and contrast different scopes in Spring Boot?

Reported in Elm Software Engineer Interview Questions & Guide 2026

The 90-second answer

Spring has five built-in bean scopes. Singleton is the default and the one you should reach for first. Prototype, request, session and application cover the cases where one shared instance is wrong. The choice comes down to how many instances you want, when they are created, and who destroys them.

ScopeInstancesCreatedDestroyedThread safetyTypical use
singleton1 per ApplicationContextAt context refresh, unless @LazyAt context closeMust be stateless or synchronisedServices, repositories, controllers
prototype1 per injection point or getBean() callOn demandContainer does not manage it. @PreDestroy is not calledEach caller gets its own, so no sharing hazardStateful helper objects, per-operation workers
request1 per HTTP requestOn first use in that requestAt request endSafe within a request, not across threads handling different requestsPer-request context, audit holder
session1 per HTTP sessionOn first use in that sessionAt session invalidation or timeoutMutable state is a race risk across concurrent requests in the same sessionShopping cart, wizard state
application1 per ServletContextOn first useAt servlet context shutdownSame caution as singleton, wider blast radiusApp-wide config that is not a singleton for testability reasons

There is also websocket scope in Spring MVC for per-websocket-session beans, and custom scopes via Scope implementations. In most Spring Boot services you will use the first three.

Where candidates get caught: injection

A singleton that depends on a prototype does not get a fresh prototype each time. It gets one at construction and keeps it for the life of the context.

Java
@Service
@Scope("prototype")
public class ReportGenerator {
    private final StringBuilder out = new StringBuilder();
    public void add(String line) { out.append(line).append('\n'); }
    public String render() { return out.toString(); }
}

@Service
public class ReportService {
    private final ReportGenerator generator; // BUG: one instance, reused forever
    public ReportService(ReportGenerator generator) { this.generator = generator; }
}

Trace: request A calls ReportService, adds "A1". Request B calls the same service, adds "B1", and render() returns both lines. The fix is to ask the container each time:

Java
@Service
public class ReportService {
    private final ObjectProvider<ReportGenerator> generators;
    public ReportService(ObjectProvider<ReportGenerator> generators) {
        this.generators = generators;
    }
    public String build(List<String> lines) {
        ReportGenerator g = generators.getObject(); // fresh per call
        lines.forEach(g::add);
        return g.render();
    }
}

@Lookup on a method is the older alternative. ObjectProvider is clearer and works with constructors.

Request and session scope use proxies

Java
@RestController
@RequestScope
public class RequestContext {
    private String tenantId;
    public String tenantId() { return tenantId; }
    public void tenantId(String t) { this.tenantId = t; }
}

Spring injects a proxy, not a real instance, into singletons that depend on it. Each method call resolves the proxy to the bean bound to the current request. That is why a singleton can safely hold a @RequestScope dependency, and why it fails outside a web request: there is no request to resolve to, and you get a ScopeNotActiveException.

Failure modes I check for

  1. Mutable singleton. A @Service with a private List<Order> pending field accumulates state across threads. Under load, orders leak between customers. Fix: make it stateless, or move the state to a prototype or request-scoped bean.
  2. Session scope as a database. Session beans live in memory on one node. With sticky sessions off, a user can land on a node without their session. Session state also survives longer than users expect, so stale carts and memory pressure follow. Keep session scope for small, short-lived UI state, and store authoritative data in the database.
  3. Prototype cleanup assumed. Because the container does not destroy prototype beans, a prototype that opens a file or connection must close it itself. Relying on @PreDestroy there silently leaks resources.
  4. Application scope confusion. It is not "more singleton". It is scoped to the ServletContext, so in tests with multiple contexts you can get a different instance than in production. Prefer singleton unless you need that boundary.

Rule of thumb: singleton unless you can name the unit of lifetime (one operation, one request, one session) and explain who creates and destroys the instance.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16Explain how your prior experience and successes have prepared you for this role?

Reported in Elm Assessment and Interview Process: Candidate Guide

I would point to the backend work I have owned end to end, because that is the part of this role I have already done under production pressure. For the past three years I built and ran order and payment services in Java and Spring Boot, about 2 million requests a day, and I was on call for them. So I have dealt with retries, partial failures and schema changes where getting it wrong corrupts data, not just returns an error.

The clearest example is duplicate orders. Clients retried POST /orders after a timeout, and without protection we created two orders for one intent. I added an Idempotency-Key header. The server stores the key with the created order id and the response for 24 hours, and a retry returns the original 201 instead of inserting again. Duplicates dropped from 0.4 percent of creates to near zero. The trade-off is storage and a lookup on every create, plus we have to decide what happens when the same key arrives with a different body. We reject that as a conflict. For a read-only internal endpoint I would not add this, the cost buys nothing there.

Pagination was a similar call. We used a keyset cursor on created_at and id for the orders list, so each page examined about 50 rows. After a backfill the old offset query scanned 48,000 rows to return 50 and p99 went from 40 ms to 1,800 ms. The fix was a composite index and the cursor. Keyset is worse when someone needs to jump to page 47 in an admin console, because there is no page number. We kept offset for that internal view and keyset for the public API, where users scroll forward.

For database changes I used expand, migrate, contract. Add the new column, backfill in batches, switch reads, then drop the old column in a later release. It costs double writes during the migration and more code, so I would not use it for an internal tool where a short maintenance window is acceptable. For a service we cannot take down, it gave us a rollback path at each step.

One failure mode I learned the hard way was connection pool saturation. In a load test, p99 rose from 40 ms to 180 ms once the pool hit 20 connections and requests started queueing. The fix was bounding the pool per dependency and alerting on wait time, not just errors. That is the habit I would bring here: name the failure, reproduce it with realistic volume, and keep the old path until the new one is verified.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-17Why are you interested in this role at Elm?

Reported in Elm Assessment and Interview Process: Candidate Guide

The 90-second answer

"I want production ownership of services where correctness is visible to the user. In my last role I ran a payments-adjacent API handling about 1.4 million requests a day. A duplicate write was not a cosmetic bug. It created a second charge record that finance had to reconcile by hand. That kind of work is what I am looking for next, and a large platform operator in Saudi Arabia is where that constraint is the job, not an edge case."

Then stop and let them probe. If they ask why Elm rather than another large employer, I would answer from the job description and public material I read before the interview, not from claims I cannot verify. The posting emphasised scale, reliability, and work on national digital services. That matches the part of my work I want more of.

Why the constraints change the design

Government and enterprise platforms in this market operate under change control, audit requirements, and data handling rules that a consumer startup does not. Those rules are not paperwork around the engineering. They decide the engineering.

If every state change must be auditable, you cannot update a row in place and hope a log line explains it later. You write the transition as an explicit event, with actor, timestamp, and before and after state, in the same transaction as the change. If a regulator or an internal audit asks why a permit moved from submitted to approved, you replay that record.

If releases need approval and a rollback window, you avoid a flag day migration. You expand the schema, dual write for one release, backfill, then contract in the next. That costs more code for a week and saves a 2 a.m. incident when the backfill turns out to be slower than estimated.

If traffic peaks are predictable but sharp, for example month end renewals, average load tells you nothing. You size for the peak hour and you load test at that concurrency, with realistic payload sizes. In my previous service, p99 latency stayed at 45 ms until we passed 180 concurrent connections per instance, then it rose to 310 ms because the database pool saturated. We found that in a test with 250 concurrent workers, not in production.

Evidence from my work

SituationWhat I didResult I can quote
Duplicate processing after a queue retryAdded an idempotency key stored with the response for 24 hours, and made the consumer check a processed message ID before writingDuplicate records fell from about 300 a week to zero in the following six weeks
Slow schema migration on a live tableSplit it into expand, backfill in batches of 5,000 rows, dual read, contractMigration completed over three releases with no downtime and no rollback
Pool saturation under peak loadRaised the pool from 20 to 40 per instance after the load test, and added a queue depth alert at 70 percent of pool usep99 at peak returned to under 60 ms

The trace I would walk through is the first one. A worker picks up a message, writes the order, then crashes before acknowledging. The queue redelivers it 30 seconds later. Without a check, the second delivery creates a second record. With the processed ID stored in the same transaction as the order, the redelivery finds the ID, returns the original result, and acknowledges. That is a small mechanism, but it is the difference between a retry being safe and a retry being a data problem.

Where my fit could fail

I tend to over design the first version. On a previous project I spent three weeks building a general reconciliation framework when the team needed one specific report. I caught it when a reviewer asked what would break if we deleted half the framework, and the honest answer was nothing. I now timebox that exploration and ship the narrow version first.

The other risk is pace. I am slower to accept a shortcut that skips a load test or an audit trail, even when a deadline is tight. If a team here routinely ships without those, we would clash. I would rather negotiate scope down, for example launch with two workflows instead of five, than launch five that I cannot defend under load.

I would close by asking what the team is currently finding hardest to keep reliable. Their answer tells me whether the work matches what I described, and it gives me something concrete to react to instead of a generic closing line.

Curated: · Written: · Reviewed:

Difficulty: Easy

Curated: · Written: · Reviewed: