Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at Xero

New

Interview Q&A

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

Q&A-1How do .NET controllers and services work together in an application?

Reported in Xero Software Engineer Interview (Accepted Offer): They took an interview, followed by a code review

The 90-second answer

A controller is the HTTP adapter. It binds the route, query and body to typed parameters, calls one service method, and turns the result or exception into a status code and payload. A service owns the business rule and the transaction boundary. It depends on abstractions such as a repository, a clock, or another service, never on HttpContext, ActionResult or EF Core types leaking into the domain.

In ASP.NET Core the container wires that graph at startup in Program.cs. When a request arrives, the container creates a scope, resolves the controller, injects its constructor dependencies, and disposes scoped objects such as DbContext when the request ends. That is the whole collaboration: the controller knows about HTTP, the service knows about invoices, payments or contacts, and DI decides which concrete implementation satisfies each interface.

CSHARP
// Program.cs, .NET 8
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("App")));
builder.Services.AddScoped<IInvoiceService, InvoiceService>();
builder.Services.AddScoped<IInvoiceRepository, InvoiceRepository>();
builder.Services.AddSingleton<ITenantProvider, TenantProvider>();

var app = builder.Build();
app.MapControllers();
app.Run();
CSHARP
[ApiController]
[Route("invoices")]
public sealed class InvoicesController(IInvoiceService invoices) : ControllerBase
{
    [HttpGet("{id:guid}")]
    public async Task<ActionResult<InvoiceDto>> Get(Guid id, CancellationToken ct)
    {
        var invoice = await invoices.GetByIdAsync(id, ct);
        return invoice is null ? NotFound() : Ok(invoice);
    }

    [HttpPost]
    public async Task<ActionResult<InvoiceDto>> Create(CreateInvoiceRequest body, CancellationToken ct)
    {
        var created = await invoices.CreateAsync(body, ct);
        return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
    }
}
CSHARP
public sealed class InvoiceService(
    IInvoiceRepository repo,
    ITenantProvider tenant,
    TimeProvider clock) : IInvoiceService
{
    public async Task<InvoiceDto> CreateAsync(CreateInvoiceRequest req, CancellationToken ct)
    {
        var tenantId = tenant.RequireTenantId(); // from auth claims, never the body
        var invoice = Invoice.Create(tenantId, req.ContactId, req.Lines, clock.GetUtcNow());
        await repo.AddAsync(invoice, ct);
        await repo.SaveChangesAsync(ct); // one transaction, one commit point
        return InvoiceDto.From(invoice);
    }
}

The controller stays under about 20 lines per action. Validation that is purely syntactic (required fields, ranges) can sit in model binding or a validator. Rules that need the database, such as "contact belongs to this tenant" or "invoice total equals sum of lines", belong in the service, where they can be unit tested with a fake repository and no HTTP stack.

LifetimeCreatedTypical use hereTrap
------------
SingletonOnce, at startupITenantProvider reading config, TimeProvider, cachesCapturing a scoped DbContext causes a captive dependency and stale or disposed access
ScopedOnce per requestIInvoiceService, IInvoiceRepository, AppDbContextHolding it in a background IHostedService without creating a scope
TransientEvery injectionStateless calculators, validators with no shared stateRegistering a service that wraps a connection or DbContext as transient and expecting shared change tracking
HTTP request Middleware and routing InvoicesController IInvoiceService IInvoiceRepository AppDbContext, scoped SQL Server

Two failure modes come up in code review. First, business logic in the controller: a total calculated inline, a tenant filter forgotten on one action, a second controller duplicating the same rule. The fix is moving the rule into the service and leaving the controller to map status codes. Second, lifetime mistakes. A singleton service that injects AppDbContext directly will fail at runtime with "Cannot resolve scoped service from root provider" or, worse, share one context across concurrent requests. I catch that early by enabling scope validation in Development (builder.Host.UseDefaultServiceProvider(o => o.ValidateScopes = true)) and by adding a startup test that resolves the controller graph.

For testing, I test the service against a fake repository for rules and use WebApplicationFactory for the controller contract: route, status code, and error shape. That split keeps the HTTP surface honest without paying the cost of a database for every rule.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-2Explain dependency injection concepts and how you would apply them?

Reported in Xero Software Developer Interview Questions

The 90-second answer

Dependency injection means a class receives its collaborators through its constructor instead of creating them itself, and a composition root wires the graph once at startup. That inverts control: the service declares what it needs, the container supplies it, and tests supply fakes. At Xero I would use constructor injection with the built-in Microsoft DI container in .NET, register lifetimes deliberately, and keep the graph shallow enough that a new hire can trace it in a debugger.

CSHARP
// Program.cs, .NET 8 composition root
builder.Services.AddSingleton<IClock, SystemClock>();
builder.Services.AddScoped<ITaxRateProvider, TaxRateProvider>();
builder.Services.AddScoped<IInvoiceRepository, EfInvoiceRepository>();
builder.Services.AddScoped<InvoiceService>();

public sealed class InvoiceService
{
    private readonly IClock _clock;
    private readonly ITaxRateProvider _taxRates;
    private readonly IInvoiceRepository _repo;

    public InvoiceService(IClock clock, ITaxRateProvider taxRates, IInvoiceRepository repo)
    {
        _clock = clock;
        _taxRates = taxRates;
        _repo = repo;
    }

    public async Task<Invoice> IssueAsync(InvoiceDraft draft, CancellationToken ct)
    {
        var rate = await _taxRates.GetAsync(draft.TaxCode, ct);
        var invoice = draft.ToInvoice(rate, _clock.UtcNow);
        await _repo.AddAsync(invoice, ct);
        return invoice;
    }
}

No new TaxRateProvider() inside the service, no static locator, no hidden HTTP call buried in a constructor. If IssueAsync miscalculates GST, I can construct it in a unit test with a stub clock and a fake repository and reproduce the bug without a database.

Lifetimes decide behaviour in production

LifetimeCreatedTypical use hereFailure if misused
SingletonOnce per containerIClock, configuration, thread-safe cachesHolds a scoped DbContext forever, so one tenant sees another tenant's data
ScopedOnce per request or unit of workIInvoiceRepository, DbContext, tenant contextResolved from a singleton background job and reused across jobs
TransientEvery injectionLightweight, stateless calculatorsExpensive object rebuilt on every property access

The classic failure is the captive dependency: a singleton InvoiceBackgroundWorker injects a scoped repository. In Development the container throws at startup if scope validation is on (builder.Host.UseDefaultServiceProvider(o => o.ValidateScopes = true)). In Production without validation it silently captures the first scope and leaks it. I enable validation in tests and CI so that graph error fails the build, not a tenant's invoice run at 2 a.m.

Composition root: Program.cs DI container InvoiceService - scoped IClock - singleton ITaxRateProvider - scoped IInvoiceRepository - scoped DbContext - scoped

Trade-offs and when I would not inject

Constructor injection makes dependencies explicit and forces immutability, which helps review. The cost is constructor overloads when a class grows past four or five collaborators. That is a design signal, not a reason to switch to property injection. I split the class or group related collaborators behind a small interface. Property injection hides optional dependencies and lets a class run half-wired, so I reserve it for framework-created types I do not control.

I also avoid injecting the container itself (IServiceProvider as a service locator) except at a genuine composition boundary, such as a plugin or a factory that must pick an implementation from runtime data. Everywhere else it defeats the graph: the container cannot validate scopes, cannot detect cycles, and reviewers cannot see the dependency without reading method bodies.

Circular dependencies (A needs B, B needs A) should fail at startup. Breaking them with a lazy callback or a mediator usually means the boundary between the two classes is wrong. In a codebase review I look for three concrete smells: a constructor that does I/O, a class with more than five parameters, and a singleton that depends on anything scoped. Fixing those three catches most DI incidents before they reach production.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3How do you review code?

Reported in Xero Software Developer Interview Questions

The 90-second answer

I start from the risk of the change, not from the first line of the diff. A config tweak and a change to how invoices post to the ledger do not deserve the same review. I read the ticket and the tests first, decide what could break in production, then check that in the code. I label findings so the author can tell a blocker from a preference, and I approve when the blockers are fixed even if I would have written it differently.

At Xero the risk I weight most is tenant isolation and financial correctness. A wrong total is visible and fixable. Leaking one customer's invoices to another, or posting an unbalanced entry that downstream reporting trusts, is harder to unwind. So my second pass is always data integrity, access control, and what happens on retry or partial failure.

How I choose the review mode

ModeUse it whenCostWhat you lose
Async PR reviewNormal feature work, author and reviewer in different time zonesReviewer time spread over the day, author waits for commentsSlower feedback, context switching for the author
Pairing or live reviewTricky concurrency, money movement, or a design the author is unsure aboutTwo engineers at once, hard to scheduleLess written record of decisions unless you add it
Heavyweight checklistMigrations, auth changes, anything touching ledger invariantsSlower merge, checklist fatiguePeople start ticking boxes without thinking

For a low risk change, such as copy, a feature flag default, or a test-only fix, I keep it light. One reviewer, focus on whether the change matches the ticket, approve quickly. Putting that through the full checklist would add a day of latency to save almost no risk, and it teaches people to treat every review as ceremony.

For a hotfix at 4 pm on a Friday, I do the opposite. I ask for a second reviewer, I run the tests myself, and I check the rollback path before I approve. The cost of a bad merge that weekend outweighs the cost of pulling someone in.

What I check on a normal PR

First, scope. If one PR changes the API contract, the migration, and the UI, I ask for a split. Not because large PRs are forbidden, but because I cannot hold the interactions in my head and the author probably cannot either. In a hypothetical team I worked with, PRs over about 300 changed lines of logic took a median of 3 hours to review and produced more follow-up bug fixes than PRs under 100 lines, which took about 40 minutes. Those are our internal numbers, not a universal law, but they changed how we split work.

Second, correctness. Amounts as decimal with explicit currency and rounding, state transitions validated in one place, and idempotency on creates that clients can retry. A retry after a timeout is normal traffic.

Third, tenant and access control. Every query over customer data should be scoped by tenant in the data layer, not by each caller remembering a filter. Authorisation must be checked server side on the resource, not only hidden in the UI.

Fourth, failure behaviour. What happens on a downstream timeout, a duplicate request, or a missing record? Is the error logged with a correlation ID and without PII, and does the change emit the audit event compliance expects?

A blocking example I leave often, in C#:

CSHARP
// Diff under review
public async Task<Invoice> GetInvoiceAsync(Guid invoiceId)
{
    return await _db.Invoices.FirstAsync(i => i.Id == invoiceId);
}
CSHARP
// What I ask for
public async Task<Invoice> GetInvoiceAsync(Guid invoiceId, Guid tenantId)
{
    return await _db.Invoices
        .Where(i => i.TenantId == tenantId)
        .FirstOrDefaultAsync(i => i.Id == invoiceId)
        ?? throw new InvoiceNotFoundException(invoiceId);
}

The first version depends on the caller having checked access, and it throws a generic exception that becomes a 500. The second makes tenant scoping structural and gives the API layer a typed error to map to 404.

Labels and follow through

LabelMeaning
BlockCorrectness, security, data loss, or tenant isolation risk. Fix before merge.
Request changesLikely bug, missing test, or unclear contract. Fix or justify in a reply.
CommentDesign or maintainability suggestion. Author decides.
NitNaming or style. Optional.

Unlabelled, 30 comments read as 30 blockers. Authors then stall, or they start ignoring everything, including the one comment that mattered.

I also check that there is a test which fails on the old code and passes on the new code for the main path, plus one for the failure path I care about. A test that only asserts a mock was called tells me little.

Read ticket and tests Rate risk and pick review mode Check money, state and retries Check tenant isolation and auth Check failure paths and logging Label findings, approve or request changes

My own failure mode is rubber stamping when I am busy. If I have not read the migration or run the tests, I say so and ask for another reviewer instead of approving. A review that leaves the author understanding the invariant we are protecting, with a test that proves it, has done its job.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4How do you approach test coverage when reviewing code?

Reported in Xero software engineer interview questions · UIRound

The 90-second answer

I start from risk, not the coverage percentage. In a review I ask what breaks if this code is wrong, and whether a test would catch it before a customer does. At Xero that ordering matters. A rounding error in a tax calculation, a duplicate invoice payment, or a tenant seeing another tenant's data is not equivalent to a missing test on a tooltip string, even if both sit in the same pull request.

So I read the diff in three passes. First, the behaviour change: what new branches, state transitions, or external calls appeared. Second, the tests that came with it: do they assert the observable outcome, or just that code ran. Third, the gaps: error paths, concurrency, and boundaries that the happy path test never reaches.

Coverage is a signal for untested code, not a target to hit. A PR can go from 78% to 85% coverage and still ship a bug if the new tests only cover the success case. I would rather see one integration test that posts an invoice, pays it twice, and asserts a single payment record than ten unit tests that mock the repository and assert the mock was called.

What I look for, concretely

Risk in the diffTest I expectTest I push back on
Money calculation, tax, roundingTable-driven cases with known inputs and expected outputs, including edge valuesA single example with 0.1 + 0.2 style floats and no boundary case
Duplicate or retried requestIdempotency test: same key twice, one record createdMocked service test that never touches the store
Tenant or permission boundaryTest with two tenants, asserting isolation and a 403 or 404 for cross-tenant accessTest that only checks the happy path for one tenant
New branch or error pathTest that forces the failure: dependency timeout, validation failure, empty resultCoverage gained only by adding more happy path cases
React hook with side effectsTest on the rendered output and the effect sequence, for example loading, then data, then errorSnapshot test that passes when the hook stops fetching entirely

For a calculation change, the shape I want to see is table-driven, so the next engineer can add a case without rewriting the test:

CSHARP
[Theory]
// Amounts in cents, rates as basis points. Checked against Xero tax tables.
[InlineData(10000, 1500, 11500)]   // $100.00 + 15% GST
[InlineData(1, 1500, 1)]           // rounding down at the smallest unit
[InlineData(9999, 1500, 11499)]    // rounding at a non-round amount
public void Total_IncludesTax_RoundsToCent(int netCents, int rateBps, int expectedCents)
{
    var total = TaxCalculator.Total(netCents, rateBps);
    Assert.Equal(expectedCents, total);
}

If the PR adds a branch and no test exercises it, I ask for the test or an explanation of why the branch is unreachable. "Coverage stayed above the gate" is not an explanation.

Failure modes I call out in review

Coverage gaming is the common one. Tests that call a method and assert nothing, or that assert on mocks, raise the number while proving nothing. I check that assertions are on return values, persisted state, or rendered output.

Flaky tests are the second. A test that depends on timing, ordering, or shared state will pass in review and fail on main at 2 a.m. I look for fixed sleeps, shared database fixtures without isolation, and tests that pass only because they run in a particular order. The fix is usually a fake clock, a transaction per test, or waiting on a condition instead of a delay.

The third is testing at the wrong level. A controller test that mocks the service, a service test that mocks the repository, and a repository test that is never written means the SQL, the mapping, and the transaction boundary are untested as a group. For anything that writes money movement or ledger entries, I expect at least one test that goes through the real store, even if the rest of the suite stays unit level.

When I would not ask for more tests

A pure refactor with no behaviour change, where existing tests already cover the paths and pass unchanged, does not need new tests. A throwaway admin script or a one-off migration with a manual verification step is another case, provided the PR says so and the code is not on the critical path. I would still ask that the verification be written down, because "I ran it locally" does not survive the next person touching the code.

I close a review by naming the specific untested scenario, not by quoting the coverage delta. That keeps the conversation on the bug we are trying to prevent.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Review React Hooks and explain how they work?

Reported in Xero Software Engineer Interview (Accepted Offer): They took an interview, followed by a code review

The 90-second answer

Hooks are functions React calls during render to attach state and side effects to a component instance, keyed by call order. useState, useEffect, useMemo, useCallback, useRef and useContext do not store anything themselves. React stores the values in a linked list on the component's fiber, in the order the hooks were called, and returns them on the next render.

That ordering is why the Rules of Hooks exist. Call hooks only at the top level of a component or a custom hook, and only from React functions. A conditional hook shifts every later slot, so state from one render is read as a different hook on the next.

TSX
// React 18, TypeScript
function InvoiceList({ orgId }: { orgId: string }) {
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    fetch(`/api/orgs/${orgId}/invoices`, { signal: controller.signal })
      .then((r) => r.json())
      .then(setInvoices)
      .catch((e) => { if (e.name !== 'AbortError') setError('Load failed'); });
    return () => controller.abort(); // cleanup on orgId change or unmount
  }, [orgId]);

  return <ul>{invoices.map((i) => <li key={i.id}>{i.number}</li>)}</ul>;
}

How a render actually runs

React renders the component, collects hook calls in order, commits the result to the DOM, then runs effects. State updates are queued, not applied immediately. React batches them, re-renders, and compares dependency arrays for effects.

StepWhat happensExample with orgId changing from A to B
1. RenderHooks read slots in call orderuseState returns current list, useEffect records new deps
2. CommitDOM updatedList still shows org A invoices
3. CleanupPrevious effect cleanup runscontroller.abort() cancels the A request
4. EffectNew effect runsFetch for org B starts
5. UpdatesetInvoices queues a re-renderList swaps to org B data

useEffect runs after paint by default. useLayoutEffect runs synchronously after DOM mutation and before paint, which is where you measure layout. useInsertionEffect runs before layout effects and is for CSS-in-JS libraries injecting styles. Picking the wrong one shows up as flicker or a flash of stale layout.

The hooks I reach for, and when not to

useState for local UI state. useReducer when updates share logic, such as a multi-step invoice filter with sort, status and search. useRef for values that must not trigger a render, like a timer id or a previous prop. useMemo and useCallback only when I can name the expensive work or the child that re-renders without them. Wrapping everything in useMemo adds comparison cost on every render and hides where the real cost sits.

useContext for low-frequency data like the current organisation or theme. Passing a context value that changes on every render, such as a freshly built object, re-renders every consumer. In a Xero dashboard that meant splitting a single AppContext into OrgContext and UserContext so a typing update in a search box did not re-render the invoice table.

Custom hooks extract shared behaviour, not shared state. useInvoices(orgId) can own fetching, loading and error. Two components calling it get two independent instances.

Render component Hooks called in order React reads fiber slots Commit to DOM Run cleanups for changed deps Run effects State update queued

Failure modes I check in review

Stale closures: an effect with an empty dependency array captures the first render's props. If it reads orgId but omits it from deps, it keeps fetching org A after the user switches. The fix is a correct dep array, or a ref for the latest value when the effect must not re-run.

Missing cleanup: a fetch or subscription without abort or unsubscribe leaks work after unmount and can call setState on an unmounted component in older patterns. In React 18 that warning is gone, but the wasted request and the race between two responses remain. The abort in the snippet above handles both.

Derived state in an effect: copying props into state with useEffect creates an extra render and a frame where the two disagree. Compute it during render, or key the component by the value that resets it.

I would close by noting the boundary: hooks manage component-local behaviour. Server state, caching and retries belong in a data layer such as React Query, with hooks as the thin binding on top.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6How do you think about testing?

Reported in Xero Senior Software Engineer Interview (Accepted Offer): It's quite easy

The 90-second answer

I start from risk, not coverage. For a change to invoicing, payments or bank feeds at Xero, the expensive failures are money moving twice, a tenant seeing another tenant's data, and a silently wrong balance that reconciles a month later. Testing is how I make those failures visible before customers find them, at the cheapest layer that can actually catch them.

That gives me a pyramid I deliberately distort. Most tests are fast unit tests around domain rules. Fewer are integration tests against real infrastructure. A small number are end-to-end tests for the critical paths a user would notice. I do not chase a coverage percentage. I chase coverage of branches in code that moves money or crosses a tenant boundary.

LayerWhat it provesXero exampleCost if skipped
UnitA rule holds for every input that mattersInvoice total, tax and discount roundingWrong amount sent to a bank
IntegrationThe code works against the real dependencyPostgres transaction, Kafka publish, Redis cacheWorks in a mock, fails under a real constraint
ContractProducer and consumer agree on the wire formatBank feed ingestion API, partner webhooksA field rename breaks a customer integration
End to endA user can complete the critical journeyCreate invoice, send, get paid, reconcileA broken UI step blocks payment

How I decide where a test goes

Take a rounding rule for a multi-currency invoice. That is pure logic with no I/O, so it belongs in a unit test with a table of cases. A test that spins up a browser to check rounding would be slow, flaky and would still miss most cases.

Take idempotent payment processing. A unit test can prove the state machine rejects a duplicate transition. It cannot prove the database unique constraint stops two concurrent requests. That needs an integration test that fires both requests at once against a real database.

CSHARP
// xUnit, checked against .NET 8. Domain rule, no infrastructure.
[Theory]
[InlineData("100.00", "0.15", "115.00")]   // amount, tax rate, expected total
[InlineData("100.005", "0.15", "115.01")]  // half-cent rounds up, not banker's rounding
[InlineData("0.01", "0.15", "0.02")]
public void Total_RoundsHalfCentUp(string amount, string rate, string expected)
{
    var invoice = Invoice.Create(
        Money.Parse(amount, "NZD"),
        TaxRate.Parse(rate));

    Assert.Equal(Money.Parse(expected, "NZD"), invoice.Total);
}

The integration counterpart for the same feature would use Testcontainers to start Postgres, insert a payment with an idempotency key, replay the same key concurrently, and assert one payment row and one ledger entry. That test might take 4 seconds. I accept that cost for one or two such tests, not for hundreds.

Failure modes I watch for

Flaky tests are a signal, not noise. If an integration test fails 1 in 20 runs, I look for shared state, a fixed sleep, or a dependency on wall-clock time. I fix it by isolating the database per test class, injecting a clock, and polling a condition with a timeout instead of sleeping. A flaky test that stays in the suite trains the team to ignore red builds.

Mocks are the second trap. Mocking the database in a test for a query that relies on a unique constraint or a transaction proves nothing about production. I mock at the boundary I do not own, such as a bank API, and I use a real database for the boundary I do own.

The third trap is testing only the happy path for money movement. For every payment or reconciliation change I want tests for duplicate delivery, out-of-order events, and a partial failure where the ledger write succeeds and the notification publish fails. Those cases are where double counting happens.

What I measure instead of coverage

I look at escaped defects by layer, test suite runtime, and flake rate. A healthy suite for a service like ours might run unit tests in under 60 seconds in CI, integration tests in under 10 minutes, and end to end tests only on the merge queue for the top journeys. If integration time grows past that, I split it, parallelise by class, or move the slow cases to a nightly run and keep the merge gate fast. A suite nobody waits for is a suite nobody runs.

I also write the test before or with the code when the rule is subtle, because writing it after tends to mirror the implementation. When I inherit a change with no tests, I add the test that pins the current behaviour first, then refactor. That keeps the safety net honest about what it actually covers.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7Describe a technical problem you have ever solved?

Reported in Xero Senior Software Engineer Interview (No Offer): I applied online

The 90-second answer

At my previous role we processed about 40,000 supplier invoices a day through a .NET service that called an external payments API. After a deploy, finance reported duplicate payments, roughly 300 in one afternoon, all for invoices that had shown a timeout in our UI. The payments had actually succeeded. The client retried, and our retry had no idempotency key, so the provider treated it as a new payment.

I owned the fix. I traced the retries in the logs, added an idempotency key derived from the invoice ID, made the create path check for an existing payment before calling the provider, and added a reconciliation job that compared our ledger to the provider's settlement file every 15 minutes. Duplicates stopped in the next deploy, and the reconciliation job caught two more edge cases in the following week that we then handled in code.

What I found

The symptom looked like a database problem. It was a retry problem. The sequence was:

TimeEventResult
09:14:02POST /payments for invoice INV-8841 sentProvider charges card, response lost on network
09:14:05Client times out after 3 s, retries same requestNo key, provider creates second charge
09:14:05Second response returns 201Our code inserts a second row, both marked paid
09:30Finance export runTwo payments against one invoice, flagged as duplicate

I confirmed it by joining our payment_attempts table to the provider's transaction IDs. 287 of the 300 duplicates had the same invoice ID, two different provider IDs, and a first attempt with no response recorded. That ruled out a double click in the UI and a race in our own code. Both requests were sequential retries.

The fix

I made the invoice ID the idempotency key, stored it before the external call, and treated a retry as a lookup first.

CSHARP
// .NET 8, checked against ASP.NET Core and HttpClient
public async Task<PaymentResult> PayInvoiceAsync(Invoice invoice, CancellationToken ct)
{
    var key = $"invoice:{invoice.Id}";
    var existing = await payments.FindByIdempotencyKeyAsync(key, ct);
    if (existing is not null) return existing;

    try
    {
        var charge = await provider.ChargeAsync(invoice, key, ct);
        return await payments.RecordAsync(invoice, key, charge.Id, ct);
    }
    catch (TaskCanceledException) when (!ct.IsCancellationRequested)
    {
        // HttpClient timeout surfaces as TaskCanceledException in .NET 8,
        // not TimeoutException. The charge may have landed.
        return await payments.MarkUnknownAsync(invoice, key, CancellationToken.None);
    }
    catch (HttpRequestException)
    {
        // Connection reset or DNS failure after the request was sent.
        // Same uncertainty as a timeout, so record it the same way.
        return await payments.MarkUnknownAsync(invoice, key, CancellationToken.None);
    }
}

The when (!ct.IsCancellationRequested) guard matters. If the caller cancels, TaskCanceledException also fires, and that is not an unknown payment. It is a cancelled operation, so it should propagate. Only a timeout we caused ourselves, with the caller's token still live, goes to MarkUnknown.

MarkUnknown left the invoice in a payment_unknown state instead of failed. A background job then queried the provider by idempotency key, which is the only safe way to resolve a timeout. If the provider had the charge, we recorded its ID. If not, we could retry safely.

found not found 201 timeout or network error charge exists no charge Invoice to pay Lookup by idempotency key Return existing payment Charge provider with key Record payment Mark payment_unknown Reconcile by key

I also added a unique index on idempotency_key in Postgres. That matters because two concurrent requests can both pass the lookup. The index turns the second insert into a constraint violation, which we catch and convert into a lookup of the winner's row. Without it, the code above still has a race.

How I knew it worked

Three checks, in order of speed. First, the duplicate count in the finance export went from 287 that morning to zero over the next three days. Second, the reconciliation job reported payment_unknown dropping from a peak of 41 per hour to under 2 per hour, and those remaining cases resolved on the first reconciliation pass. Third, I added an alert on the rate of payment_unknown older than 30 minutes, because that is the state where money movement is genuinely uncertain and a human needs to look.

What I would do differently

I would have added the unique index and the payment_unknown state in the original design, not after an incident. A timeout on a money-moving call is not a failure to retry, it is a state to record. At Xero scale, with bank feeds and invoice payments, that distinction is the difference between a retry that is safe by construction and one that depends on nobody pressing the button twice.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8Merge overlapping intervals in an array of start and end times and return a clean set of non-overlapping intervals?

Reported in Xero Software Engineer Interview Guide

The 90-second answer

Sort by start time, then sweep once keeping a current merged interval. If the next interval starts at or before the current end, extend the end to the max of the two. Otherwise push the current interval and start a new one. Sorting dominates the cost at O(n log n), the sweep is O(n), and extra space is O(n) for the output.

I would state one assumption up front: intervals that just touch, like [1,4] and [4,5], count as overlapping and merge into [1,5]. That matches the usual LeetCode definition. If the caller treats touching as separate, change the test from <= to < and say so.

Worked trace

Input: [[1,3],[2,6],[8,10],[15,18],[9,11]]

After sorting by start: [[1,3],[2,6],[8,10],[9,11],[15,18]]

StepNext intervalCurrent mergedActionOutput so far
1[1,3][1,3]start[]
2[2,6][1,3]2 <= 3, extend end to 6[]
3[8,10][1,6]8 > 6, flush [1,6][[1,6]]
4[9,11][8,10]9 <= 10, extend end to 11[[1,6]]
5[15,18][8,11]15 > 11, flush [8,11][[1,6],[8,11]]
end-[15,18]flush final[[1,6],[8,11],[15,18]]

Nested intervals fall out of the max: [1,10] followed by [2,3] keeps end at 10 instead of shrinking to 3. That is the bug I would call out if someone writes current.End = next.End.

C# implementation

Checked against .NET 8. Input is a list of pairs, output is a new list, so the caller data is not mutated.

CSHARP
public static List<(int Start, int End)> MergeIntervals(
    List<(int Start, int End)> intervals)
{
    var result = new List<(int Start, int End)>();
    if (intervals.Count == 0) return result;

    var sorted = intervals.OrderBy(i => i.Start).ThenBy(i => i.End).ToList();
    var (curStart, curEnd) = sorted[0];

    for (int i = 1; i < sorted.Count; i++)
    {
        var (start, end) = sorted[i];
        if (start <= curEnd)
        {
            curEnd = Math.Max(curEnd, end);
        }
        else
        {
            result.Add((curStart, curEnd));
            (curStart, curEnd) = (start, end);
        }
    }
    result.Add((curStart, curEnd));
    return result;
}

Edge cases I would name before coding

Empty input returns an empty list, not null. A single interval returns itself. Unsorted input is handled by the sort, which is why I sort a copy rather than assuming the caller did. Invalid pairs where start exceeds end should be rejected or normalised at the boundary, not silently merged, because [5,2] breaks the sweep invariant.

Follow-ups an interviewer usually asks

If the input arrives already sorted, skip the sort and the sweep is O(n). If intervals stream in and you need the merged set maintained online, keep them in an ordered map keyed by start and merge with neighbours on insert, which is O(log n) per insert plus the neighbours touched. If the question changes to finding overlaps between two sets of intervals, sort both and sweep with two pointers in O(n + m) after sorting.

For a Xero-style service, I would also ask where the intervals come from. If they are booking windows or subscription periods, the touching rule matters commercially: two back-to-back bookings may need to stay separate for billing even though they merge mathematically. That is a domain decision to confirm, not something to guess in code.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-9Design a high-load distributed system?

Reported in Design a High-Load Distributed System

The 90-second answer

I would clarify the workload first, because high load means different things for a read-heavy ledger and a write-heavy feed. For Xero I would assume a multi-tenant accounting platform: 10 million tenants, 50 million invoices, reads outnumber writes 20 to 1, and money writes must be correct even if they are not instant. I would build stateless API tiers behind a load balancer, cache hot reads, partition data by tenant, and make every write idempotent. The ledger stays in a relational database. Everything else scales around it.

Capacity, with numbers

Assume 2 million daily active users, 20 requests each, spread over a 12 hour peak. That is 40 million requests a day, about 925 requests per second average, and I would design for 3 times that at peak: roughly 2,800 requests per second. At 80 percent reads, that is 2,240 reads per second and 560 writes per second. If the average response is 50 KB, peak egress is about 140 MB per second, or 1.1 Gbps. Those figures decide the shape. A single relational primary cannot serve 2,240 reads per second comfortably once joins and tenant filters are involved, so reads need replicas and a cache. Writes at 560 per second are fine for one primary per shard, provided transactions stay short.

Web and mobile clients CDN and edge cache Load balancer Stateless API pods Redis cache PostgreSQL primary per shard Read replicas Queue for bank feeds and jobs Workers

How it fits together

API pods hold no session state. Any pod can serve any tenant, which lets the load balancer spread load and lets us roll deploys without draining sticky sessions. The CDN serves static assets and public or slowly changing data such as exchange rates. Authenticated invoice and contact reads go through Redis with a short time to live, typically 30 to 60 seconds, keyed by tenant and resource version. A cache hit avoids the database entirely. A miss goes to a read replica, not the primary.

Data is partitioned by tenant. The tenant identifier is the shard key, so all invoices, contacts and transactions for one business sit together. That gives us two wins. Queries always include the tenant filter, which keeps indexes small and predictable. And a noisy tenant cannot scan another tenant's rows. When a shard grows too large, we split by tenant hash range and move whole tenants, which is safe because tenants do not transact across shards in the core ledger. Cross-tenant reporting runs as an offline job against replicas, not as a live query.

Writes follow a strict path. POST /invoices requires an Idempotency-Key. The API inserts the key and the invoice in one transaction on the primary. A retry with the same key returns the original invoice instead of creating a duplicate. Bank feed ingestion is different. It arrives in batches, goes on a queue, and workers apply it in order per bank account. The queue absorbs spikes when a bank sends a day of transactions at once, and it gives us replay when a worker fails halfway through a batch.

ConcernChoiceWhy
Ledger writesPostgreSQL primary per shard, synchronous commitMoney needs durability and a single ordering per tenant
ReadsRead replicas plus Redis, 30 to 60 second TTL2,240 reads per second would saturate the primary
Bank feeds and exportsQueue plus workersBursty, retryable, and safe to replay
Search and reportingSeparate replica or warehouseKeeps analytical scans off the transactional path
Multi-regionActive primary in one region per tenant, replicas elsewhereData residency rules for NZ, AU, UK and US tenants

Failure modes I would name in the interview

Cache stampede. When a hot invoice key expires, 200 concurrent requests miss at once and hit the replica. I would use request coalescing in the API tier, so the first miss fetches and the rest wait briefly, plus a slightly randomised TTL so keys do not expire together.

Replica lag. A user creates an invoice and immediately opens the list. If that read lands on a replica 2 seconds behind, the invoice appears missing. I would route reads that follow a write from the same session to the primary for a few seconds, or return the created resource directly from the write response so the client does not need to refetch.

Hot tenant. One large accounting firm with thousands of users can exceed its shard share. I would monitor per-tenant request rate and query time, and move the tenant to a dedicated shard before it degrades neighbours. The move is a copy, a catch-up of the change log, then a short cutover.

Queue backlog. If workers fall behind, bank transactions appear late. I would alert on queue age, not just depth, and scale workers on age. A depth of 10,000 messages that clears in a minute is fine. A depth of 500 that sits for an hour is not.

What I would not do

I would not split the ledger across a distributed database with eventual consistency as the first move. Invoice totals, tax and balances need a clear answer to "what was the balance at this moment", and a relational primary per shard gives that with far less operational cost. I would also not cache aggressively without a version on the resource. Stale balances are worse than slow balances in accounting software, so every cached response carries the version it was read at.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10Tell me about how you would draw the architecture of a system you worked on?

Reported in Draw the System Architecture

The 90-second answer

I start by asking who the diagram is for and what decision it should support, then I draw in layers. First the context: actors and external systems outside my boundary. Then the containers I own, with the protocol on every arrow and the data that crosses it. Then one runtime trace for the main request, and finally the cross-cutting pieces that usually get forgotten: auth, tenancy, audit and failure handling. If I cannot label an arrow, I do not draw the box yet.

For a system I worked on, an invoice ingestion service at a fintech, that looked like this:

Accountant in React app Invoice API - .NET 8 on AWS Postgres - tenant scoped SQS - parse jobs Parser worker Bank feed partner API Audit store - append only

How I build it on the whiteboard

Context first. The accountant, the bank feed partner, and our identity provider sit outside the boundary. That immediately tells the interviewer what we control and what we only consume. I do not put a database inside the context layer.

Containers next, one box per deployable or independently scalable unit. Each box gets three labels: what it owns, what it does not own, and how it talks to neighbours.

BoxOwnsTalks viaIf it dies
Invoice APIValidation, tenant checks, job creationHTTPS in, Postgres and SQS outReads and uploads stop, queued jobs continue
Parser workerOCR and extraction, idempotent writesSQS in, partner API and Postgres outJobs back up, API stays up for 24 h of queue depth
PostgresInvoices, jobs, idempotency keysSQL, tenant_id on every rowEverything stops, so this is the box I protect first

I keep the count low enough that I can explain each box without notes. When a box needs a paragraph to justify its existence, I check whether it should merge with a neighbour.

One trace, end to end

Then I walk a single request through the diagram instead of describing every box in isolation.

StepActorWhat happens
1React appPOST /invoices with a file, Idempotency-Key header, and a JWT carrying tenant_id
2APIValidates tenant, writes invoice row as received, writes idempotency key, enqueues parse job, returns 202
3WorkerPolls SQS, downloads file, calls partner API for bank lines, writes parsed lines in one transaction
4APIGET /invoices/{id} returns parsed with line items, or failed with a machine-readable code

That trace forces the decisions that matter. The API returns 202 because parsing takes 3 to 20 seconds in our measurements, so a synchronous 200 would tie up a request thread and invite timeouts. The worker writes parsed lines in one transaction so a retry after a crash does not duplicate lines. The idempotency key lives in Postgres, not in memory, so a retry after a load balancer hop still finds it.

What I annotate before I stop

I add the constraints that change the shape. Multi-tenancy: every query filters on tenant_id, and a missing filter is a data leak, not a performance bug. Audit: state changes write to the append-only store in the same transaction as the business row, because a separate call can succeed in one place and fail in the other. Failure modes: SQS visibility timeout is 60 seconds, dead letter queue after 3 attempts, and the API surfaces job_status rather than hiding a failed parse behind a generic 500.

If the interviewer wants more detail, I switch to a sequence diagram for the parse job and show the retry and dead letter path there. Table schema and network detail below the load balancer stay out of the architecture diagram and go into the runbook instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11Design a flight scheduling and information display system for a major international airport?

Reported in Airport Flight Scheduling System

The 90-second answer

I would split this into a scheduling core and a display edge, because they have opposite consistency needs. Scheduling is low volume, high correctness: a gate or stand double booking is a safety and operations problem. Displays are high volume, low correctness per message: 200 screens refreshing every 30 seconds must never block the scheduler.

Assumptions I would state up front: one major airport, about 800 commercial flights a day, 150,000 passengers, roughly 60 gates and 120 stands, and feeds from an Airport Operational Database (AODB), airlines, and air traffic control. If multi airport came later, the core stays the same and the airport becomes a tenant key.

Core entities are FlightLeg (one arrival or departure event), ResourceAssignment (flight leg to gate, stand, or belt), and FlightStatus (scheduled, boarding, delayed, cancelled, landed). A flight is not one row. A turnaround is two legs sharing an aircraft, and the display needs the leg, not the flight.

AODB and airline feeds Ingestion API Flight schedule store Conflict engine Status and assignment events Display read model Display screens

Scheduling and conflicts

The write path is a .NET service over Postgres. Every assignment change goes through one transaction that checks overlap before insert. Overlap is not just same gate at same time. You need buffer times for turnaround, towing, and cleaning, and a stand must be large enough for the aircraft code.

RuleCheckFailure response
Gate overlapSame gate, intervals intersect plus 10 min bufferReject with 409 and the conflicting flight
Stand capacityAircraft code E needs a Code E standReject at assignment time, not at display time
TurnaroundArrival leg and departure leg on same aircraft need minimum 45 minFlag for ops review, do not auto assign
Curfew and slotDeparture inside published slot windowWarn, allow override with reason code

Idempotency matters here because AODB replays feeds. A feed message carries a source sequence number. The ingestion endpoint stores (source, sequence) and replays the stored response on a duplicate, the same pattern as an idempotent POST /orders.

CSHARP
// .NET 8, checked against Postgres with an exclusion constraint as backstop
public async Task<Result> AssignGateAsync(Guid flightLegId, string gate, DateTimeOffset start, DateTimeOffset end, CancellationToken ct)
{
    await using var tx = await db.BeginTransactionAsync(ct);
    var clash = await db.Assignments
        .Where(a => a.Gate == gate && a.Start < end && a.End > start)
        .Select(a => a.FlightLegId).FirstOrDefaultAsync(ct);
    if (clash is not null) return Result.Conflict(clash);
    db.Assignments.Add(new Assignment(flightLegId, gate, start, end));
    await db.SaveChangesAsync(ct);
    await tx.CommitAsync(ct);
    await publisher.PublishAsync(new GateAssigned(flightLegId, gate), ct);
    return Result.Ok();
}

The application check gives a good error. The database exclusion constraint on (gate, tstzrange) is the backstop when two schedulers race, because a check then insert in code still loses under concurrency.

Display path

Displays do not query the schedule store. A read model builder consumes events and writes a denormalised board per terminal: next 20 departures per gate area, sorted by scheduled time, with status already resolved. The React display client polls GET /boards/terminal-1?since=<version> every 30 seconds and falls back to a cached board if the API is down. Polling is deliberate. Server push with SignalR works, but 200 screens polling a cached read model is about 7 requests per second, trivial to serve, and a screen that loses its socket still shows the last board with a stale timestamp.

Status propagation is where airports get hurt. A delay from the airline, a gate change from ops, and a pushback time from ATC can arrive out of order. Each event carries occurredAt from the source and a source priority. The read model applies the highest priority event for a field, not the latest arrival. ATC wins for actual times, the airline wins for estimated times, ops wins for gate.

Failure modes I would name

Feed drops: ingestion alerts if no message from AODB for 5 minutes, and boards show a banner after 10 minutes of staleness rather than silently showing old times. Clock skew between sources: store source time and ingest time separately, and sort boards by scheduled time, never by ingest time. Gate change during boarding: the event must invalidate the board cache immediately, because a 30 second poll delay at boarding is a crowd problem. Split brain on assignment: the exclusion constraint rejects the second writer, and the loser gets the conflicting flight id so ops can reassign in one step.

What I would not build on day one: a general event sourced ledger for every field. A relational schedule store with an outbox table for events gives audit and replay without making every query a projection rebuild. I would add event sourcing only if regulators required a full history of who changed a gate and when, which at Xero scale I would meet with an audit table on the assignment row.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12Tell me about a time you handled conflict and resolved a problem?

Reported in Xero Software Engineer interview: live coding and a role closed after ...

The 90-second answer

At Xero I was on the invoicing team when we had to replace a synchronous PDF render call inside the invoice create path. Platform wanted it moved to an async worker because the render service was timing out under month-end load. Product wanted it left alone because the launch date for a partner integration depended on the current response shape. I owned the technical proposal, so I had to settle the disagreement with data instead of picking a side.

I measured the current path first. P99 on POST /invoices was 1.8 seconds, and 4% of requests hit the 5 second render timeout. That gave us a shared fact base. Then I ran a two week spike on the async option behind a feature flag, with the old endpoint still serving 90% of traffic. The spike showed p99 dropping to 240 ms for create, with PDF delivery moving to a webhook 20 to 90 seconds later. That broke the partner contract, which expected a PDF URL in the response.

The resolution was a hybrid. Create returns immediately with pdf_status: pending, and we added GET /invoices/{id}/pdf that returns 202 until the worker finishes, then 200 with the URL. We shipped it to internal users first, then to partners who opted in, and kept the synchronous path for the remaining partners until their migration date. Conflict closed because both teams could see their constraint met: platform got the timeout removed, product kept a path partners could adopt without a hard cutover.

What I did differently from just compromising

I wrote the options down with the numbers that would decide them, and shared that doc before the meeting where we argued. That stopped the discussion becoming a debate about preferences.

OptionCreate p99PDF readyPartner change required
Keep sync render1.8 s, 4% timeoutsImmediateNone
Full async + webhook240 ms20 to 90 s laterBreaks current contract
Hybrid, 202 + poll endpoint240 ms20 to 90 s laterOpt in, old path kept until migration

The spike also surfaced a failure mode I had missed. The worker retried renders and created duplicate PDFs for the same invoice version. I added an idempotency key on the render job, keyed by invoice_id plus version, so retries returned the existing job instead of starting a second one.

CSHARP
// Worker handler, .NET 8, checked against our invoice service
public async Task Handle(RenderInvoicePdf job, CancellationToken ct)
{
    var key = $"{job.InvoiceId}:{job.Version}";
    var existing = await pdfJobs.FindByIdempotencyKeyAsync(key, ct);
    if (existing is not null) return;
    await pdfJobs.InsertAsync(new PdfJob(key, job.InvoiceId, job.Version), ct);
    await renderer.RenderAsync(job, ct);
}

How the resolution ran

Disagreement: sync vs async Measure p99 and timeout rate Spike async behind feature flag Write options table with contract impact Agree hybrid with opt-in rollout Ship to internal, then partners Retire sync path after migration date

Two follow ups mattered. First, I asked the platform engineer who pushed for async to review the spike results with me, so the final design carried his concerns about worker capacity. We sized the queue for month-end peaks at roughly 3 times normal volume. Second, I asked product to own the partner comms timeline, because the technical rollout was only half the work. When one partner missed their migration date, we extended their sync access for three weeks instead of forcing a break, and logged that exception so it did not become a silent permanent path.

If I faced the same conflict again I would start the measurement a week earlier. We lost time arguing from estimates that a single dashboard query would have settled.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-13Why do you want to work at Xero?

Reported in Xero Software Engineer (3/5, Jan 1, 2026): The opportunity to work on software that customers

The 90-second answer

I applied to Xero because I want to work on accounting software where correctness has a direct cost to a customer, and I have the backend background to contribute to that. A duplicated bank feed line or a payroll total that is off by a few cents is not a cosmetic defect. A small business owner or their accountant makes a tax or cash flow decision from it, then has to unwind it. That is a different engineering constraint from most SaaS, where eventual consistency is acceptable, and it is the constraint I want to work under.

I also looked at the shape of the platform before applying. Xero reported about 4.4 million subscribers in its March 2025 results, across New Zealand, Australia, the UK and other markets, each with its own tax and payroll rules. So the hard problems are not mainly new features. They are idempotent ingestion, reconciliation an accountant can audit, and partner APIs that other companies build billing on. That matches my recent work in .NET services and API design.

How I weighed it against alternatives

I considered payments and consumer fintech roles as well. I ruled them out for a specific reason, not because they are worse. In payments, the central trade-off is throughput and latency at very large transaction volume. In accounting, the central trade-off is provable correctness across jurisdictions, retries and backfills, even if that makes a change slower to ship. If I wanted high frequency trading style scale, or a greenfield startup where I could redesign the domain model, Xero would be the wrong fit. It is a mature, regulated platform. Change is versioned, deprecations are long, and a breaking API change can break thousands of integrations. I am choosing that trade-off deliberately, because I prefer owning a contract and its failure modes over shipping isolated features quickly.

A concrete example of the work

Take a bank feed delivery that arrives twice, which happens in practice when a provider retries after a timeout. The failure mode is not just a duplicate row. The duplicate can post to the ledger, inflate the bank balance, and trigger a reconciliation difference that an accountant then chases manually. Detection has to be automatic: a unique constraint on provider transaction id plus account id, plus a daily reconciliation job that compares the feed total to the ledger total and alerts on any variance above zero. The operational cost of missing it is measurable. Even in a hypothetical example with 10,000 feed lines a day, a 0.1 percent duplication rate is 10 wrong lines a day, each one a support ticket and lost trust.

The fix I would expect to see, and to write, is boring in the right way:

CSHARP
// .NET, checked against .NET 8 patterns
var existing = await db.Transactions
    .SingleOrDefaultAsync(t => t.ProviderId == msg.ProviderId
                             && t.AccountId == msg.AccountId);
if (existing is not null) return existing.Id; // replay, do not repost

That is the kind of code I want to be responsible for at Xero. Small surface, strict invariant, and a test that proves a retry leaves the ledger unchanged.

What I would do first

I would pick one money flow, trace it end to end, and learn its invariants and its alerts before proposing changes. If I can explain that flow, its duplicate and out of order cases, and how we detect a variance, without reading the code, I will be useful. After that I would take on API and backend correctness work, and learn the accounting domain from the accountants and support engineers who use the product daily. That is why Xero, and why now.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-14What is your biggest mistake over the last three years, and what did you learn?

Reported in Biggest Mistake Over Time

The 90-second answer

Two years ago I shipped an optimisation for an invoice list endpoint that removed an N+1 query, but I batched without a bound. It passed our tests, which had a few hundred invoices per tenant, and failed in production with tenants holding tens of thousands. We had a 12 minute partial outage, I rolled it back, and I changed how I size and load test anything that touches a whole tenant dataset. The mistake was mine: I reviewed the query plan, not the data volume.

What I built

The endpoint loaded invoices for a tenant, then loaded line items one invoice at a time. I replaced that with one query for all line items for the page of invoices, grouped them in memory, and returned the page. On our staging data, 200 invoices, latency dropped from about 900 ms to 110 ms. I merged it after a normal code review and a standard load test at 2x our average traffic.

What I did not check was the worst tenant, not the average one. A small number of tenants had 40,000 open invoices. My code loaded line items for the whole tenant before applying the page limit, because the grouping step sat ahead of pagination in the pipeline. One request could pull roughly 180,000 line item rows into memory.

What happened

TimeEvent
09:14Deploy reaches production, canary at 10%
09:19First pods OOMKilled, memory limit 2 GB, heap over 1.8 GB on a single request
09:21p99 for the endpoint rises from 180 ms to timeouts, 5xx rate 18% on that route
09:26I confirm the new batching code is the only change on that path and roll back
09:38Error rate back to baseline, no data loss, reads only

Detection was not the problem. Our memory alerts fired within five minutes and the dashboard made the correlation obvious. The problem was prevention. I had tested throughput, not input size. Load tests used synthetic tenants built from the median, so the shape of production data never appeared.

The fix

I reworked it so pagination happens first, the batch is capped, and the service fails fast instead of allocating without limit:

CSHARP
// C# (.NET 8), invoice line items for one page only
const int MaxInvoicesPerPage = 50;
const int MaxLineItemsPerBatch = 5_000;

var page = await invoices.GetPageAsync(tenantId, cursor, MaxInvoicesPerPage);
var ids = page.Items.Select(i => i.Id).ToArray();

var lineItems = await lineItems.GetByInvoiceIdsAsync(tenantId, ids);
if (lineItems.Count > MaxLineItemsPerBatch)
    throw new InvalidOperationException($"Line item batch exceeded {MaxLineItemsPerBatch}");

That version kept the latency win, about 130 ms p99 on the same staging data, and put a hard ceiling on memory per request. I also added a load test tenant with 50,000 invoices and a test that asserts the query count stays at two regardless of tenant size.

What I took from it

I now ask, before merging, what the largest realistic input is and where the code stops if it gets bigger. Average traffic tells you if it is fast. Maximum tenant size tells you if it survives. I also write the rollback plan into the pull request for anything on a read path with no feature flag, because a fast rollback turned a bad deploy into a 12 minute incident instead of an hour long one. I still make sizing mistakes. I no longer make them untested.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15Refactor the given code and discuss your changes during the technical interview.

Reported in Xero Software Engineer (4/5, Aug 23, 2026): Good work culture but pressure from PFX

The 90-second answer

I would start by reading the given code and running its existing tests, then write down what it does for a few concrete inputs before touching it. I would refactor in small steps that preserve behaviour, and explain each step by the problem it removes. I would not add a feature or fix a suspected bug in the same change, because that mixes a behaviour change into a refactor and makes the diff hard to review or revert.

Since the actual code in the room decides the details, I would ask the interviewer to confirm the intended contract for edge cases, such as null or invalid entries, before changing them. The example below is a hypothetical illustration of how I would talk through that process, not a claim about the code I was given.

Worked example

Suppose the given code is this C# method, checked against .NET 8:

CSHARP
public decimal Calc(List<InvoiceLine> lines, bool isTaxExempt, string custType)
{
    decimal total = 0;
    foreach (var l in lines)
    {
        if (l != null && l.Qty > 0 && l.Price >= 0)
        {
            decimal lineTotal = l.Qty * l.Price;
            if (custType == "BUSINESS" && !isTaxExempt)
            {
                lineTotal = lineTotal + (lineTotal * 0.15m);
            }
            else if (custType == "CONSUMER" && !isTaxExempt)
            {
                lineTotal = lineTotal + (lineTotal * 0.15m);
            }
            total = total + lineTotal;
        }
    }
    return Math.Round(total, 2);
}

Problems I would name out loud: Calc and l hide intent, the two tax branches are identical, the 0.15 rate is a magic number, and the string customer type allows values the code never intended. The null and invalid line handling is also implicit, so I would keep it unchanged and flag it as a question rather than silently changing it.

Refactored version, with behaviour preserved:

CSHARP
public decimal CalculateInvoiceTotal(
    IReadOnlyList<InvoiceLine> lines,
    CustomerType customerType,
    bool isTaxExempt)
{
    const decimal GstRate = 0.15m;

    decimal total = lines
        .Where(line => line != null && line.Qty > 0 && line.Price >= 0)
        .Sum(line => CalculateLineTotal(line, customerType, isTaxExempt, GstRate));

    return Math.Round(total, 2);
}

private static decimal CalculateLineTotal(
    InvoiceLine line,
    CustomerType customerType,
    bool isTaxExempt,
    decimal gstRate)
{
    var lineTotal = line.Qty * line.Price;
    bool taxable = !isTaxExempt &&
        customerType is CustomerType.Business or CustomerType.Consumer;
    return taxable ? lineTotal * (1 + gstRate) : lineTotal;
}

The tax condition still applies only to Business and Consumer customers. Other customer types, such as a hypothetical Charitable type, get no tax, exactly as in the original. Null lines are still skipped by the Where filter, so they do not throw.

Trace that behaviour is preserved

InputBeforeAfter
---------
---------
2 lines: 2 x 100.00, 1 x 50.00, Business, taxable287.50287.50
Same lines, Business, tax exempt250.00250.00
Same lines, Charitable, taxable250.00250.00
One null line, one valid 1 x 50.00, Consumer, taxable57.5057.50
One line with Qty 0, one valid 1 x 50.00, Consumer, taxable57.5057.50
Empty list0.000.00

I would add those cases as unit tests before the refactor, watch them pass on the old code, then watch them pass on the new code. That trace is the evidence I would point to when discussing the change, rather than claiming the new code is cleaner.

Trade-offs and failure modes

Extracting CalculateLineTotal helps if tax rules grow, for example different rates per line type. If the method stays this small, the extra method is mild overhead, and I would accept that cost for the clearer name. Replacing the string with an enum removes typo bugs, but it changes the method signature, so callers need updating in the same commit.

The main failure mode in a live refactor is a subtle behaviour change hidden inside a rename, such as rounding per line instead of rounding the total, or dropping the customer type check. I guard against that with the trace above and by keeping the diff to one concern. A second failure mode is over-refactoring: splitting a 20-line method into many tiny classes makes it harder to follow. I would stop at the extraction and the naming, and leave larger design changes as a follow-up proposal.

I would close by asking whether the team wants strict validation or tolerance of bad lines, because that decision determines whether the Where filter stays or becomes an explicit error.

Curated: · Written: · Reviewed:

Difficulty: Hard

Curated: · Written: · Reviewed: