Interview guides · Ambu
Ambu Software Engineer Interview Questions & Guide 2026
Code reading practice for Ambu software engineer prep: work out what unfamiliar code does before judging it.
The 60-second brief
As a Software Engineer at Ambu, you are at the intersection of medical innovation and digital transformation. Ambu is a leader in single-use endoscopy and diagnostic solutions, meaning your code doesn't just run on a server—it directly contributes to life-saving medical procedures and improves patient outcomes globally. You will be tasked with building robust, scalable software that powers next-generation diagnostic tools, bridging the gap between hardware sensors and clinical decision-making.
Ask how many rounds there are and what each one is before you plan your weeks, because the composition is what your hours should follow. A loop with three coding rounds and one short design conversation deserves a different split from the reverse, and whoever schedules it will usually say plainly which it is.
Focus areas
- Make HL7 and X12 ingestion idempotent under replay
- Authorise every identified read against current consent
- Version clinical results instead of updating rows in place
Overview
This role requires a unique blend of technical precision and a commitment to quality, as the software you develop must adhere to high safety and regulatory standards. You will work in a fast-paced, collaborative environment where your contributions have a tangible impact on the efficiency of healthcare providers. If you are passionate about engineering software that makes a meaningful difference in the medical field, this position offers a rare opportunity to influence the future of healthcare technology.
The Ambu interview process
Ambu candidates report 2 rounds · ≈ 2-4 weeks. The stages below are what candidates describe, not a published process.
Direct Manager Discussion
Because the format is not fixed, the first job in the room is classification. Listen to the opening question and decide what it is: a probe into work you have already described, a fresh problem to solve now, or a conversation about how you operate. Each wants a different register, and the common failure is forcing a rehearsed structure onto a question that did not ask for it. Running a full design ritual on a ten-minute debugging question reads as not listening. When you cannot tell which it is, ask how long they want to spend and answer at that depth.
What to demonstrate
- Whether the shape of your answer matches the question, so a yes-or-no gets answered before it is justified and an open prompt gets a direction before a detour
- Whether you check how much depth is wanted instead of deciding for them, and whether you stop when the answer is complete rather than continuing until someone interrupts
- Whether you can be redirected in the middle of an answer without restarting it from the beginning
- Whether a question outside your experience gets an honest boundary followed by reasoning from what you do know, instead of a confident answer with nothing behind it
How to prepare
- Rehearse one project at three lengths, roughly thirty seconds, three minutes, and a full walkthrough at the depth of a design review, and practise switching between them when someone interrupts mid-telling
- Have someone ask you five questions of deliberately mixed type in one sitting without telling you the types, and score only whether you identified each one correctly before you started answering
- Draft the sentence you will use to check depth, along the lines of asking whether the short version is useful here or they want the detail, and use it in a real conversation this week so the day of the round is not its first outing
Leadership Discussion
An unlabelled round is first an information problem, and the cheapest information is free. Whoever schedules it can usually tell you how long it runs, who will be in the room and what they work on, whether you will be writing code and in what environment, and whether anything is being sent beforehand. Ask in writing so the answer is on record, then prepare for the two or three formats those answers still leave open instead of betting on one. What separates a strong candidate is not guessing right; it is having an opening that works whichever one it turns out to be.
What to demonstrate
- Whether you can start work from an ambiguous brief, since tolerating a vague scope without stalling is the same thing the job asks for
- Whether the questions you asked beforehand were ones that change your preparation, such as duration, medium and who is joining, rather than ones whose answers you could not have acted on
- Whether you adapt when the round turns out to be something other than what you were told, instead of spending the first ten minutes visibly recalibrating
How to prepare
- Send one short scheduling message asking four things: how long, who is joining and what they work on, whether you will be writing code and where, and whether to prepare anything in advance. Treat a vague reply as real information, since it means the round is loosely structured and you will be shaping it yourself.
- Write one opening that works in any of the formats still open: restate in your own words what you have been asked to do, then ask which of two directions is more useful to them. Say it aloud until it stops sounding recited.
- Set up for the two most likely formats before the call starts, with a blank editor in the language you would choose and a shared document you can type into, so a format surprise costs you nothing in the first minutes
Where candidates lose points
Treating a medical record number or a member ID as a globally unique key and joining on it directly.
These identifiers are unique only within the authority that issued them. Two facilities in one network routinely have the same medical record number for different people, and member IDs get reissued when someone changes plans. Joining on the bare value merges two patients' records, which is the most damaging failure available in this domain, and it passes every test written against a single-facility fixture because the collision only appears once a second source is connected.
Upserting on the order or result identifier, so a correction overwrites the original row.
It makes the question 'what did the clinician see at 14:02' unanswerable, which is exactly what an incident review or a legal hold asks. It also leaves downstream consumers that already acted on the preliminary value with no correction event to react to, because the state transition was collapsed into a single mutated row and never emitted.
Treating a network call as though it were a local function call
A remote call can be slow, fail, or return after you stopped waiting, so name the timeout, the retry policy, and what the caller sees while the dependency is down. A call with no timeout turns one slow dependency into an exhausted thread or connection pool in every service upstream of it.
Optimising an axis nobody named
Ask which resource is actually scarce here: wall-clock latency, throughput, memory footprint, cost per request, or engineering time. Shaving a constant factor off an in-memory step is wasted effort when the same function makes a blocking remote call inside the loop.
Questions & practice
Sum surviving claim versions in one pass over unordered lines
Easy · hash map · versioning · streaming aggregation
You are streamed up to 50 million claim_line records in arbitrary order: claim_id, claim_version, line_number, frequency_code (original, replacement, void), enterprise_person_id, allowed_amount_cents. Every version of a claim shares its claim_id, and a replacement arrives as a higher claim_version. Return total allowed_amount_cents per enterprise_person_id, counting each claim once at its highest version and contributing zero when that version is a void. Amounts are non-negative int64 minor units. Target O(N) time and O(C) space for C distinct claims, single pass, no sort.
Approach
- Say the two grains out loud before writing anything: the version lives at claim grain, the money lives at line grain. Every wrong answer here comes from applying a claim-level rule with a line-level filter.
- Keep one hash map from claim_id to a small record (best_version, sum_cents, person_id, is_void). Per line: if claim_version is greater than best_version, reset sum_cents to this line's amount and overwrite the person and void flag; if equal, add to it; if lower, discard the line. That reset is what makes the pass order-independent, so a replacement arriving before its original still wins.
- Resolve the void at the end, not at ingest. A void only nullifies the claim if it is the surviving version, and zeroing on sight would let an earlier replacement that arrives later resurrect the money.
- Fold the C claim records into a person-keyed map in a second phase, O(C). Do not accumulate into the person total during the stream: you cannot subtract a superseded version you have already forgotten.
- Cost is O(N) time, O(C) space. The sort-based alternative, group by (claim_id, claim_version) and keep the max, is O(N log N) and needs the set resident; prefer it only when C approaches N and the map will not fit.
- Keep cents in int64 throughout. Fifty million lines at a realistic per-line ceiling stay four orders of magnitude below 2^63, so the integer type costs nothing and removes the float drift class entirely.
Worked solution (20 min)
- Define the per-claim record and the three-way comparison on claim_version: greater resets, equal accumulates, lower discards.
- Run the stream once, touching only the claim map.
- Walk the claim map, skipping entries whose surviving version is a void, and add each remaining sum into a person map.
- Return the person map sorted descending by total.
Expected result: Claim A: version 1 has lines of 12000 and 8000 cents, version 2 (replacement) has lines of 9000, 8000 and 500. Claim B: version 1 has a single line of 5000, version 2 is a void carrying one zero-amount line. Both claims belong to one person. Your answer is 17500 cents, from claim A's version 2 only. The naive sum over all seven lines is 42500.
Verify it yourself
- The number of claims contributing equals the number of distinct claim_ids whose highest version is not a void.
- For a multi-line claim, the addends in its sum equal that surviving version's line count, not one.
- Shuffling the input and re-running produces an identical result, which is the property the reset-on-higher-version rule buys you.
- The all-rows sum is greater than or equal to your total, equal only when no claim has a version above 1 and none is a void.
Follow-up
- You shard the stream across eight workers. Sharding by hash of claim_id works; what exactly breaks if you shard by enterprise_person_id instead?
- A replacement arrives for a claim_id whose original never appears in the batch. What does your map produce, and is that the financially correct answer or a reconciliation break?
- The same claim_id is reused by two different submitting organisations. How does the key have to change, and when would you have noticed?
Flag a requester reading too many distinct charts per window
Medium · sliding window · two pointers · distinct count
You consume access-audit records (event_ts, requester_id, enterprise_person_id, purpose_of_use, break_glass) at tens of thousands per second, non-decreasing in event_ts. For each requester, emit an alert the first time any sliding 600-second window contains reads of more than D distinct enterprise_person_ids. Break-glass reads count toward the window and are also reported separately. Return (requester_id, window_start_ts, distinct_count). Target O(1) amortised per event and memory proportional to the events resident in the window, not to the day.
Approach
- Per requester, hold a deque of (event_ts, person_id) and a hash map from person_id to its occurrence count inside the window, plus a running distinct counter. Push on the right; while the front is older than event_ts minus 600 seconds, pop it, decrement its count and erase the key when the count reaches zero, decrementing the distinct counter. Each event is pushed once and popped once, so the amortised cost is O(1) and the memory is O(W) for window occupancy W.
- Test the threshold immediately after each push and nowhere else. Between two consecutive events the window can only lose members as its left edge advances, so the maximum distinct count over all window positions is attained at a position whose right edge is an event. Checking at pushes is therefore exhaustive rather than a sampling approximation.
- Latch the alert per requester and re-arm only when the distinct count falls back below D, otherwise one busy stretch emits thousands of near-identical rows and the real signal is buried by its own volume.
- Bound memory both per requester and globally. A requester whose window legitimately holds tens of thousands of reads must not hold the process hostage, so cap the deque and degrade above the cap to an approximate distinct counter such as HyperLogLog, stating the error you accept in exchange.
- Count break-glass toward the window but carry it in its own output field. Break-glass has to succeed during an emergency, which is exactly why it must be the most visible path in the audit, and excluding it from the count would make the abuse route the quiet one.
- State the precondition: this is correct only while input is non-decreasing in event_ts. Out-of-order arrival needs a bounded-lateness buffer and a watermark, and dropping late events without a counter is the failure that hides itself.
Follow-up
- One region's events arrive up to 90 seconds late. What buffer do you add, and what does that do to alert latency?
- One person uses two requester accounts. What has to change in the key, and what new false positive does that introduce?
- How do you restore window state after a process restart without replaying the whole day?
Group transfer-chained encounters into episodes with out-of-order arrival
Medium · graph traversal · cycle detection · memoisation
You have up to 5 million encounter rows for a reporting month, in arbitrary order: encounter_id, enterprise_person_id, facility_id, encounter_class, admit_ts, discharge_ts (nullable), status, prior_encounter_id (nullable, set on transfer), source_event_ts. prior_encounter_id may reference a row that arrives later or never arrives. Group rows into episodes, one per maximal transfer chain, returning episode root, person, earliest admit_ts, latest discharge_ts (null if any member is still open) and member count. Report cycles instead of following them. Target O(N) expected time.
Approach
- Recognise the shape: every row has at most one prior_encounter_id, so this is a forest of parent pointers, not a general graph. A hash map from encounter_id to row is the whole index you need, and the work is O(N) expected rather than anything sort-shaped.
- Resolve roots by iterative pointer-following with write-back memoisation: from each node walk prior_encounter_id until you reach a node with no parent, a parent absent from the input, or a node whose root is already known, then stamp the discovered root onto every node on that path. Each node is finalised once, so total work stays O(N) even when one chain is very long.
- Do not recurse. A malformed feed can produce a chain tens of thousands deep, and a recursive resolver dies on stack depth taking the whole batch with it. An explicit loop with write-back is both faster and bounded.
- Detect cycles with three-state marking: unvisited, on the current path, finalised. On reaching a node that is on the current path, emit a data-quality record naming every encounter_id in the cycle and exclude that component from the episode output. Choosing an arbitrary root instead would produce an episode that looks plausible and will be believed.
- Keep a dangling prior_encounter_id distinct from a genuine root. It means the chain starts outside the window or has not arrived, so flag the episode left-truncated and carry that flag into the output: an episode with an unknown start cannot be used for length of stay or readmission counting without biasing both downward.
- Compute aggregates during the same pass that assigns roots: minimum admit_ts, maximum discharge_ts with null propagation so any open member leaves the episode open, and exclude cancelled and entered_in_error members from the aggregates while keeping them retrievable.
Follow-up
- Two encounters name each other as prior_encounter_id. What does your detector emit, and who needs to see it?
- One episode spans two facilities whose clocks differ by four seconds. Do you order on source_event_ts or admit_ts, and what does the choice cost?
- A chain is cut in half by the month boundary. What does this month's report say, and how do you make next month's agree with it?
Reproduce and fix a lost update on a deductible accumulator
Medium · isolation levels · lost update · lock contention
An accumulator row holds deductible_applied_cents bigint and plan_deductible_cents bigint, keyed by (enterprise_person_id, plan_id, benefit_year). The adjudicator opens a transaction, SELECTs the row, computes the member's share in application code, then UPDATEs the row to the absolute new total it computed, all under PostgreSQL's default READ COMMITTED. Two claim lines for one member adjudicate concurrently: both charge the member deductible, but the accumulator advances by only one of the two amounts, so the member is billed deductible again on a later line after the plan deductible has already been met. Write the exact two-session interleaving that produces it. Then give three fixes, each naming the lock or isolation level, the SQLSTATE you must handle, and the throughput cost.
Approach
- State the anomaly precisely. READ COMMITTED takes a fresh snapshot per statement, so it prevents dirty reads but permits a lost update when a transaction reads a value, computes outside the database, and writes back an absolute result. The vulnerable window is the round trip through application code between two statements, not the transaction boundary — the same logic expressed as one relative UPDATE is safe at this very isolation level.
- Write the interleaving as an ordered script both sessions can be replayed from, with the commit points marked, and make both writes absolute (SET deductible_applied_cents = :computed_total). The point is not that two writes happen — it is that the second write stores a total computed from a value that had already been superseded by the time it landed.
- Fix one, SELECT ... FOR UPDATE on the read: the second session blocks on the row lock and, under READ COMMITTED, re-reads the newest committed version when it unblocks, so its computation starts from the winner's total. No serialization error to handle. Cost is serialised throughput per member and a lock held for the transaction's whole duration, so nothing inside may call an external payer.
- Fix two, REPEATABLE READ or SERIALIZABLE with a retry loop: in PostgreSQL, REPEATABLE READ aborts the second writer of a row with SQLSTATE 40001, 'could not serialize access due to concurrent update'; SERIALIZABLE additionally aborts on read/write dependencies detected by SSI, also under 40001. The retry re-runs the whole transaction, so the claim application must be idempotent or keyed by claim_line_id, or a retry double-applies.
- Fix three, single-writer partitioning: route by hash(enterprise_person_id) to one consumer per partition, so no two transactions ever touch one accumulator. No locks, no retries; the cost is head-of-line blocking behind a slow claim, rebalancing during deploys, and losing the ability to scale a hot member.
- Name the cheapest option and its real catch. A single UPDATE ... SET deductible_applied_cents = LEAST(plan_deductible_cents, deductible_applied_cents + :amt) ... RETURNING deductible_applied_cents does not lose the update: under READ COMMITTED an UPDATE that hits a concurrently updated row blocks, then re-evaluates its expressions against the newly committed version, so both increments land. The catch is that the member's share is the delta this statement actually applied, which is the returned value minus the row's pre-image — and RETURNING does not expose the pre-image before PostgreSQL 18's OLD/NEW aliases. On earlier versions you must read that pre-image under the same row lock, which puts you back in fix one with a shorter critical section. The one-statement form is a clean fix only when the caller does not need the delta.
Follow-up
- A claim is reversed six months later under a plan design that has since changed. What amount does the reversal subtract, and where is that number stored?
- Your retry loop hits 40001 repeatedly for one member during a batch window. What is the backoff, and at what point do you stop retrying and pend the claim?
- Which of the three fixes survives a retroactive eligibility change that invalidates everything applied in the last month, and what does the rebuild look like?
Diagnose why an eligibility lookup ignores its index
Medium · indexing · query planning · partial indexes
A 40-million-row coverage_span serves eligibility lookups with: SELECT coverage_id, plan_id, coverage_order FROM coverage_span WHERE enterprise_person_id = $1 AND valid_to = 'infinity' AND effective_date <= $2 AND (termination_date IS NULL OR termination_date >= $2). An index exists on (effective_date). EXPLAIN (ANALYZE, BUFFERS) shows a sequential scan reading 1.8 million buffers at 2.4 seconds. Explain why that index cannot help, propose the index plus any schema change that makes the predicate index-friendly, and state what you expect the new plan and buffer count to be.
Approach
- Read the predicate for selectivity before touching the index. effective_date <= $2 matches most of a 40-million-row history, so a leading range scan on that column returns a large fraction of the table and the planner correctly prefers a sequential scan over millions of random heap fetches. The index is not being ignored; it is being rejected on cost.
- Put the equality column first. enterprise_person_id = $1 selects a handful of rows out of 40 million, so it must lead the composite index; a b-tree can only use columns after the first range predicate as filters, not as search bounds.
- Turn the open-ended termination into something indexable. The OR ... IS NULL branch forces either a BitmapOr or a post-index filter. Add coverage_end date GENERATED ALWAYS AS (COALESCE(termination_date, DATE '9999-12-31')) STORED and rewrite the predicate to coverage_end >= $2; both COALESCE over a column and a date literal are immutable, so the generated column is legal.
- Make the index partial on WHERE valid_to = 'infinity'. Most rows in a bitemporal table are superseded beliefs, so the partial index is a fraction of the full one, stays in cache, and encodes the predicate for free rather than re-checking it per row.
- Consider the range alternative honestly: a daterange(effective_date, termination_date + 1, '[)') column with a GiST index and the && operator handles overlap queries and supports an EXCLUDE constraint against overlapping active coverage, but GiST lookups are slower than b-tree for this point-in-time pattern. Pick b-tree for the read path and keep GiST only if you also need the overlap constraint.
- Verify rather than assert: re-run EXPLAIN (ANALYZE, BUFFERS) and read Rows Removed by Filter and the shared hit/read split, not just the total time.
Worked solution (30 min)
- Run EXPLAIN (ANALYZE, BUFFERS) on the original and write down estimated versus actual rows for each predicate, which shows effective_date <= $2 is not selective.
- Add the generated column and rewrite the predicate to use coverage_end.
- Create the partial composite index and ANALYZE the table so the planner has statistics for the new column.
- Re-run EXPLAIN (ANALYZE, BUFFERS) and confirm an index scan with Rows Removed by Filter at or near zero.
- Measure the partial index size against the full-table equivalent with pg_relation_size to confirm the cache argument is real and not assumed.
Expected result: The (effective_date) index is rejected because effective_date <= $2 is a low-selectivity leading range predicate over 40M rows; the planner's estimated cost of random heap access exceeds a sequential scan. Fix: ALTER TABLE coverage_span ADD COLUMN coverage_end date GENERATED ALWAYS AS (COALESCE(termination_date, DATE '9999-12-31')) STORED; CREATE INDEX CONCURRENTLY idx_coverage_active ON coverage_span (enterprise_person_id, effective_date, coverage_end) WHERE valid_to = 'infinity'; and rewrite the last predicate as coverage_end >= $2. The new plan is an Index Scan on idx_coverage_active, Rows Removed by Filter near zero, buffers in the low tens rather than 1.8 million, and sub-millisecond execution.
Verify it yourself
- Buffers drop from roughly 1.8 million to double digits — an order-of-magnitude change in buffers, not just in wall-clock time, is what proves the index is doing the work.
- Rows Removed by Filter is 0 or near it; a large value means a predicate is still being re-checked per row and belongs in the index or the partial clause.
- The rewritten and original predicates return identical rows for a member with an open-ended coverage and for one terminated exactly on $2.
- pg_relation_size on the partial index is a small fraction of the same index built without the WHERE clause.
Follow-up
- After the change the plan is still a sequential scan for one particular member. What single query tells you whether that is stale statistics, a genuinely huge row count for that person, or parameter-dependent plan caching?
- Your generated column needs backfilling on a live table. Does adding a STORED generated column rewrite it, and what does that mean for your maintenance window?
- How would you serve the same lookup when the answer must be as of a past system-time instant rather than the current belief, given your index is partial on valid_to = 'infinity'?
Can you walk us through your most relevant professional experience as it relates to this role?
Medium
Approach
- Work from the requirement backwards to the design.
- Clarify what is being asked and what a complete answer contains.
- Say what you would check first and why it is the highest-information step.
Follow-up
- How would you know your answer was wrong?
- What assumption would you test first?
What draws you to the intersection of software engineering and the medical device industry?
Medium
Approach
- Say what you would check first and why it is the highest-information step.
- Clarify what is being asked and what a complete answer contains.
- Work from the requirement backwards to the design.
Follow-up
- What assumption would you test first?
- How would you know your answer was wrong?
What specific technical challenges have you overcome in your previous software projects?
Medium
Approach
- State your assumptions explicitly before working the problem.
- Clarify what is being asked and what a complete answer contains.
- Say what you would check first and why it is the highest-information step.
Follow-up
- What assumption would you test first?
- How would you know your answer was wrong?
Composite patient summary reads over versioned clinical resources
Medium · fan-out · tail-latency · partitioning · versioning
The longitudinal record service serves a patient summary that fans out across eight to twelve resource types — encounters, observations, orders, medications and others — over billions of versioned rows, where a correction inserts a new version and points at the row it supersedes rather than updating in place. Reads outnumber writes about twenty to one. The number that matters is the p99 of the composite read, not of any single resource call. Give the partitioning key, the index and predicate that select current versions, and the mechanism that stops one slow resource type from setting the whole summary's p99.
Approach
- Partition by enterprise_person_id on a hash, because every read in this path is patient-scoped: each resource type's fan-out then lands on one partition, and no summary becomes a scatter-gather across the whole keyspace. Partitioning by time instead optimises the analytical query at the expense of the query that runs twenty times per write.
- Make current-version selection a cheap predicate rather than a computed one. NOT EXISTS against supersedes_observation_id is an anti-join on every read; a superseded_at column written in the same transaction as the correction, with a partial index on (enterprise_person_id, loinc_code, collected_ts DESC) WHERE superseded_at IS NULL, turns it into an index range scan. You pay one extra write per correction and take on the obligation to keep the flag consistent with the supersedes pointer.
- Do the tail arithmetic before choosing a mechanism. If ten subcalls are independent, the probability that at least one exceeds its own p99 is 1 - 0.99^10, about 9.6%, so the composite p99 sits near each subcall's p99.9. Independence is the precondition and shared storage makes it optimistic, so budget backwards from the composite target to a per-call p99.9.
- Attack the tail rather than the median: issue subcalls concurrently with a per-call deadline well inside the composite budget, hedge to a second replica when a call passes its p95, and return the summary with a per-section unavailable marker when a non-critical resource type misses. A summary missing one section is clinically usable; a summary that arrives four seconds late is not.
- State what you will not do: no long-lived cache of the assembled summary. Amendments and corrections are ordinary traffic, and a stale composite is exactly the failure the versioned model exists to prevent. Cache per resource version under an immutable key instead, so a correction produces a new key rather than requiring invalidation.
Worked solution (30 min)
- Write the current-version query two ways — anti-join and partial index on a maintained flag — and compare the plan shape each produces.
- Compute the composite p99 implied by ten independent subcalls at a given per-call p99, and derive the per-call p99.9 your budget actually requires.
- Write the per-call deadline, the hedge trigger and the degradation rule, marking which sections may be omitted and which may not.
- Name the partition key and trace one summary read through it, counting partitions touched.
Expected result: Hash partitioning on enterprise_person_id, a maintained superseded_at flag with a partial index making current-version selection an index range scan, a per-call budget derived from the composite target via the independence calculation, concurrent subcalls with hedging and per-section degradation, and per-version immutable caching instead of a cached composite.
Verify it yourself
- Every subquery in the summary carries the current-version predicate; grep the fan-out and count.
- Amending one observation changes the summary on the next read with no invalidation step.
- Injecting 500ms of latency into one resource type leaves the composite p99 inside budget with that section marked unavailable.
- A single summary read touches one partition per resource type, not all of them.
Follow-up
- A correction commits midway through the fan-out, so one section reflects it and another does not. What consistency do you promise the reader, and how do you express it in the response?
- Hedging doubles load on the slowest replica at precisely the worst moment. How do you bound the hedge rate without losing its benefit?
Nightly adjudication throughput collapses with deadlocks on accumulators
Medium · deadlock · lock ordering · isolation levels
During the nightly claims batch, throughput collapses from 4,000 to about 300 claim lines a second for minutes at a time. pg_stat_database.deadlocks climbs, the PostgreSQL log carries deadlock detected with SQLSTATE 40P01, and the application retries the aborted transactions. Benefit application and the reversal handler both take SELECT ... FOR UPDATE on the member's deductible accumulator row and on the out-of-pocket accumulator row. Diagnose in order, then give a fix that removes the cycle by construction rather than by retrying faster.
Approach
- Read the deadlock report before theorising. PostgreSQL logs both process IDs, the statement each was running and the relation and tuple each was waiting on, which names the two lock-acquisition orders directly. There is no need to guess which code paths collide or to reproduce it first.
- Separate deadlock from ordinary contention. pg_stat_database.deadlocks counts cycles, while log_lock_waits reports waits longer than deadlock_timeout that never form a cycle. Collapsing throughput with few recorded deadlocks means a hot row — one family plan's shared accumulator — is serialising the batch, which has a different remedy from a cycle.
- Account for the detector's cost. A cycle is only detected after deadlock_timeout, one second by default, so every deadlock burns at least that on both sides plus the retried work. Raising the timeout lengthens each stall; lowering it raises the frequency of the detector's checks. Neither is a fix, and both are common first answers.
- Reject the two reflex answers explicitly. SERIALIZABLE does not prevent deadlocks in PostgreSQL — row-level lock cycles still occur and serialization failures with SQLSTATE 40001 are added on top — and a larger connection pool simply puts more transactions in contention for the same rows.
- Remove the cycle by construction: make each member's benefit application take exactly one lock. Either fold both accumulators into a single row keyed (enterprise_person_id, plan_id, plan_year) and update it in one statement, or take pg_advisory_xact_lock over a hash of that key as the first statement of both paths. One lock cannot form a cycle with itself. Deterministic ordering via ORDER BY ... FOR UPDATE also works but depends on the chosen plan preserving that order, so it is a weaker guarantee; hash collisions in the advisory-lock variant only serialise two unrelated members, which is safe but costs throughput.
- Then bound the transaction. No external call may sit between acquiring the lock and committing, or the row is held for a network round trip and the hot member serialises the batch regardless of which deadlock fix you chose.
Follow-up
- A reversal arrives for a claim adjudicated under a plan design that has since changed. What amount does it subtract, where is that amount recorded, and is that still atomic under your single-lock design?
- Remove the FOR UPDATE entirely and show the exact two-session interleaving that produces a lost update under READ COMMITTED, then say why a single UPDATE ... SET remaining = remaining - $1 does not have the same problem.
Suggested practice checklist
Day one measures instead of guessing, under a fixed rubric, and the remaining hours are allocated in proportion to the gaps before any studying begins. The allocation is deliberately not renegotiated midweek, because the area that feels worst on day three is usually the one that is moving.
Day 1 — Diagnostic, scored before you study anything
- Sit a 110-minute diagnostic in four blocks: forty-five minutes on two coding problems, twenty-five on one design prompt taken to interface and data model, twenty of short-answer fundamentals, and twenty delivering two behavioural answers aloud.
- Score each block from 0 to 3 on a fixed rubric where 3 is correct and fluent, 2 is correct but slow or prompted, 1 is partially correct and 0 is stuck, grading the artifact rather than how the attempt felt.
- Allocate days two to five in proportion to 3 minus each block's score, write the allocation down, and commit to leaving it alone.
Deliverable: A scored rubric and a fixed hour allocation for the rest of the week.
Day 2 — Largest gap: find the boundary rather than the subject
- Split the weakest area into named sub-skills and rate each separately. For coding those are restating the problem, choosing the structure, stating the invariant, turning the invariant into loop bounds, handling empty and single-element input, and accounting for complexity out loud.
- Attempt three items positioned just above where the rating drops off, and for each write the first move you failed to make.
- Re-attempt one of them from blank four hours later with nothing open.
Deliverable: A sub-skill map with the two blocking sub-skills circled.
Day 3 — Drill the blocking sub-skill by repeating the shape
- Do eight short repetitions of the same shape rather than eight different problems, so what gets practised is the pattern and not the puzzle.
- State the rule you now hold in one sentence, then test it against a case built to break it, a sliding window over an array containing negative values, or a cache-aside read path whose invalidation message is dropped.
- Have someone else read your one-sentence rule and find the precondition you left out.
Deliverable: One rule statement with its preconditions attached and one counterexample that would have caught the incomplete version.
Day 4 — Second gap, plus maintenance on the strongest area
- Run the same sub-skill decomposition on the second-largest gap in half the time.
- Spend twenty-five timed minutes on the block you scored highest, choosing the hardest item you can still finish rather than a warm-up.
- Write whether each area fails you on recall, on setup, or on execution, and set the fix accordingly: repetition for recall, a written checklist for setup, timed work for execution.
Deliverable: A second sub-skill map plus a one-line failure diagnosis for each area.
Day 5 — The gap that is not a skill
- Record one technical and one behavioural answer, then count two things in the playback: seconds before your first clarifying question, and sentences you began without knowing where they would end.
- Practise saying that you do not know, followed by how you would find out, without letting it soften into a guess, and practise stating a complexity or an estimate before being asked for it.
- Redeliver one answer under a hard ninety-second cap, which forces structure ahead of detail.
Deliverable: Two recordings with a counted reduction in time-to-first-question.
Day 6 — Retest under day-one conditions
- Sit the same 110-minute structure with new prompts of comparable difficulty and score it on the identical rubric.
- For any block that did not move, change the method rather than adding hours: a block stuck at 1 usually means the practice was too varied, not too short.
- Write down which single block you would still lose the offer on.
Deliverable: A second scored rubric placed beside the first, with one named remaining risk.
Day 7 — Full loop under interview conditions
- Run a sixty-minute mock over the two blocks that moved least, with an interviewer briefed to interrupt and change direction mid-answer.
- Write the recovery script for going blank: restate the question, state your assumption, name the first thing you would check.
- Say every rule from the week aloud without reading it, and cut any you cannot state in a single sentence, since a rule you have to reconstruct mid-answer will not survive an interruption.
Deliverable: A one-page card holding the recovery script and only the rules you could state from memory.
The estimate and the day you knew
A slipped date is only a bad story if you sat on it. What matters is what you believed when you gave the number, the signal that told you it was wrong, how many days passed before you said so, and what you cut rather than asking for more time. Scope you defended counts as much as scope you dropped.
How do you handle working in a highly regulated, high-stakes environment?
Medium · behavioural and engineering judgement
Approach
- Close with what you would do differently, concretely.
- Give the blast radius: what could have broken, and what you measured.
- Pick a story where you made the decision, not one where you watched it.
Follow-up
- How did you know your change caused the improvement?
- What did you decide not to do, and why?
Take a review disagreement about upserting corrected lab results
Medium · code review · versioning · unique constraints · idempotency
A colleague's result consumer writes observation_result with INSERT ... ON CONFLICT (filler_order_id) DO UPDATE SET value_numeric, result_status, issued_ts. Corrections arrive carrying the same filler order identifier as the original, and their fixture suite — one final result per order — passes. They argue the table stays bounded and reads need no version predicate, and you are the only objector. Reconstruct the review: the comment you wrote, how you demonstrated the defect without a full reproduction, the uniqueness key you proposed instead, and what you would have accepted.
Approach
- The probe is whether you can make a correctness objection land on someone who has passing tests. Name what the upsert destroys in specifics — the prior value_numeric, its issued_ts and its result_status — so that no query can answer what was displayed before the correction arrived, which is the exact question an incident review or a legal hold asks.
- Demonstrate inside their own suite rather than arguing. Add one message: same filler order and LOINC code, result_status 'corrected', a different value. Point at the row count staying constant and the original value becoming unselectable. A failing case in their fixture is more persuasive than a paragraph.
- Lead with the sharper defect, which is the key itself. One accession fans out to many analytes, so filler_order_id is not unique even across originals; the unique index their ON CONFLICT requires cannot exist without collapsing a panel to a single row. Propose UNIQUE (filler_order_id, loinc_code, version), with the insert carrying supersedes_observation_id.
- Deal with their read-simplicity objection honestly instead of dismissing it. With a backwards supersedes pointer, 'current' means 'no row supersedes this one', which is an anti-join; a real design therefore adds a current-version marker maintained in the same transaction as the insert, or a per-(order, analyte) pointer table. Versioning is not free and saying so is what makes the rest credible.
- Name the second consequence, for consumers rather than for storage: an in-place update emits no state transition, so anything that already acted on the preliminary value never learns it changed. Versioned inserts produce that correction event as a by-product.
- Close on conduct: what you wrote, whether you blocked the merge, who decided, and the smaller thing you would have accepted — shipping the versioned insert without the current-version marker and eating the anti-join until it shows up in p99.
Follow-up
- The same corrected message is replayed a week later during an interface restart. Walk both designs through it.
- How do you keep the current-version marker correct when two corrections for the same analyte are processed concurrently?
- A result arrives with status 'entered_in_error'. Is that a new version, a deletion, or something else, and what does a chart show afterwards?
Unblock an engineer whose deductible accumulator overshoots
Easy · mentoring · lost update · isolation levels · reproduction
An engineer on your team has a benefit-application path that occasionally leaves a member's accumulated deductible above the plan limit — a handful of times a day, never in tests. Their code SELECTs the remaining deductible, computes patient responsibility in application code, then UPDATEs the accumulator to an absolute value. They have spent three days adding logging and are now asking whether the database is losing writes. Describe unblocking someone in this position: what you did first, what you let them find themselves, and what you left them able to diagnose next time.
Approach
- The probe is whether you teach a method or hand over a patch. Reproduce before explaining: two sessions, both BEGIN, both SELECT the accumulator row, both compute, both UPDATE to an absolute value, both COMMIT. The second overwrites the first and neither errors. Fifteen minutes of that ends three days of logging and, more importantly, ends the theory that the database is at fault.
- Be precise about where the anomaly is and is not, because the imprecise version teaches the wrong lesson. A single UPDATE that does its arithmetic in SQL is safe under READ COMMITTED: the blocked statement re-reads the row after the first commits. The loss comes from computing the new value in application code across the statement boundary, so the UPDATE writes an absolute amount derived from a stale read.
- Lay out three fixes with their costs rather than naming one. SELECT ... FOR UPDATE serialises writers per member and holds the lock for the transaction, so nothing in that transaction may make an external call. SERIALIZABLE with a retry loop on SQLSTATE 40001 requires the operation to be safely retryable. Per-member partitioning removes contention entirely and adds routing and rebalancing.
- Let them pick and defend one. The outcome you want is that they can name the anomaly and the isolation level unprompted next time, not that this particular ticket closes today.
- Leave an artefact behind: the two-session reproduction checked in, so the next person meets the interleaving rather than the symptom, and the reasoning is not stored only in your head.
Follow-up
- A claim is reversed and the accumulator must be credited back. What amount, given the plan design may have changed since?
- They choose SERIALIZABLE. How do they make the retry safe when the transaction also wrote a claim adjudication row?
- How would you have noticed this before a member saw it, and what would that check cost per adjudication?