
Real Interview Questions for the Cybersecurity Engineer at Elm
NewInterview Q&A
Q&A-1Compare TCP and UDP reliability, ordering, connection setup, and appropriate use cases?
Reported in Elm Software Engineer Interview Questions & Guide 2026
The 90-second answer
TCP gives you a reliable, ordered byte stream over an unreliable network. UDP gives you datagrams with no delivery promise, no ordering, and no connection state. That single choice drives everything else: latency, head-of-line blocking, how much state an attacker can exhaust, and what your application has to build itself.
| TCP | UDP | |
|---|---|---|
| Connection setup | 3-way handshake, 1 RTT before data (TCP Fast Open can cut this, with replay caveats) | None. First datagram is data. |
| Reliability | Sequence numbers, ACKs, retransmission, duplicate detection | None. A lost datagram is gone unless the app resends it. |
| Ordering | Bytes delivered in send order | Arrival order only. Datagrams can arrive out of order or duplicated. |
| Header overhead | 20 bytes minimum, 60 with options | 8 bytes fixed |
| Flow and congestion control | Sliding window, congestion window (CUBIC, BBR) | None. Sender can overwhelm the path. |
| State per flow | Socket, buffers, timers on both ends | Usually none in the kernel |
Connection setup, traced
Client -> Server SYN seq=1000
Client <- Server SYN, ACK seq=5000 ack=1001
Client -> Server ACK seq=1001 ack=5001
Client -> Server data...The handshake costs a round trip and creates state an attacker can target. A SYN flood sends SYN packets with spoofed sources. The server allocates a backlog entry for each, replies SYN-ACK, and waits. With a backlog of 128 and no SYN cookies, a few thousand packets per second can fill it and legitimate clients get dropped. Defences are SYN cookies, a larger backlog, and rate limiting at the edge. You see it in ss -s as a spike in TCP: ... syn_recv and in tcpdump 'tcp[tcpflags] & tcp-syn != 0' as many SYNs with no completing ACK.
UDP has no handshake to flood in that way, but it has a different abuse case. Because the source address in a UDP packet is not verified, an attacker can spoof a victim's address in a small DNS query. The server replies to the victim with a much larger response. That is DNS amplification, and it is why open resolvers and services that reply to unauthenticated UDP need response rate limiting and, where possible, TCP or DTLS for the sensitive path.
Reliability and ordering in practice
TCP retransmits a lost segment and holds later bytes until the gap fills. That preserves order and correctness, and it creates head-of-line blocking. On a lossy link, one dropped segment stalls everything behind it. For a 1200-byte payload, TCP overhead is about 1.7% before options. UDP is about 0.7%. The overhead difference rarely decides the protocol. The stall behaviour does.
UDP applications that need reliability build it themselves and pay for it. QUIC runs over UDP, adds stream IDs so one lost packet does not stall unrelated streams, and adds TLS 1.3 for encryption and integrity. DTLS does similar work for datagram protocols such as WebRTC media and DNS over DTLS. Plain UDP provides no integrity at all. A flipped bit in a syslog or telemetry datagram is delivered as-is unless the application checksums or signs it.
Where each fits
TCP: HTTPS and APIs, SSH, SMTP, database connections, file transfer, anything where a missing or reordered byte corrupts the result and where the peer can absorb retransmission delay.
UDP: DNS queries (small, idempotent, retry is cheap, and the client can fall back to TCP on truncation), DHCP, NTP, VoIP and video where a late packet is worthless and a retransmit would arrive after the playout deadline, multiplayer game state, and QUIC as a transport substrate.
The security question I ask first is not which protocol is safer in the abstract. It is what state the protocol creates, who can spoof it, and what the application assumes about delivery. TCP assumes the peer is who the handshake says it is, which is why TLS still has to authenticate it. UDP assumes nothing, which is flexible and dangerous when a service replies with more data than it received.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2How would you prioritize technical debt under pressure?
Reported in Elm Software Engineer Interview Questions & Guide 2026
The 90-second answer
I rank security debt by risk reduction per engineer-week, adjusted for exposure. Age alone does not move an item up the list, and neither does a stakeholder deadline. An externally exploitable flaw on an internet-facing service outranks a clean-up ticket for an internal tool, even if the clean-up is easier and the tool owner is louder.
I put four numbers on every item, each 1 to 5: exploitability, exposure, impact if exploited, and effort in engineer-weeks. Priority is (exploitability + exposure + impact) / effort. If an item blocks detection, I multiply the risk sum by 1.5 before dividing, because missing logs on a privileged service make every other risk harder to see. Two overrides come before the sort. Anything with a known exploited CVE, or a path to authentication bypass, jumps to the top regardless of score.
| Debt item (hypothetical example) | Exploit. | Exposure | Impact | Effort | Score | Rank |
|---|---|---|---|---|---|---|
| Unpatched VPN gateway, public CVE, internet-facing | 5 | 5 | 4 | 1 | 14.0 | 1 |
| No central alerting on admin logins to payment DB | 3 | 3 | 5 | 2 | 8.25 | 2 |
| Weak TLS config on internal reporting site | 2 | 2 | 3 | 1 | 7.0 | 3 |
| Service accounts with no MFA and shared secrets in code | 4 | 3 | 5 | 3 | 4.0 | 4 |
| Deprecated MD5 checksums in offline batch files | 1 | 1 | 2 | 4 | 1.0 | 5 |
The alerting item scores 8.25, not 5.5, because the detection multiplier applies: (3 + 3 + 5) * 1.5 / 2 = 8.25. It ranks second for that reason. Without those logs I cannot confirm whether the service account problem has already been abused, so fixing detection first also improves the evidence for the item below it.
How I run it under pressure
First, I separate compensating controls from fixes. If the VPN patch needs a maintenance window in three weeks, I can restrict the gateway to corporate egress IPs, disable the vulnerable service, or put it behind the WAF today. That buys time without pretending the debt is gone. I record the compensating control, its expiry date, and the owner who accepted the residual risk. No expiry, no deferral.
Second, I bundle debt with work already scheduled. If the team is touching the identity provider for a roadmap feature, adding MFA enforcement and rotating shared secrets costs days, not a separate project. If they are not, I do not let a feature ship that widens the debt, for example a new admin API with no audit logging. Blocking that one change is cheaper than retrofitting logs later.
Third, I make the trade-off visible in the same units stakeholders use. Instead of saying "security debt is high", I say: "Deferring the VPN patch saves one sprint but leaves a CVSS 9.8 flaw reachable from the internet. Our logs show one external scan hit per day, so the expected cost is an emergency patch plus a possible credential reset for 400 users." That arithmetic usually ends the argument.
A small script keeps the ranking honest when the list grows:
def priority(item):
if item["exploited"] or item["auth_bypass"]:
return float("inf")
risk = item["exploitability"] + item["exposure"] + item["impact"]
if item["blocks_detection"]:
risk *= 1.5
return risk / item["effort_weeks"]Failure modes I watch for
Scoring gets gamed when teams inflate impact to win a sprint slot. I require evidence for a 5 on exploitability, such as a public exploit or a scanner hit, and I re-score monthly. Patching without a rollback plan is another trap. I have seen a rushed OpenSSL upgrade break mutual TLS for service-to-service calls and force a rollback that left the flaw open longer. The fix is a canary host, a config snapshot, and a tested rollback before the window opens.
The last failure mode is deferring detection debt because it produces no visible feature. If we cannot alert on privilege escalation, we cannot bound the blast radius of any other item on the list. That is why logging and alerting for privileged paths often outranks a higher raw risk score on a narrower vulnerability.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3What 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 anchor on the OWASP Top 10 (2021) and answer by mechanism, not by list. For each class I would name how it is exploited in a real request, the control that stops it, and how I would know the control failed. The classes that cause most production incidents are broken access control, injection, cryptographic failures, authentication failures, and security misconfiguration. Everything else matters, but those five decide whether an attacker reads or changes someone else's data.
| Vulnerability | Concrete exploit | Mitigation that works | How I detect failure |
|---|---|---|---|
| Broken access control | GET /api/invoices/1042 returns another tenant's invoice because the handler checks login but not ownership | Deny by default. Authorize every object against the authenticated principal on the server, never trust a client-supplied tenant_id or role | Tests with two tenants swapping IDs; audit log of 403s on object endpoints |
| Injection: SQL, XSS, command | id=1 OR 1=1 in a query; <script> stored in a profile name and rendered to an admin | Parameterized queries and ORM bindings for SQL. Contextual output encoding plus a strict Content Security Policy for XSS. Never build shell commands from input | SAST rules for string-concatenated SQL; CSP violation reports; WAF logs for encoded payloads |
| Cryptographic failures | Password reset token in a URL over HTTP, or a JWT signed with a weak secret and no expiry | TLS everywhere with HSTS. Hash passwords with Argon2id. Sign tokens with a managed key, short expiry, audience and issuer checks | Certificate and header scans; token replay tests; secret scanning in CI |
| Authentication failures | Credential stuffing against /login with no rate limit, or session IDs that never rotate after login | MFA for privileged accounts, rate limiting and bot controls on login, rotate session on privilege change, short idle timeout | Login anomaly alerts by IP and account; impossible travel; spike in 401s |
| Security misconfiguration | Verbose stack traces, default admin credentials, a public S3 bucket, directory listing on /uploads | Harden the image, disable debug mode in production, least privilege IAM, security headers, automated config checks in CI | External scan for open ports, headers and exposed .git or backup files |
| Vulnerable components | A known CVE in a transitive dependency in the image | Pin and scan dependencies, rebuild on critical CVE, remove unused packages | pip-audit, npm audit, or Trivy in CI with a fail gate on criticals |
| SSRF | POST /fetch?url=http://169.254.169.254/latest/meta-data/ makes the server call cloud metadata | Allowlist URL hosts and schemes, block private and link-local ranges at the egress proxy, disable metadata service v1 | Egress logs showing calls to internal ranges; tests with internal URLs |
Injection, worked through. The vulnerable pattern is string interpolation into a query:
# Vulnerable: user input becomes SQL syntax
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
# user_id = "1 OR 1=1" returns every row
# Safe: the driver sends value and query separately (Python 3.12, psycopg)
cursor.execute("SELECT id, email FROM users WHERE id = %s", (user_id,))Parameterized queries do not sanitize the input. They remove its ability to change the structure of the query, so 1 OR 1=1 is compared as a literal string and matches no row. The same principle applies to XSS. Encoding is contextual: HTML encoding for body text, attribute encoding inside attributes, JavaScript encoding inside a script block. A CSP such as default-src 'self'; script-src 'self' then limits damage if encoding is missed, because inline injected scripts will not run.
Access control, worked through. Authentication answers who you are. Authorization must run per object. A handler that only checks if user.is_authenticated will pass a logged-in attacker straight to another customer's record. The fix is a check inside the handler, after loading the object: load invoice 1042, then compare invoice.tenant_id with the tenant from the verified token, and return 404 rather than 403 when they differ, so the endpoint does not confirm the object exists. I test this with a matrix of user A, user B, and admin roles against every object endpoint, and I log authorization denials with the principal, object ID, and decision. A sudden rise in denials after a deploy usually means a permission check was dropped in a refactor.
Where teams still get caught. Three patterns recur. First, client-side controls treated as security: hiding a button in the UI while the API still accepts the request. Second, trusting headers such as X-User-Id set by a proxy without verifying the proxy is the only path in. Third, logging failures: no audit trail for password resets, permission changes, or exports, so an incident has no timeline. I would require structured logs for authentication events, authorization denials, and data exports, shipped off the host, with alerts on volume changes.
If an interviewer pushes on priority, I would fix access control and injection first. They give direct data access with a single request. Cryptographic and configuration issues are next because they are cheap to fix at scale with templates and scanning. A WAF helps as a compensating layer, but it does not replace parameterized queries or server-side authorization, and I would say that explicitly.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Can 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, not atomicity. A write to a volatile field happens-before any later read of that same field, so the reader is guaranteed to see the new value and everything written before it. Without it, a thread can cache the value in a register or CPU cache and never notice the change, or the compiler and CPU can reorder writes around it.
I use it for a single flag or a single reference that one thread publishes and others poll. I do not use it for anything that needs a check and an update to happen as one step.
// Checked against Java 21, JLS 17.4.5
public final class Worker implements Runnable {
private volatile boolean running = true;
private volatile Config config; // immutable snapshot, swapped whole
public void stop() { running = false; }
public void reload(Config next) { config = next; }
@Override public void run() {
while (running) {
Config c = config; // one volatile read, consistent snapshot
if (c != null) c.apply();
}
}
}Here running is a stop signal and config is an immutable object published by reference. Both are safe because each operation is a single read or write.
What it actually guarantees
The Java Memory Model treats a volatile write as a release and a volatile read as an acquire. That has two effects. First, visibility: no stale cached value after the read. Second, ordering: writes before the volatile write cannot move after it, and reads after the volatile read cannot move before it. Non-volatile writes before the volatile write become visible too, which is why publishing an immutable object through a volatile reference is safe.
Trace for a non-volatile flag, which is the failure I see in shutdown code:
Thread A (main): running = false; // plain write, sits in A's cache
Thread B (worker): while (running) { } // plain read, keeps hitting its own cache
Result: B never exits. No exception, no log line. The process hangs on shutdown.With volatile, B's next read must go to main memory and sees false.
When it is the wrong tool
Volatile does not make a compound action atomic. This is the classic bug, and in a security context it shows up in rate limiters and counters:
private volatile int requests;
// two threads, each increments 1,000 times
requests++; // read, add, write: three steps, not oneTwo threads can both read 41, both write 42, and one increment is lost. A limiter built on that undercounts and lets traffic through. The same problem breaks check-then-act:
if (!locked) { locked = true; grantAccess(); } // two threads can both passFor those cases I reach for AtomicInteger or AtomicBoolean with compareAndSet, or a lock. The table I keep in my head:
| Need | Use | Why |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| Single flag or snapshot reference | volatile | Visibility plus ordering, cheap |
| Counter, increment, compare-and-set | AtomicInteger / AtomicLong | Atomic compound update |
| Check-then-act, multi-field invariant | synchronized or ReentrantLock | Mutual exclusion across fields |
| Lazy singleton, double-checked locking | volatile field plus lock on creation | Volatile stops a partially built object leaking |
One nuance worth stating: since Java 5, reads and writes of volatile long and double are atomic, whereas plain ones could tear on 32-bit platforms. That still does not make counter++ atomic.
Security angle
A stale read is not just a liveness bug. If a revocation flag, a feature kill switch, or a blocklist version is read as non-volatile, a node can keep serving revoked tokens or keep a disabled endpoint open long after the control plane flipped it. Volatile fixes the visibility part, but I still treat it as a hint for polling loops, not a security boundary. For anything where a missed update has a security cost, I pair the flag with a bounded poll interval and an expiry, so a stuck reader fails closed instead of running forever.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5What 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. Encapsulation means an object owns its state and only exposes operations that preserve its invariants. Abstraction means callers depend on a narrow interface, not on concrete types. Inheritance reuses behaviour by specialising a base type. Polymorphism lets different specialisations be used through that same interface.
In security code I treat inheritance as the last resort. It couples a subclass to every change in the base class, and in an authentication or scanning tool that coupling becomes a privilege problem: a subclass can accidentally widen what the base class was allowed to do. Composition, where an object holds collaborators behind interfaces, gives the same reuse without that coupling. I use inheritance mainly to express an is-a relationship that really holds, and to plug into a framework that expects it.
Worked example: auth handlers in Python 3.12
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class Principal:
user_id: str
scopes: frozenset[str]
class AuthHandler(ABC):
@abstractmethod
def authenticate(self, credential: str) -> Principal | None: ...
def require_scope(self, p: Principal, scope: str) -> bool:
return scope in p.scopes
class ApiKeyHandler(AuthHandler):
def __init__(self, keys: dict[str, Principal]):
self._keys = keys
def authenticate(self, credential: str) -> Principal | None:
return self._keys.get(credential)
class OidcHandler(AuthHandler):
def __init__(self, verifier):
self._verifier = verifier # composition: token verification is separate
def authenticate(self, credential: str) -> Principal | None:
claims = self._verifier.verify(credential)
if claims is None:
return None
return Principal(claims["sub"], frozenset(claims.get("scp", [])))
def login(handlers: list[AuthHandler], credential: str) -> Principal | None:
for h in handlers:
p = h.authenticate(credential)
if p is not None:
return p
return NoneTrace: login([ApiKeyHandler({...}), OidcHandler(v)], "key-123") calls authenticate on the first handler, gets a Principal, and returns it without knowing which handler produced it. That is polymorphism: the loop depends on AuthHandler, so adding a SAML handler later means writing one new class and adding it to the list. No existing handler changes. Encapsulation is visible in Principal being frozen, so a handler cannot mutate scopes after creation, and in OidcHandler keeping the verifier private.
| Approach | Reuse mechanism | When I use it | Main risk |
|---|---|---|---|
| Inheritance | Subclass inherits methods and state | Framework hooks, genuine is-a types | Fragile base class, accidental override of a security check |
| Composition | Object holds collaborators | Token verification, policy checks, logging | More wiring code, needs clear ownership |
| Interface only | Shared contract, no shared code | Plugin points such as AuthHandler | Callers must handle every implementation correctly |
Where this breaks in practice
The classic failure is a Liskov substitution violation. A base class promises that authenticate returns None on failure and never raises for a bad credential. A subclass that raises ValueError on an expired token breaks every caller that loops over handlers, turning a failed login into a 500 and, worse, sometimes into a bypass if the caller catches the exception and continues. I guard against this by keeping base class methods small and final where the language allows it, by testing each implementation against the same contract tests, and by making failure a return value rather than an exception for expected cases.
The second failure is inheritance used for code reuse instead of modelling. A AdminHandler that inherits from ApiKeyHandler just to reuse the key lookup, then overrides require_scope to always return True, has silently granted admin scope to anyone with a valid key. The fix is composition: AdminHandler holds an ApiKeyHandler and delegates, while scope checks stay in one place that security review can read.
A third failure is mutable shared state in a base class. If AuthHandler stored a per-request cache as an instance attribute, concurrent requests through the same handler instance would leak one user's principal to another. Encapsulation here means request state lives in parameters and return values, not on self, and shared collaborators are either stateless or explicitly thread-safe.
So my rule of thumb: define the interface first, implement with composition, and reach for inheritance only when the is-a relationship survives scrutiny and the base class is stable enough that subclassing it will not become a maintenance and audit burden.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6How 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 share a transaction across threads. It binds one database connection to the current thread, and every thread in the pool gets its own binding. When a method annotated @Transactional runs, Spring's proxy starts or joins a transaction, obtains a connection from the pool, stores it in a ThreadLocal via TransactionSynchronizationManager, and commits or rolls back when the outermost method exits. A second thread calling the same method gets a second connection and a second, independent transaction. That isolation is the whole design.
@Service
public class TransferService {
private final JdbcTemplate jdbc;
@Transactional(timeout = 5) // seconds, enforced by the transaction manager
public void transfer(long from, long to, long amount) {
jdbc.update("UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, from);
jdbc.update("UPDATE accounts SET balance = balance + ? WHERE id = ?", amount, to);
audit(from, to, amount); // same connection, same transaction
}
}Both updates and the audit insert use the connection bound to this thread. If the second update throws a RuntimeException, the proxy rolls back all three. If audit spawns a new thread, that thread sees none of it.
How the binding works
PlatformTransactionManager (usually JpaTransactionManager or JdbcTransactionManager) acquires a connection from the DataSource pool. TransactionSynchronizationManager holds it in a ThreadLocal map keyed by data source, plus a stack of synchronization callbacks. The proxy in TransactionInterceptor pushes that state on entry and, in a finally block, pops it and unbinds the connection when the outermost method exits. Because the state lives in the thread, there is no locking around the transaction itself. Concurrency control is delegated to the database: row locks, isolation level, and unique constraints.
Trace with a pool of 2 connections and 3 concurrent requests:
pool-1 transfer(1,2,100) -> conn A bound to pool-1, UPDATE 1, UPDATE 2, COMMIT
pool-2 transfer(3,4,50) -> conn B bound to pool-2, UPDATE 3, UPDATE 4, COMMIT
pool-1 transfer(5,6,10) -> conn A reused, fresh transaction, no state from request 1Thread reuse is where leaks happen. If application code sets a ThreadLocal (tenant id, SecurityContextHolder, MDC trace id) and forgets to clear it in a finally block, the next request on that pooled thread inherits it. Spring's interceptor clears the transaction binding it created, but it does not clear application ThreadLocal values. In a security review I check for that pattern in filters and @Async executors, because a stale principal or tenant id is an authorization bug, not just a memory leak.
Where multi-threading breaks the model
| Situation | What happens | Fix |
|---|---|---|
@Async or CompletableFuture.supplyAsync inside a @Transactional method | New thread has no bound connection. Each data access gets its own pooled connection in autocommit mode, so there is no shared transaction. | Pass data explicitly, start a new transaction in the worker, or use a transactional outbox |
Self-invocation: this.transfer(...) from another method in the same bean | Proxy is bypassed, no transaction starts | Inject a self proxy or split into two beans |
parallelStream() inside a transaction | ForkJoinPool threads have no binding, each statement grabs its own connection | Keep transactional work on one thread, parallelise outside it |
| Long transaction waiting on a lock or a slow HTTP call | Holds one pooled connection for the duration, pool drains under load | Keep transactions short, set timeout, move I/O outside |
Propagation decides what happens when transactional methods call each other on the same thread. REQUIRED (default) joins the existing transaction. REQUIRES_NEW suspends it and starts a fresh one on a second connection, which is how I implement audit logging that must survive a rollback of the business operation. NOT_SUPPORTED suspends and runs in autocommit. None of these propagate across threads. There is no safe way to hand a live connection to another thread, because the connection is not thread-safe and the ThreadLocal binding is invisible there.
Failure modes I would name in the interview
Rollback rules surprise people: by default only RuntimeException and Error trigger rollback. A checked exception commits unless you set rollbackFor = Exception.class. Silent commits after a failed business step are a data integrity issue I have seen in production.
Isolation is the other one. Spring does not impose an isolation level unless you set isolation on @Transactional, so the database default applies. PostgreSQL defaults to READ COMMITTED and Oracle also defaults to READ COMMITTED, while MySQL with InnoDB defaults to REPEATABLE READ. Under READ COMMITTED, two concurrent transfers can both read a balance of 100 and both debit 80. Spring will not save you there. The fix is a conditional update (UPDATE ... WHERE balance >= ? and check the row count), pessimistic locking with SELECT ... FOR UPDATE, or a serializable retry loop.
For a cybersecurity engineer the audit point matters most. If the audit record must be trustworthy, write it in the same transaction as the action it describes, or write it to an outbox table in that transaction and publish asynchronously. Writing it from a new thread after commit gives you an audit trail that can claim an action happened when the transaction rolled back, or miss an action that committed. That ordering gap is exactly what an attacker exploits when they probe error paths.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Can 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, initialization callbacks, readiness, and destruction. The order matters because initialization callbacks can fail the whole context, and because proxies are created late in the process.
Instantiation
-> Populate properties / setters / constructor injection
-> Aware callbacks: BeanNameAware, BeanFactoryAware, ApplicationContextAware
-> BeanPostProcessor.beforeInitialization
-> @PostConstruct
-> InitializingBean.afterPropertiesSet
-> init-method from @Bean(initMethod=...)
-> BeanPostProcessor.afterInitialization (AOP / security proxy created here)
-> Ready for use
-> Destruction: @PreDestroy, DisposableBean.destroy, destroy-methodPhase by phase
| Phase | What happens | Who controls it |
|---|---|---|
| Instantiation | Constructor or factory method runs, instance created | Spring container |
| Population | Fields, setters, or constructor arguments injected | Spring container |
| Aware callbacks | Bean learns its name, factory, or context | Interfaces on the bean |
| Before initialization | BeanPostProcessor can wrap, decorate, or validate the bean | Infrastructure beans |
| Initialization | @PostConstruct, then afterPropertiesSet, then configured init-method | The bean itself |
| After initialization | BeanPostProcessor can return a proxy instead of the raw bean | Infrastructure beans |
| Destruction | @PreDestroy, then destroy, then configured destroy-method | The bean itself |
A concrete example, checked against Spring Boot 3.x:
@Component
public class SigningService implements InitializingBean, DisposableBean {
@PostConstruct
void loadKeys() {
// Load key material, fail fast if missing or malformed
}
@Override
public void afterPropertiesSet() {
// Validate configuration after all properties are set
}
@Override
public void destroy() {
// Zero key material in memory, close resources
}
}The details interviewers probe
Scope changes destruction. Singleton beans are destroyed when the ApplicationContext closes. Prototype beans are created on demand and Spring does not call destruction callbacks for them, because the container loses track of the instance after handing it out. If a prototype holds a connection or key material, cleanup is the caller's problem.
Proxies appear in afterInitialization. That is where Spring AOP and Spring Security create the proxy that enforces method security and auditing. Code inside the bean calling its own method via this bypasses the proxy, so the security check never runs. That is a real failure mode in secured services, and the fix is self-injection through a proxy or moving the call to another bean.
Failure modes are concrete. An exception in @PostConstruct or afterPropertiesSet aborts context refresh and the application does not start, which is preferable to starting with a half-initialized signer or filter. A circular dependency between singletons can be resolved by Spring 5+ only in limited cases, and constructor-based cycles fail at startup with BeanCurrentlyInCreationException. Lazy initialization (@Lazy) defers creation until first use, which hides that failure until traffic arrives.
For a security review, I look at three points in this lifecycle: where secrets are loaded and whether failure is fail-fast, where BeanPostProcessor beans wrap beans with authentication or authorization proxies, and whether destruction actually clears sensitive state. A bean that loads a private key in @PostConstruct and never clears it in @PreDestroy leaves that material in the heap for the life of the JVM.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8What 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 inject a dependency into a bean: constructor, setter, and field. They all end up calling the same bean factory, but they differ in when the dependency is fixed, whether it can change later, and how visible it is in review. For security work I default to constructor injection, because it makes trust boundaries explicit and fails startup if a security bean is missing.
// Constructor: preferred in Spring Boot 3.x
@Service
public class OrderService {
private final PasswordEncoder encoder;
private final JwtDecoder jwtDecoder;
public OrderService(PasswordEncoder encoder, JwtDecoder jwtDecoder) {
this.encoder = encoder;
this.jwtDecoder = jwtDecoder;
}
}
// Setter: mutable after construction
@Service
public class LegacyService {
private PasswordEncoder encoder;
@Autowired
public void setEncoder(PasswordEncoder encoder) { this.encoder = encoder; }
}
// Field: hidden, reflection only
@Service
public class OldService {
@Autowired private PasswordEncoder encoder;
}| Constructor | Setter | Field | |
|---|---|---|---|
| Timing | At instantiation, before the bean is usable | After instantiation, via a method call | After instantiation, via reflection |
| Immutability | Fields can be final | Fields are mutable, can be re-set | Fields are mutable, can be re-set by reflection |
| Missing dependency | Startup fails with NoSuchBeanDefinitionException | Startup may succeed, failure moves to first call and can throw NullPointerException | Same as setter, and harder to spot in code review |
| Circular dependency | Fails fast, which exposes the design flaw | Silently allows a cycle, bean may be partially initialised | Silently allows a cycle |
| Testability | Pass fakes directly in new OrderService(fake, fake) | Pass fakes via setter, but object exists in an incomplete state first | Needs reflection or a Spring context to test |
| Audit visibility | Dependencies are the constructor signature | Dependencies are scattered across methods | Dependencies are annotations on fields, easy to miss in a diff |
Why this matters for security reviews
A missing PasswordEncoder or JwtDecoder is not a style issue. With constructor injection, an application that forgets to register the encoder will not start, and the pipeline catches it before deployment. With field injection, the bean starts, the field stays null, and the failure appears only when a login path runs. That is the difference between a failed health check and a runtime error on an authentication endpoint.
Setter and field injection also allow a dependency to be swapped after the bean has been created. In a normal application that is rarely intentional. In an incident review it complicates reasoning: which UserRepository, which ObjectMapper, which audit logger was actually in use when the request was handled? Constructor injection with final fields removes that question. The bean cannot be quietly reconfigured by another setter call or by reflection in a test or a compromised component.
There is a legitimate use for setter injection. Optional dependencies are the clearest case:
@Service
public class ReportService {
private final CoreClient core;
private AuditSink auditSink; // optional
public ReportService(CoreClient core) { this.core = core; }
@Autowired(required = false)
public void setAuditSink(AuditSink auditSink) { this.auditSink = auditSink; }
}That pattern is defensible when the dependency is genuinely optional and the code checks for null. It is not defensible as a way to work around a circular dependency between two security components. A cycle between, say, a filter and a service that depends on the filter usually means a responsibility is misplaced, and allowing it with a setter hides the problem until one side is called before the other is ready.
Failure trace I would expect to see
With constructor injection and a missing bean, startup logs show the exact chain:
UnsatisfiedDependencyException: Error creating bean with name 'orderService'
-> No qualifying bean of type 'JwtDecoder' available
Application run failedThe service never binds a port. With field injection the same misconfiguration produces a running application, a passing health check if the health endpoint does not touch that bean, and a NullPointerException on the first authenticated request. From a security standpoint the first outcome is far better, because a failed startup is visible in deployment logs and blocks traffic, while a lazy failure can be triggered selectively by an attacker probing the endpoint.
When I would not use constructor injection
Framework classes that need a no-argument constructor for proxies or for libraries that instantiate beans themselves, and the optional dependency case above. Outside those cases, if I see field injection in a controller or a security filter in a review, I ask what dependency it is hiding and why it cannot be in the constructor. In Spring Boot 3, with a single constructor, @Autowired is not even needed on that constructor. The signature is the documentation.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How 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: CPU, memory, database connections, or a single hot partition. Scaling blindly just moves the bottleneck and widens the attack surface. Assuming a typical stateless service in front of a stateful store, my order is: make the app tier stateless and horizontally scalable, put a load balancer and rate limiting at the edge, scale the data tier by partitioning only when a single node is proven insufficient, and add caching where the read pattern allows it. At each step I would keep authentication, authorisation, audit logging and encryption working under the new topology, because a design that is secure on one node often breaks at ten.
Step 1: Stateless app tier
Remove in-memory sessions and local files. Store session state in a shared store or use signed, short-lived tokens validated locally. That lets me add or remove instances behind a load balancer without sticky sessions, which also removes a single point of failure an attacker can target.
# Token validation cached locally, refreshed on a timer
# Avoids a call to the auth service on every request
class TokenValidator:
def __init__(self, jwks_url):
self.cache = {}
self.jwks_url = jwks_url
self.refresh()
def refresh(self):
self.cache = fetch_jwks(self.jwks_url) # keys, not secrets
def validate(self, token):
key = self.cache[token.kid]
return verify_signature(token, key) and not token.expired()Caching JWKS locally is the security-relevant detail. If 20 instances each call the identity provider per request, a traffic spike becomes a self-inflicted denial of service against the auth service, and a compromised instance cannot be contained by revoking one key.
Step 2: Edge and load balancing
Terminate TLS at the load balancer or CDN, enforce a WAF and rate limits before traffic reaches the app. Rate limiting has to be distributed. A per-instance counter lets an attacker multiply their allowance by the instance count.
| Layer | Scaling move | Security control that must scale with it |
|---|---|---|
| Edge | CDN, anycast, DDoS absorption | WAF rules, TLS policy, bot filtering |
| Load balancer | Round robin or least connections across AZs | Health checks that fail closed, connection limits |
| App tier | Stateless instances, autoscaling | Local JWKS cache, per-instance rate limit token bucket in Redis |
| Data tier | Read replicas, then sharding by tenant or key | mTLS between tiers, per-tenant encryption keys, audit log replication |
| Async tier | Queue for non-critical work | Signed payloads, dead-letter queue with alerting |
Step 3: Data tier, with arithmetic
Hypothetical figures to make the decision concrete: 10,000 requests per second, 80% reads. One app instance handles roughly 500 rps at 60% CPU in our load test, so I need 20 instances for headroom, spread across 3 availability zones. If the primary database saturates at 2,000 writes per second, read replicas help reads but not writes. Sharding by tenant_id then becomes the option, and I would accept its cost: cross-shard queries and transactions get hard, and I need per-shard encryption keys and consistent audit ordering. I would not shard on day one. Replicas plus a cache for hot reads usually buys an order of magnitude without that complexity.
Failure modes I would name in the interview
Cache stampede: when a hot key expires, hundreds of requests hit the database at once. Mitigate with request coalescing and jittered TTLs. Split-brain on failover: two primaries accepting writes. Mitigate with fencing tokens and a consensus-backed leader election, not a timer. Audit log loss under backpressure: if the log pipeline slows, the app must queue locally with a bounded buffer and alert at 70% full, rather than dropping security events silently. Credential sprawl: more instances means more places secrets live. Use short-lived credentials from a workload identity provider, rotated hourly, instead of long-lived keys baked into images.
The trade-off I would state plainly: horizontal scaling is cheap for stateless work and expensive for strongly consistent writes. If the workload is write-heavy and needs global consistency, I would rather scale the queue and batch writes than shard prematurely and lose transactional guarantees.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Explain how your prior experience and successes have prepared you for this role?
Reported in Elm Assessment and Interview Process: Candidate Guide
The 90-second answer
I spent the last four years in a SOC and incident response team for a payments processor handling about 2 million transactions a day, so the scale and the regulatory pressure at Elm are familiar ground. My day job was triaging alerts from EDR, WAF and cloud audit logs, hunting for credential theft, and closing the loop with engineering when a control failed. Two results I would point to: we cut mean time to detect for confirmed intrusions from roughly 4 hours to 45 minutes in 11 months, and we cut repeat findings from vulnerability scans by about 60 percent by fixing the patching workflow instead of just reporting CVEs.
That prepared me for this role in three concrete ways. I know how an alert becomes an incident, how an incident becomes a fix, and how to prove the fix worked when an auditor asks. I have also worked under the same kind of controls Elm operates against, including NCA Essential Cybersecurity Controls and SAMA requirements, so I am not learning the vocabulary on the job.
What I actually did, and what transfers
| Prior work | Evidence from that role | What it maps to here |
|---|---|---|
| SOC triage for 40 to 60 alerts per shift | Wrote Sigma rules for impossible travel and token replay, tuned to cut false positives from 18 percent to 6 percent over two quarters | Alert tuning and use case development for Elm's monitoring stack |
| Lead responder for a credential stuffing incident | Contained in 3 hours, forced password resets for 12,000 accounts, added rate limiting and device fingerprint checks at login | Incident playbooks, containment decisions, and post-incident follow up |
| Vulnerability management across 300 servers | Moved from monthly scans to risk based patching, critical CVEs patched within 72 hours, exceptions tracked with expiry dates | Patch prioritisation and exception handling that engineering will actually accept |
| Tabletop exercises with fraud and IT teams | Ran two exercises a year, one scenario produced a new runbook for payment gateway failover under attack | Coordinating across teams during a live incident, not just writing the plan |
A trace from the incident I led
02:14, alert fires: 400 failed logins in 10 minutes against the customer API, spread across 900 source IPs. 02:19, I check the WAF and application logs. Failures are concentrated on one endpoint and the user agents are identical. 02:31, I escalate to incident, block the top ASN at the edge, and enable a CAPTCHA challenge for that endpoint. 03:05, login success rate returns to baseline and no account takeover is confirmed. 09:00 next day, we ship a permanent fix: per account rate limiting, breached password screening at reset, and an alert on success rate dropping below 92 percent over 5 minutes. The lesson I took from that one is that detection without a pre approved containment step just gives you a faster view of the damage.
Where I am still growing
I have less depth in OT and industrial control environments, and I have not owned a full cloud migration security review end to end. I have supported one, reviewing IAM policies and logging coverage in AWS, and I know where I would need to lean on the cloud team and ask for the architecture diagrams early. I would rather flag that gap now than pretend the SOC experience covers it.
If I joined Elm, the first thing I would want to understand is which alerts the team trusts, which ones they ignore, and where the handoff to engineering breaks down. That is usually where the real risk sits, and it is where my previous wins came from.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: