Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at Atlassian

New

Interview Q&A

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

Q&A-1Design a tagging system like tagging pages or issues, with a focus on REST API design?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

I would model a tag as its own resource, separate from the page or issue it labels. That separation matters at Atlassian scale because the same tag, say incident-2024, can appear on a Confluence page and on three Jira issues, and deleting it from one target must not delete it from the others. So I keep three things apart: the tag itself, the tagging relation, and the target.

JSON
// Tag
{ "id": "tag_9f2", "name": "incident-2024", "displayName": "Incident-2024",
  "createdBy": "user_118", "createdAt": "2026-01-14T09:31:00Z", "usageCount": 42 }

// Tagging relation, returned when you list tags on a target
{ "tagId": "tag_9f2", "targetType": "issue", "targetId": "OPS-1042",
  "addedBy": "user_118", "addedAt": "2026-01-14T09:32:00Z" }

name is the normalized identity: trimmed, lowercased, Unicode-normalized, internal whitespace collapsed to a single hyphen. displayName preserves what the creator typed for display. Normalizing at write time is what stops Incident, incident and INCIDENT becoming three tags that search treats as one.

Endpoints

OperationEndpointContract detail
---------
---------
---------
---------
create or get tagPOST /tags with {"name": "..."}returns existing tag if name already exists, 201 if new
autocompleteGET /tags/search?q=inc&limit=20prefix match on name, cursor pagination
list tags on targetGET /targets/issues/OPS-1042/tagstarget addressed by type and id
add tagsPOST /targets/issues/OPS-1042/tags with {"tagNames": ["a","b"]}set semantics, idempotent
remove tagDELETE /targets/issues/OPS-1042/tags/tag_9f2204, repeat delete also 204
replace all tagsPUT /targets/issues/OPS-1042/tagsfull replacement, requires If-Match
find targets by tagGET /tags/tag_9f2/targets?targetType=issuepermission-filtered, cursor pagination

Two design choices carry most of the weight. First, adding tags is a set operation, not a create. POST .../tags with a name that already exists attaches the existing tag and returns 200; a genuinely new name creates it and returns 201 for that entry. A retry of the same request therefore converges instead of creating duplicates. Second, replacement is a separate verb. Clients that edit a page in one save want PUT to mean "make the set exactly this", guarded by If-Match with the target's ETag, so two editors cannot silently overwrite each other. Mixing add and replace into one endpoint is where lost updates hide.

Worked trace

Hypothetical figures, labelled as such. A user tags issue OPS-1042 with incident-2024 and oncall:

StepRequestResult
---------
1POST /targets/issues/OPS-1042/tags {"tagNames":["Incident-2024","oncall"]}incident-2024 normalized, tag created, relation inserted, 201
2Same request retried after a timeoutBoth relations already exist, 200, no duplicate rows
3GET /tags/search?q=incReturns incident-2024 with usageCount: 1
4DELETE /targets/issues/OPS-1042/tags/tag_9f2 twice204 both times, tag itself survives

The unique constraint that makes step 2 safe is (target_type, target_id, tag_id) in the tagging table, plus a unique index on tags.name. Concurrent creates of the same new name race on that index; the loser catches the conflict and re-reads the winner's row instead of returning 500.

yes no POST tags on target Normalize names Upsert tag rows by name Insert tagging relations Conflict on unique index? Re-read existing rows, return 200 Return 201 with relations

Failure modes I would name in the loop

Permission leakage is the one Atlassian reviewers care about. GET /tags/{id}/targets must filter by the caller's access to each target. A user without permission to see a private Confluence space must not learn that a page exists, or what tags it carries, through tag search. That means the filter happens before pagination, not after, or page sizes leak counts.

Tag explosion is the second. Free-text creation with no length or character rules produces thousands of near-duplicates and makes autocomplete useless. I would cap name at 50 characters, reject empty and punctuation-only names with 422 and a code, and require a separate permission to create global tags versus attaching existing ones. Usage counts should be maintained asynchronously from a counter table, not incremented in the request path, or a popular tag becomes a write hotspot.

Orphan tags are the third. Deleting the last relation should not delete the tag immediately, because a concurrent attach may be in flight. I would keep the tag, let a background job reap tags with zero relations after a grace period, and never cascade-delete tags when a page or issue is deleted. The cascade runs the other way: deleting a target deletes its relations only.

For scale, listing targets by tag is the expensive query, so it gets a keyset cursor on (added_at, target_id) rather than offset pagination, and autocomplete is served from a prefix index on name rather than a scan. If tag search needs full-text ranking later, that is a search index problem, not a reason to change the resource model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2Design and implement an agent-rating service that records a score of 1-5 for a named agent with a running average and returns agents ranked by average score descending?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

Keep one aggregate per agent: a count and a sum. A rating updates both, the average is sum divided by count, and ranking is a snapshot sorted by that average. That gives O(1) recording and a correct running average without storing every rating.

The interview version is a thread-safe in-memory map. In production I would persist the same aggregate in a database and update it in one atomic statement, because an in-memory map loses everything on restart and cannot be shared across instances.

Implementation

Java
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

public class AgentRatingService {

    private static final class Stats {
        final AtomicLong count = new AtomicLong();
        final AtomicLong sum = new AtomicLong();
    }

    private final ConcurrentHashMap<String, Stats> byAgent = new ConcurrentHashMap<>();

    public void recordRating(String agent, int score) {
        if (agent == null || agent.isBlank()) {
            throw new IllegalArgumentException("agent must not be blank");
        }
        if (score < 1 || score > 5) {
            throw new IllegalArgumentException("score must be between 1 and 5");
        }
        Stats s = byAgent.computeIfAbsent(agent, k -> new Stats());
        s.count.incrementAndGet();
        s.sum.addAndGet(score);
    }

    public record RankedAgent(String agent, double average, long ratings) {}

    public List<RankedAgent> rankedAgents() {
        return byAgent.entrySet().stream()
            .map(e -> {
                long c = e.getValue().count.get();
                long sum = e.getValue().sum.get();
                return new RankedAgent(e.getKey(), c == 0 ? 0.0 : (double) sum / c, c);
            })
            .sorted(Comparator.comparingDouble(RankedAgent::average).reversed()
                .thenComparing(Comparator.comparingLong(RankedAgent::ratings).reversed())
                .thenComparing(RankedAgent::agent))
            .toList();
    }
}

computeIfAbsent creates the aggregate once per agent. The two atomic increments avoid the classic lost-update bug. A naive version that reads count and sum, adds, and writes back loses a rating when two threads interleave.

Worked trace

CallState for priya (count, sum)Average
recordRating("priya", 5)(1, 5)5.00
recordRating("priya", 3)(2, 8)4.00
recordRating("priya", 4)(3, 12)4.00
recordRating("sam", 5)sam: (1, 5)5.00

rankedAgents() then returns sam (5.00, 1 rating) ahead of priya (4.00, 3 ratings). That exposes a product decision worth raising in the interview: a single 5-star rating outranks a proven 4.0. If the ranking is shown to users, I would add a minimum rating count, for example only agents with at least 10 ratings qualify, or rank by a Bayesian average that pulls small samples toward the global mean.

Concurrency failure mode

InterleavingNaive read-modify-writeAtomic increments above
Thread A reads count=2, sum=8A writes count=3, sum=13A increments to 3, 13
Thread B reads count=2, sum=8B writes count=3, sum=12, overwriting AB increments to 4, 17
ResultOne rating lost, average wrongBoth ratings counted

Reading count and sum separately in rankedAgents() can also pair a new count with an old sum for a split second. For a leaderboard that is acceptable, but if exact consistency matters I would snapshot under a per-agent lock or store the pair in an immutable holder swapped with AtomicReference.

Scaling and persistence

Recording stays O(1). Ranking is O(n log n) in the number of agents on every call, which is fine for thousands and wasteful for millions. At that point I would cache the sorted list, invalidate it on write, paginate the response, and push the sort into SQL with an index on the aggregate table: ORDER BY sum * 1.0 / count DESC LIMIT 50.

For storage, the same aggregate maps to one row per agent. The update becomes UPDATE agent_ratings SET count = count + 1, sum = sum + ? WHERE agent = ?, executed in a transaction, with a unique constraint on agent. That survives restarts, works across service instances, and keeps the running average exact without replaying a ratings table.

Edge cases to state out loud: reject scores outside 1 to 5 rather than clamping them, reject blank agent names, define tie-breaking before the interviewer asks, and decide whether rankedAgents() returns all agents or a top N page.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3Implement a sliding window rate limiter?

Reported in Atlassian Software Engineer Interview Questions & Loop | prepare.fyi

The 90-second answer

Assume one limit per API key, say 100 requests per 60 seconds, and that the interviewer wants the single-process version first. I would implement a sliding window log: keep the timestamp of every allowed request for that key, drop timestamps older than now - window, and allow the new request only if the remaining count is below the limit. That gives an exact count over the last 60 seconds, unlike a fixed window that resets at the minute boundary and lets a client send 100 at 12:00:59 and another 100 at 12:01:01.

Then I would say where that breaks in production, because Atlassian style services such as Jira and Confluence run many instances behind a load balancer. The in-memory version is correct per process and wrong globally. The production version moves the log to Redis as a sorted set, scored by timestamp, and does prune, count and insert in one Lua script so concurrent requests cannot race.

Python
import time
from collections import deque

class SlidingWindowRateLimiter:
    def __init__(self, limit: int, window_seconds: float):
        self.limit = limit
        self.window = window_seconds
        self.hits: dict[str, deque[float]] = {}

    def allow(self, key: str, now: float | None = None) -> tuple[bool, int]:
        now = time.monotonic() if now is None else now
        q = self.hits.setdefault(key, deque())
        cutoff = now - self.window
        while q and q[0] <= cutoff:
            q.popleft()
        if len(q) >= self.limit:
            retry_after = int(q[0] + self.window - now) + 1
            return False, retry_after
        q.append(now)
        return True, 0

time.monotonic() matters here. Wall clock time can jump backwards on an NTP correction and either grant a burst or block everyone. Monotonic time only moves forward within a process. In Redis I would use the Redis server time inside the script for the same reason, rather than trusting a client clock.

Worked trace

Limit 3 per 10 seconds, one key:

Time (s)ActionLog after pruningDecision
0request[0]allow
2request[0, 2]allow
4request[0, 2, 4]allow
5request[0, 2, 4]deny, Retry-After: 6
10.1request[2, 4] after dropping 0allow, log becomes [2, 4, 10.1]

At 5 seconds the oldest entry expires at 10, so the client waits about 5 seconds, rounded up to 6 in the header. Returning that value lets a well behaved client back off instead of hammering the endpoint.

Choosing the variant

VariantHow it countsCostWhen I would use it
Sliding window logevery timestampO(limit) memory per keyexactness matters, limit is modest
Sliding window countercurrent and previous fixed buckets, weightedO(1) memory per keyhigh traffic, small error acceptable
Fixed window counterone bucket per windowO(1) memory per keysimple quotas, boundary burst acceptable

The log costs memory proportional to the limit. At 100 requests per minute per key and 100,000 active keys that is 10 million timestamps in the worst case, which is why the counter variant exists. It estimates the sliding count as prev * (1 - elapsed/window) + curr. That can over or under count by a few requests when traffic is uneven, so I would only pick it after stating that error to the interviewer.

Distributed version and failure modes

In Redis, each key maps to a sorted set. The Lua script removes entries with score at or below now - window, counts the rest, and adds the new entry only when under the limit. One script call is atomic, so two instances cannot both read count 99 and both admit request 100.

Three failures I would name unprompted. First, unbounded growth from a key that never expires: set a TTL on the Redis key equal to the window so idle keys disappear. Second, Redis unavailability: decide explicitly whether to fail open and admit traffic during an outage, or fail closed and return 503. For a public API I usually fail open with an alert, because a rate limiter outage should not become a full outage, but I would state that as a product decision. Third, clock skew across app servers if timestamps are generated client side: generating now inside Redis removes that dependency.

On the wire, an allowed response carries X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. A denied response is 429 Too Many Requests with Retry-After and the same headers. That contract is what lets clients implement backoff without guessing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4Find the lowest common ancestor of a binary tree?

Reported in Atlassian Software Engineer Interview Questions & Loop | prepare.fyi

The 90-second answer

Assume a general binary tree, not a binary search tree, and that p and q are nodes in it. The lowest common ancestor is the deepest node that has both p and q in its subtree, where a node counts as its own descendant. I would write the recursive version first, then discuss the iterative version if the tree can be deep.

Java
// Java 17
static class Node { int val; Node left, right; Node(int v) { val = v; } }

static Node lca(Node root, Node p, Node q) {
    if (root == null || root == p || root == q) return root;
    Node left = lca(root.left, p, q);
    Node right = lca(root.right, p, q);
    if (left != null && right != null) return root; // split found here
    return left != null ? left : right;             // propagate the one hit
}

The logic is a post-order search. If the current node is p or q, it is a candidate and the search stops in that branch. If both children return a hit, the targets lie in different subtrees, so this node is the split point and therefore the answer. If only one child returns a hit, both targets are in that subtree, so the hit bubbles up unchanged.

Worked trace

Tree: 3 has children 5, 1; 5 has 6, 2; 1 has 0, 8; 2 has 7, 4. Call lca(root, 5, 4).

CallLeft resultRight resultReturns
lca(4, 5, 4)nullnull4 (matches q)
lca(2, 5, 4)null44
lca(5, 5, 4)null45 (matches p)
lca(3, 5, 4)5null5

The answer is 5, which is correct because 5 is an ancestor of 4 and is deeper than 3. A second call, lca(root, 7, 4), returns 2: both children of 2 return hits, so 2 is the split point. That second case is the one candidates most often miss when they return the first hit they see.

When the assumptions change the answer

InputAlgorithmTimeExtra space
General binary tree, no parent pointersPost-order search aboveO(n)O(h) recursion stack
Binary search tree, values orderedWalk down comparing values to p and qO(h)O(1) iterative
Nodes have parent pointersMark ancestors of p in a set, walk up from qO(h) averageO(h) set

For a BST the post-order version still works, but it wastes the ordering. The BST walk is: if both values are smaller, go left; if both are larger, go right; otherwise this node is the split. I would state that distinction up front, because interviewers use this question to check whether you ask what kind of tree it is before coding.

Failure modes and follow-ups

Time is O(n) because in the worst case, when one target is absent or both sit deep in one branch, every node is visited. Space is O(h), where h is tree height, so a balanced tree costs O(log n) stack and a skewed tree of 100,000 nodes costs O(n) stack and can overflow the JVM stack. For that case I would switch to an explicit stack doing a post-order traversal, or store parent pointers during a BFS from the root and then walk up from both targets. The iterative version keeps the same O(n) time and trades call stack for heap-allocated stack frames.

Two edge cases to name without being asked: if either p or q is null, or neither is in the tree, the function returns null, and the caller must decide whether that means "not found" or is a programming error. If p == q, the answer is that node, and the base case handles it. If the interviewer wants the LCA of more than two nodes, the same recursion extends by folding pairwise, or by returning the set of found targets and checking whether all are present at a split.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Design a system ID generator that generates unique IDs for different apps, with two APIs: one for random output and one where the client has a preferred ID?

Reported in Atlassian Software Engineer Interview Questions & Loop | prepare.fyi

The 90-second answer

I would build one ID Generator service used by every Atlassian app, with IDs namespaced by app. Jira, Confluence and Bitbucket can each mint IDs independently, but the pair (app_id, id) is globally unique in the store. That gives apps freedom to choose their own format and length without a central counter becoming a bottleneck or a privacy leak.

Two APIs sit on top of the same store:

HTTP
POST /v1/ids/random      {"appId":"jira","format":"uuidv7"}
POST /v1/ids/preferred   {"appId":"jira","preferredId":"PROJ-1042"}

Random returns a fresh ID. Preferred tries to claim a client-chosen ID and either succeeds or returns a conflict. The client never gets a silent substitute, because downstream systems will have already stored the preferred value.

Random generation

For opaque IDs I would use 128 bits from a CSPRNG, encoded as UUIDv7 if the app wants time-ordered keys for database locality, or plain UUIDv4 / ULID otherwise. No sequential counter. A counter is predictable, leaks volume ("issue 9,001,442" tells a competitor your scale), and serialises writes.

Collision math, with real figures: at 128 bits, the birthday bound is about $2^{64}$ IDs. At 10 million IDs per day across all apps, the probability of a collision in a year is roughly $n^2 / 2^{129} \approx (3.65 \times 10^9)^2 / 6.8 \times 10^{38} \approx 2 \times 10^{-20}$. Negligible, but I still insert into a table with a unique index on (app_id, id) and retry on conflict. The index is the guarantee; the randomness is what makes the retry almost never happen.

Java
// Java 17, checked against java.util.UUID
public String randomId(String appId) {
    for (int attempt = 0; attempt < 3; attempt++) {
        String id = UUID.randomUUID().toString(); // v4; swap for v7 if ordered keys needed
        try {
            idStore.insert(appId, id, Source.RANDOM);
            return id;
        } catch (DuplicateKeyException e) {
            // fall through and mint again; do not return the colliding id
        }
    }
    throw new IdGenerationException("retry budget exhausted");
}

Preferred IDs

The client supplies a candidate. The service validates it, then attempts the insert. Validation is cheap and local: length bounds, allowed charset, no reserved prefixes (admin, system, null), and per-app format rules. For example Jira might require ^[A-Z]{2,10}-[0-9]+$ for issue keys, while a generic app might allow [a-z0-9-]{3,64}.

The race is the interesting part. Two clients can both pass a "does this exist?" check for PROJ-1042 at the same moment. So there is no check-then-insert. The unique index decides, and the loser gets a 409:

StepClient AClient BStore
1POST /preferred PROJ-1042
2POST /preferred PROJ-1042
3insert succeedsinsert hits unique indexPROJ-1042 owned by A
4201 {"id":"PROJ-1042"}409 {"code":"id_taken","suggestion":"PROJ-1043"}

A suggestion is helpful but optional. If the client wants a guaranteed ID before committing to it, I would add a short-lived reservation: POST /v1/ids/reservations returns a token valid for, say, 10 minutes, and the preferred insert must present that token. Without it, a client that checks availability, goes away for a day, and then claims the ID will be surprised. I would not add reservations by default, because they create abandoned holds and a cleanup job. I would add them only if a real client flow needs the guarantee.

Failure modes I would name in the loop

Entropy failure: if the CSPRNG is seeded badly or a VM snapshot replays state, UUIDv4 can repeat. Mitigation is the unique index plus retry, and monitoring the duplicate-key rate. A spike means something is wrong upstream, not that the math broke.

Hot partition: if one app mints 90% of IDs, a single table with a unique index on (app_id, id) still scales, because inserts are appends. The risk is a per-app sequence, which is why I avoided one.

Format drift: apps change their preferred-ID rules over time. Store the format version with each ID, so old IDs remain valid under the rules they were minted with.

invalid valid insert ok duplicate Client ID Generator API Validate appId and format 400 or 422 ID store: unique app_id, id 201 with id 409 id_taken

The shape to defend: randomness for the default path, a unique index as the real uniqueness mechanism, and a preferred path that fails loudly instead of substituting. That keeps both APIs honest under concurrency, which is where most designs for this question quietly break.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6Design a notification service for Jira or a real-time collaborative editor similar to Confluence?

Reported in Atlassian Software Engineer Interview Questions & Loop | prepare.fyi

The 90-second answer

I would build a notification service for Jira around one rule: the event that caused the notification is immutable, and everything downstream is a retryable, idempotent fan-out. A comment added, an issue assigned, a status changed. Those events land in a durable log first. A separate fan-out step decides who should hear about it, checks their preferences, deduplicates, and only then hands work to email, push, or in-app delivery.

That split matters because the hard parts are not sending an email. They are sending it exactly once per recipient per event, respecting opt-outs that changed mid-flight, and surviving a bulk import that creates 50,000 events in a minute without burying the one comment a teammate is waiting on.

Core flow

Jira event: comment, assign, transition Ingest API: validate and persist event Fan-out worker: resolve recipients Preference and dedup check Per-channel queues Email, push, in-app delivery Delivery receipt and bounce handling

Ingest accepts an event_id from the producer (for Jira, the issue activity ID works well) and writes it to a table or Kafka topic before returning 202. Producers can retry safely because the write is keyed on event_id. Fan-out then expands the event into recipient rows. Recipients come from watchers, assignee, reporter, mentioned users, and project role filters, minus the actor who caused the event and minus anyone who muted that issue.

Data model and dedup

TableKey columnsPurpose
---------
notification_eventevent_id, issue_id, type, actor_id, created_at, payload JSONImmutable source of truth
notification_recipient(event_id, user_id) unique, channel, statusOne row per intended delivery
user_notification_prefuser_id, event type, channel, digest mode, quiet hoursChecked at fan-out time
delivery_attemptrecipient_id, channel, provider id, status, errorAudit and retry state

The unique constraint on (event_id, user_id, channel) is the dedup mechanism. A fan-out worker that crashes and replays the event inserts the same rows and gets conflicts it can ignore. No separate dedup cache to keep consistent.

Java
// Java 17, fan-out worker. Insert is idempotent on the unique key.
for (User recipient : resolveRecipients(event)) {
    if (recipient.id().equals(event.actorId())) continue;
    if (!prefs.allow(recipient.id(), event.type(), Channel.EMAIL)) continue;
    try {
        recipientRepo.insertIgnore(new Recipient(
            event.id(), recipient.id(), Channel.EMAIL, Status.PENDING));
    } catch (DuplicateKeyException ignored) {
        // Replay after a crash: this delivery was already queued.
    }
}

Scale, with labelled hypothetical figures

Assume a large Jira Cloud instance peaks at 5,000 issue events per minute and averages 6 recipients per event. That is 30,000 recipient rows per minute, or 500 writes per second, before digests. Email is the bottleneck, not the database. At a provider limit of, say, 200 messages per second per sending domain, email delivery needs a queue that absorbs bursts and drains at a controlled rate, while in-app notifications can write straight to the inbox table and push via WebSocket to connected clients.

Digest mode changes the shape. Instead of one email per event, the worker accumulates pending items per user and flushes hourly or daily summaries. That turns a spike of 200 comments on a watched epic into one email, which is usually what users asked for when they chose digest.

Failure modes I would name in the interview

A poison event, such as a payload with a deleted user ID, must not block the partition. Send it to a dead-letter queue after a bounded number of retries and alert on the DLQ depth, not on individual failures. A preference change racing fan-out is handled by checking preferences at fan-out time and again at send time for email, since the gap can be minutes in a backlog. Provider bounces and hard failures feed back into a suppression list so the service stops emailing an address that no longer exists, and that state is visible in the delivery table for support to debug.

For the Confluence-style collaborative editor variant, I would swap the fan-out problem for presence and document operations: a WebSocket gateway per region, operational transforms or a CRDT for concurrent edits, and a snapshot plus operation log so a reconnecting client can catch up. The notification service stays the same underneath, because a mention in a page is still an event that needs recipients, preferences, and dedup.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7Build a file storage system?

Reported in Atlassian Software Engineer interview experience (September 2026)

The 90-second answer

I would separate the bytes from the facts about the bytes. Object storage holds the file content, a metadata service holds ownership, permissions, version and lifecycle, and an API layer issues short-lived upload and download URLs so clients never push large files through the app servers.

Assume the Atlassian shape: attachments for Jira issues and Confluence pages, files from a few KB to a few GB, millions of objects, reads far outnumber writes, and a user who loses an attachment upload will notice immediately. That pushes the design toward resumable uploads, content addressing for deduplication, and strong metadata consistency even if the blob write is eventually consistent.

Client Upload API Metadata DB URL signer Object store CDN Lifecycle worker

Upload path

A client calls POST /files with name, size, content type and the parent resource, for example issueId or pageId. The API checks permission on that parent, creates a file record in PENDING state, and returns a presigned multipart URL. The client uploads parts directly to object storage, then calls POST /files/{id}/complete with the part ETags. Only then does the file become READY.

Multipart matters for the failure case interviewers probe. A 2 GB video over a flaky connection will not survive a single PUT. With 8 MB parts, a failed part is retried alone, and an interrupted session can resume from the parts already stored. The complete call assembles the object server side, verifies the checksum, and flips the metadata state. If the client never completes, a lifecycle worker deletes orphaned parts after 24 hours.

Python
# Python 3.12, boto3 1.34, checked against S3 multipart semantics
import boto3
s3 = boto3.client("s3")
resp = s3.create_multipart_upload(Bucket="attachments", Key="f_9c21/parts")
url = s3.generate_presigned_url(
    "upload_part",
    Params={"Bucket": "attachments", "Key": "f_9c21/parts",
            "UploadId": resp["UploadId"], "PartNumber": 1},
    ExpiresIn=3600,
)

Metadata and content addressing

Store one row per file: file_id, owner_id, parent_type, parent_id, object_key, sha256, size, content_type, version, state, created_at. Compute SHA-256 on complete and use it as the object key prefix, for example sha256/ab/cd/abcd.... Two users uploading the same Confluence template then share one stored object, with two metadata rows pointing at it. Deletion becomes a reference count problem, so I would only garbage collect an object when no READY row references its hash.

ConcernChoiceWhy
---------
---------
---------
UploadPresigned multipart, 8 MB partsResumable, app servers stay out of the data path
Identityfile_id UUID, hash for storage keyStable API id, deduplication underneath
DownloadPresigned GET, 5 min expiry, via CDNNo long-lived public URLs, cache at the edge
VersioningNew file_id per version, version counter on parentOld links keep working, rollback is a pointer change
PermissionsChecked at presign time, rechecked on downloadRevoked access stops working within minutes

Download and consistency

GET /files/{id} returns metadata plus a presigned URL when the caller has access to the parent. The CDN caches the object by hash, so repeat downloads of the same attachment do not hit origin. Metadata reads come from the primary database. Object reads can be eventually consistent, because the file only becomes READY after the complete call confirms the object exists. That ordering removes the classic bug where a listing shows a file whose bytes are not there yet.

Failure modes I would name

A complete call that times out after S3 assembled the object leaves the row in PENDING. The retry must be idempotent: completing twice with the same part list returns the same READY file instead of a second copy. A checksum mismatch on complete means a part was corrupted in transit, so the API rejects the assembly and keeps the session open for re-upload of the bad part. A permission change between presign and download is bounded by the 5 minute URL expiry, and sensitive files can skip the CDN with Cache-Control: private, no-store.

Scale check, hypothetical figures

At 10 million files averaging 2 MB, the store holds about 20 TB of logical data before deduplication. Metadata at roughly 500 bytes per row is about 5 GB, which fits a sharded relational database keyed by parent_id for listing an issue's attachments. The bottleneck is not storage cost. It is the complete call rate during bulk imports, so I would batch checksum verification and keep the metadata transaction to a single row update.

I would not build this on the application servers' local disk, and I would not expose raw object storage credentials to clients. Both choices look simpler in a demo and break on the first multi-instance deploy or the first permission audit.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8Design something like Google Sheets?

Reported in Atlassian Software Engineer interview experience (March 2025)

The 90-second answer

I would split this into three problems that fail independently: the spreadsheet model, formula recalculation, and realtime collaboration. If I try to solve them as one editor, I end up with a client that corrupts data under concurrency and a server that cannot recalculate a 10,000-row sheet without blocking.

The model is a sparse grid. A sheet has cells addressed by (row, col). A cell holds either a literal value or a formula string. Formulas form a directed acyclic graph of dependencies: C1 = A1 + B1 means C1 depends on A1 and B1. Recalculation walks that graph in topological order and only touches cells downstream of a change.

Collaboration is server-authoritative operational transformation for cell edits, not a CRDT over the whole grid. Each edit is an operation with a sequence number assigned by the server. Clients apply local edits optimistically, then reconcile against the server order. That gives one total order for conflicting writes to the same cell, which is what users expect when two people type in A1 at once.

Storage is append-only operation log plus periodic snapshots. The log is the source of truth for replay and audit. A snapshot materialises cell values and formulas so a new client does not replay a year of edits.

Core data structures

TypeScript
// TypeScript, checked against a typical React + Node stack
type CellId = string; // "A1", "B12"; encode as (row << 20) | col internally

interface Cell {
  id: CellId;
  value: string;        // literal or formula text, e.g. "=SUM(A1:A10)"
  computed?: number;    // cached result for formula cells
  version: number;      // last server sequence applied to this cell
}

interface Operation {
  opId: string;         // client-generated UUID, for idempotent retry
  sheetId: string;
  seq: number;          // assigned by server, strictly increasing per sheet
  cellId: CellId;
  value: string;
  authorId: string;
  lamport: number;      // tie-breaker before server seq is known
}

A formula parser turns =SUM(A1:A10)*1.1 into an AST, then into dependency edges. I would not evaluate formulas in the browser with eval. A small recursive-descent parser for functions, ranges, and cell refs is enough for the interview scope and keeps the security boundary clear.

Recalculation trace

Suppose A1=2, B1=3, C1==A1+B1, D1==C1*2. The user edits A1 to 5.

StepCellActionResult
1A1literal set to 55
2C1dependency A1 changed, recompute8
3D1dependency C1 changed, recompute16
4B1no dependency on A1, untouched3

With 10,000 rows and, say, 2,000 formula cells (hypothetical figures for sizing), a full recompute on every keystroke is wasteful. Incremental recalc touches only the downstream subgraph. If that subgraph is large, say over 5,000 cells, I would move it to a worker thread on the client and to a background job on the server, and show stale results with a "recalculating" indicator rather than blocking input.

Cycles need a decision. A1==B1+1 and B1==A1+1 form a cycle. I detect it during graph construction, mark both cells with #REF! style error, and refuse to propagate further. Silent iteration to a fixed point hides user errors.

Realtime flow

Client A edits A1 Local optimistic apply Send Operation to server Server assigns seq, appends to log Broadcast to other clients Clients transform and apply Recalculate downstream cells

Conflict case: A and B both edit A1 within 200 ms. The server orders them, say A first. B's client receives A's operation, rebases its pending edit on top, and the UI shows B's value winning because it has the higher sequence. No data is lost, and the operation log shows both edits for undo and audit. Undo is itself an operation that sets the cell back, rather than deleting history.

Presence, cursor position, and selection are ephemeral. They go over WebSockets but are never written to the operation log. If I persisted them, a sheet with 50 collaborators typing would generate thousands of useless log entries per minute.

Scale and failure modes

A single sheet is the consistency unit. I shard by sheetId, so operations for different sheets do not contend. Within a sheet, one writer at a time for sequence assignment keeps ordering simple. At Atlassian scale, that maps to a per-sheet actor or a single-threaded partition in a stream processor. Throughput per sheet is then bounded by how fast we can append and broadcast, which for cell edits is comfortably in the hundreds per second. If a sheet exceeds that, the bottleneck is human typing speed, not the server.

Three failures I would name in the interview:

  1. Client disconnects mid-edit. The client keeps its pending operations with their opId. On reconnect it resends them. The server deduplicates by opId, so a retry does not double-apply.
  2. Snapshot falls behind the log. A new client loads the latest snapshot, then replays operations after the snapshot sequence. If the gap is large, say over 10,000 operations, I serve a fresh snapshot instead of replaying.
  3. Formula injection. A cell starting with = is parsed as a formula, never executed as code. Functions are an allowlist (SUM, AVERAGE, IF, VLOOKUP style lookups). Anything outside the allowlist is a parse error shown in the cell.

What I would not build first

I would not start with a CRDT for the grid, offline-first sync, or charts and pivot tables. Those are real requirements for a Sheets clone, but they sit on top of the model, recalc, and operation log. Getting cell-level ordering and incremental recalculation right is what makes the later features safe to add. Charts are just views over computed cells. Offline editing is the same operation log with a longer pending queue.

For an Atlassian context, I would also call out permissions early. Sheets in Confluence or Jira are shared with groups, not just individuals. Every operation needs an authorisation check against the sheet's ACL before it gets a sequence number, and the broadcast channel must be scoped to authorised users only. A client that can guess a sheetId must not receive its operations.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9Design a scalable image upload service?

Reported in Atlassian Software Engineer interview experience (March 2025)

The 90-second answer

I would not proxy image bytes through the app servers. The client uploads directly to object storage with a short-lived presigned URL, the service only mints that URL and records metadata, and a separate pipeline validates, scans and derives thumbnails before the image becomes visible. That separation is what scales: the control plane is cheap and stateless, the data plane is S3 or equivalent, and reads go through a CDN.

Assume peak 5,000 uploads per minute, average 2 MB, 99% JPEG/PNG/WebP and 1% GIF. That is about 10 GB per minute, 14 TB per day before derivatives. A proxy would need roughly 10 GB/min of egress through the fleet and would saturate long before storage does. Direct upload removes that bottleneck and lets storage absorb bursts.

Client Upload API Metadata DB Object storage presigned URL Scan and thumbnail workers Reader CDN

Flow

  1. Client calls POST /images with filename, declared content type, size and a SHA-256 of the content if it has one. The API authenticates, checks quota and content type allowlist, creates a row in image_uploads in state PENDING, and returns a presigned PUT URL valid for 5 minutes plus an upload ID. For files over 20 MB it returns multipart part URLs instead, so a dropped connection resumes from the last completed part rather than restarting.
  2. Client uploads straight to the bucket under a server-generated key such as images/{tenant_id}/{upload_id}/original. Never trust a client-supplied key. It invites overwrites and path tricks.
  3. On completion the client calls POST /images/{id}/complete. The service verifies the object exists, its size matches, and its hash matches when supplied. Only then does it enqueue scan and thumbnail jobs and move the row to PROCESSING.
  4. Workers run antivirus and image decoding in a sandbox, strip EXIF GPS data, generate 3 derivatives (thumbnail, medium, large) as WebP, and write them to the same bucket. The row moves to READY only after scan passes. Readers never see PENDING or PROCESSING images.
EndpointReturnsNotes
POST /images201, upload ID, presigned URLIdempotency-Key required, replayed for 24 h
POST /images/{id}/complete202async processing, poll or webhook for READY
GET /images/{id}metadata, derivative URLsCDN URLs once READY, 404 before
DELETE /images/{id}202tombstone row, lifecycle deletes object in 24 h

Why this shape

Deduplication is cheap at this point. If the client sends SHA-256 and that hash already maps to a READY image for the same tenant, return the existing ID and skip the upload. At Atlassian scale, screenshots and pasted diagrams repeat a lot, and this can cut storage noticeably. Hashing server side on every object is also possible, but it forces a read of the full object before dedup helps, so client hash plus server spot check is the pragmatic split.

Metadata goes in a relational store sharded by tenant ID, because access control is per tenant and per issue or page. The object key embeds tenant and upload ID, so a leaked URL for one tenant reveals nothing about another. Reads use signed CDN URLs with a 1 hour TTL for private attachments, public ones use plain CDN URLs. That distinction matters for Jira attachments versus a public Confluence page image.

Failure modes I would name in the loop

Orphan objects: clients mint a URL and never upload, or upload and never call complete. A nightly job lists objects older than 24 h with no READY row and deletes them, and the bucket has a lifecycle rule as backstop. Without this, storage grows with junk that no query can find.

Lying content type: a client declares image/png and uploads an HTML file or a polyglot. The worker sniffs magic bytes and re-encodes through the image decoder, which neutralises most polyglots. Serving from a separate CDN domain with Content-Disposition: inline and a strict Content-Security-Policy: default-src 'none' on the image domain limits the blast radius if something slips through.

Scan backlog: if workers fall behind, images sit in PROCESSING and users complain uploads vanished. I would alert on queue age over 2 minutes, scale workers on queue depth, and show the client a PROCESSING state rather than a broken image. A poison image that crashes the decoder goes to a dead letter queue after 3 attempts and the row moves to FAILED with a reason code.

Hot tenant: one customer bulk importing attachments can starve others. Per tenant rate limits on POST /images and separate worker queues per tier keep a single tenant from consuming the whole pool. That is the part I would add first if the interviewer pushes on multi-tenancy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10Rank teams by votes?

Reported in Atlassian Software Engineer Interview Questions & Loop | prepare.fyi

The 90-second answer

I would clarify what a vote is before writing SQL. Assume one vote per user per team, votes can be added and removed, and the caller wants the top N teams right now, paginated. Then ranking is counting votes per team, sorting by count descending, and breaking ties deterministically so pagination does not shuffle between pages.

The naive version is one aggregation:

SQL
-- PostgreSQL 15, votes(team_id, user_id, created_at)
-- UNIQUE (team_id, user_id) enforces one vote per user per team
SELECT team_id, COUNT(*) AS vote_count
FROM votes
GROUP BY team_id
ORDER BY vote_count DESC, team_id ASC
LIMIT 50;

That is correct for a few thousand votes. At Atlassian scale, with Jira and Confluence teams and millions of users, I would not run that on every request. I would keep a denormalised counter and a cached ranking.

Design

Store votes as the source of truth, and maintain team_vote_counts(team_id, vote_count, updated_at) in the same transaction as the vote insert or delete. The counter update is INSERT ... ON CONFLICT (team_id) DO UPDATE SET vote_count = team_vote_counts.vote_count + 1. If the vote insert fails on the unique constraint, roll back, so the counter never drifts from the rows.

For reads, cache the ranked list. A Redis sorted set fits well: member is team_id, score is vote_count. ZREVRANGE with WITHSCORES returns a page in O(log N + M). Rebuild it from team_vote_counts on a schedule and on cache miss, and update it incrementally on each vote change with ZINCRBY. If Redis is unavailable, fall back to the SQL query against team_vote_counts, which is indexed on (vote_count DESC, team_id ASC) and answers in a few milliseconds for the top 50.

Tie-breaking matters more than people expect. If two teams both have 1,204 votes, ORDER BY vote_count DESC alone returns them in whatever order the index or planner picks, and a client paging through results can see duplicates or miss a team. Adding team_id ASC as a secondary key makes the order total and stable. If the product wants earlier teams to win ties, use MIN(created_at) per team as the secondary key instead, but pick one rule and document it in the API contract.

Worked trace

Suppose votes arrive for three teams:

Eventteam_vote_counts afterRanked output (top 3)
user A votes team 7team 7: 17 (1)
user B votes team 3team 3: 1, team 7: 13 (1), 7 (1)
user C votes team 7team 7: 2, team 3: 17 (2), 3 (1)
user A removes vote from team 7team 7: 1, team 3: 13 (1), 7 (1)

The last row shows why the counter must move in the same transaction as the delete. A separate async job that recounts later would leave the ranking wrong in between.

Failure modes and follow-ups

Concurrent votes from the same user: the unique constraint rejects the second insert, the transaction rolls back, and the counter is untouched. Without that constraint, double-clicks and retries inflate counts.

Counter drift: if a bug or a manual data fix changes votes without touching the counter, the ranking is wrong until a reconciliation job runs. I would run a nightly recount that compares COUNT(*) per team against the counter and alerts on any mismatch above a small threshold, then repair from the source table.

Hot teams: a team going viral can receive thousands of votes per second. The counter row for that team becomes a contention point. At that point I would shard the counter by hashing user_id into, say, 16 sub-counters and summing them on read, accepting a slightly more expensive read to remove the write bottleneck.

Pagination: offset pagination is fine for a top-50 leaderboard, but if the list is long and votes change constantly, keyset pagination on (vote_count, team_id) is safer. The cursor encodes the last seen pair, and the next page asks for rows strictly after it, so a team gaining votes mid-scroll does not push another team off the page.

If the interviewer then asks about personalised ranking, such as teams ranked by votes from the caller's department, I would say the global counter no longer applies. That becomes a filtered aggregation over votes joined to the user's department, and I would precompute per-department counters the same way rather than scanning the full votes table per request.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11Design an authorization system that supports both role-based access control and resource-level ACLs across spaces, pages, projects, and issues?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

I would treat this as a design I am proposing, not as a description of any existing Atlassian implementation. I assume authentication already gives me a user ID and the groups that user belongs to. Authorization then has two layers. A container permission scheme, for a space or a project, maps roles to actions such as VIEW, EDIT, and ADMINISTER. A resource ACL on a page or an issue can then narrow that grant for specific users or groups. My rule is that the scheme is checked first and the ACL can only remove access, never add it beyond the scheme. That prevents a page owner from accidentally promoting someone whose container role is read only.

Resources form a hierarchy. A space contains pages, and pages can contain child pages. A project contains issues. A child inherits the container scheme. If a child sets its own ACL, I apply the intersection of the inherited grant and the child ACL. Moving a page to a new parent therefore requires a recheck, because the inherited grant may change.

denied allowed deny found no deny Request with user, action, resource Load resource and ancestors Check container scheme for role Return 403 Check resource ACL for explicit deny Allow and write audit record

Data model

I would store three sets of rows. A scheme table maps a container ID to pairs of role and action. A membership table maps a user or a group to a role in a container. An ACL table maps a resource ID to a principal, an action, and an effect of ALLOW or DENY. Groups keep the ACL small. One row for a group of 5,000 people replaces 5,000 rows for individual users.

Java
import java.util.Set;

enum Action { VIEW, EDIT, ADMINISTER }
enum Effect { ALLOW, DENY }

record AclEntry(String principalId, Action action, Effect effect) {}

interface AclStore {
    Set<AclEntry> entriesFor(String resourceId);
}

interface SchemeStore {
    boolean allows(String containerId, Set<String> userGroups, Action action);
}

class Authorizer {
    private final SchemeStore schemes;
    private final AclStore acls;

    Authorizer(SchemeStore schemes, AclStore acls) {
        this.schemes = schemes;
        this.acls = acls;
    }

    boolean can(String userId, Set<String> userGroups, String containerId,
                String resourceId, Action action) {
        if (!schemes.allows(containerId, userGroups, action)) {
            return false;
        }
        for (AclEntry entry : acls.entriesFor(resourceId)) {
            if (entry.action() == action && entry.effect() == Effect.DENY
                    && (entry.principalId().equals(userId)
                        || userGroups.contains(entry.principalId()))) {
                return false;
            }
        }
        return true;
    }
}

That snippet is deliberately small. In a real service I would cache the scheme result per user and container for a short period, for example 60 seconds, and invalidate it when membership or the scheme changes. I would not cache the final decision for a resource without also keying it on the ACL version, because an ACL edit must take effect promptly.

Worked trace

Assume space ENG allows role CONTRIBUTOR to EDIT, and page Roadmap in that space has a DENY entry for group contractors on EDIT.

CallerScheme checkACL checkOutcome
Priya, in contractors, role CONTRIBUTOREDIT allowed in ENGDENY matches her groupDenied, 403
Marcus, role CONTRIBUTOR, no ACL entryEDIT allowed in ENGNo matching DENYAllowed
Ana, role VIEWEREDIT denied in ENGNot reachedDenied, 403

The third row shows why order matters. If the ACL were read first and contained an ALLOW for Ana, a page setting could widen access beyond the container role. With my rule, it cannot.

Trade-offs and failure modes

ApproachWhere it fitsMain cost
Roles onlySmall teams with few exceptionsEvery exception needs a new role, which multiplies roles quickly
ACLs onlyFine grained sharing on individual itemsHard to answer who can edit a whole space or project
Scheme plus narrowing ACLContainers with a few restricted items inside themTwo places to maintain, so all write paths must call one evaluator

I would call out three failure modes. First, stale membership data. If a user is removed from a group, a cached scheme result can keep granting access until invalidation arrives, so removal should publish an invalidation event rather than relying on expiry alone. Second, page moves. Moving a page under a more restricted parent, or out of one, changes the inherited grant, so the move operation must recheck and reject moves that would widen access silently. Third, list endpoints. Checking every ACL row for every item in a list is slow, so I would filter first by container scheme in the query, then apply ACL denies to the returned page of results, and I would keep pagination cursors stable while doing so.

For a known resource the caller cannot access, I would return 403. I would reserve 404 for a resource ID that does not exist. That distinction helps clients and logs, and it avoids leaking whether a restricted page exists through a different status code. Every allow and deny decision should also write an audit record with the user, action, resource, and the versions of the scheme and ACL that were evaluated. When access is questioned later, that record shows which rule produced the outcome.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12Design a system that surfaces the top-N posts on Confluence based on views, likes, and comments within configurable time windows?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

I would split this into ingestion, scoring, and serving, and precompute the ranking instead of scoring on read. Confluence has millions of pages and a read path that must stay under about 100 ms, so a query that scans engagement events will not survive.

Events for a view, like, or comment go to Kafka with page_id, actor_id, event_type, timestamp, and a dedup key. A stream job aggregates them into time buckets, applies a weighted score with decay, and writes the current top-N for each configured window to a store the API can read in one lookup. The API then filters by the caller's permissions before returning anything.

That last point decides the design at Atlassian. A page a user cannot see must not appear, and its engagement must not leak through counts or ordering. Filtering a global top-10 after the fact both leaks information and returns fewer than 10 results when several top pages are private. So I compute rankings per permission segment, typically per space and per space permission group, and the API picks the segment matching the caller.

Confluence clients Kafka: engagement events Stream aggregation Scoring with decay Redis ZSETs per window and segment Top posts API

Scoring and configurable windows

For a page p in window W, I use:

score(p, W) = sum over events e in W of weight(e.type) * decay(age(e))

with decay(age) = 0.5 ^ (age / half_life). A comment is worth more than a like, and a like more than a view, because a view costs nothing and bots generate them. Weights and half-life live in a config service, versioned, so product can change views=1, likes=5, comments=10 without a deploy. Windows are also config: 1h, 24h, 7d, 30d are common, but the job should accept a new window by adding a bucket set, not by rewriting the pipeline.

WindowBucket sizePrecompute cadenceStorage per segment
1h1 minevery 30 sZSET, trim to top 100
24h5 minevery 1 minZSET, trim to top 100
7d1 hevery 5 minZSET, trim to top 100
30d6 hevery 15 minZSET, trim to top 100

Keeping only the top 100 per segment bounds memory. At 50,000 spaces times 4 windows times 100 entries, that is 20 million entries, which is large but manageable in Redis with short string keys, and in practice most spaces are inactive and can be evicted after 24 h with no writes.

The stream job maintains sliding sums per bucket. For a 24h window with 5 minute buckets, it keeps 288 buckets per page in a rolling structure, adds the new bucket, drops the expired one, and recomputes the score. That avoids rescanning a day of raw events on every tick.

Python
# Checked against Python 3.12, illustrative scoring core
WEIGHTS = {"view": 1, "like": 5, "comment": 10}
HALF_LIFE_HOURS = 24

def decay(age_hours: float) -> float:
    return 0.5 ** (age_hours / HALF_LIFE_HOURS)

def score(events):
    return sum(WEIGHTS[e["type"]] * decay(e["age_hours"]) for e in events)

Serving

GET /top-posts?window=24h&n=10&space_id=ENG resolves the caller's groups, picks the matching ZSET, and runs ZREVRANGE key 0 9 WITHSCORES. That is O(log M + N) and returns in single digit milliseconds from Redis. Page titles and excerpts are fetched from the page service in one batch call, and pages deleted or made private since the last tick are dropped at read time as a safety net, with the API over-fetching, say top 15, to fill 10 after that drop.

If a requested window is not precomputed, for example an ad hoc 3h window, I fall back to a slower path that queries the bucket store for that range. I would not offer arbitrary windows on the hot path. Configurable means a known set of windows product can tune, not any integer a client invents.

Failure modes I would name in the interview

View inflation: crawlers and refresh loops can dominate a view weighted score. I dedup views per actor per page per hour at ingestion, and cap the contribution of a single actor per page per window.

Late and duplicate events: Kafka delivery is at least once. The dedup key, event_id, is checked in the aggregation state, and events arriving more than 10 minutes late are counted in the next bucket rather than rewriting history, which keeps the job idempotent and simple.

Permission changes: when a page moves from public to restricted, its engagement must leave every segment it was in. Page service publishes a permission change event, and the job removes the page from affected ZSETs. Until that lands, the read time check against the page service is the backstop.

Cold start and hot spaces: a new space has no history, so the API returns an empty list rather than fabricating results. A very active space can churn its ZSET on every tick, so writes are batched per tick and Redis pipelining keeps that to one round trip per segment.

I would close by asking about scale assumptions, how many spaces and events per second, and whether personalised ranking per user is in scope, because that would push the design from per segment precomputation toward a per user model, which is a different system.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13Your document-signing system sends notifications after a signature event but some are silently dropped with nothing in the logs; how do you redesign this to be reliable?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

Silent drops with no log usually mean the code path that sends the notification can fail without anyone noticing. The classic cause is a dual write: update the signature in the database, commit, then call the notification service or queue in a second step. If the process crashes, times out, or the downstream call returns an error that is swallowed, the signature is saved and the notification is gone. No retry, no record, no alert.

I would replace that with a transactional outbox. The signature state change and an outbox row are written in the same database transaction, so either both survive a crash or neither does. A separate relay publishes outbox rows to the queue, marks them sent only after the broker acknowledges, and retries with backoff. The consumer records each event_id in an inbox table before sending, so a redelivery does not send a second email. A reconciliation job then compares signature events against sent notifications and alerts on any gap older than, say, 5 minutes.

Signing service Database transaction signature_events outbox Relay Kafka or SQS Notification consumer inbox dedup table Email or Slack

Schema and relay

SQL
CREATE TABLE outbox (
  event_id    UUID PRIMARY KEY,
  event_type  TEXT NOT NULL,        -- SIGNATURE_COMPLETED
  aggregate_id TEXT NOT NULL,       -- document_id
  payload     JSONB NOT NULL,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  published_at TIMESTAMPTZ,
  attempts    INT NOT NULL DEFAULT 0,
  last_error  TEXT
);
CREATE INDEX outbox_unpublished ON outbox (created_at)
  WHERE published_at IS NULL;

The signing transaction inserts the signature row and the outbox row together. The relay, in Java with Spring JDBC or JPA, claims rows in batches:

Java
// Relay loop, one transaction per batch
List<OutboxRow> rows = jdbc.query(
  """SELECT * FROM outbox WHERE published_at IS NULL
     ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED""", mapper);
for (OutboxRow row : rows) {
  try {
    producer.send(row.topic(), row.eventId().toString(), row.payload())
      .get(5, TimeUnit.SECONDS); // broker ack before we mark sent
    jdbc.update("UPDATE outbox SET published_at = now(), attempts = attempts + 1 WHERE event_id = ?",
      row.eventId());
  } catch (Exception e) {
    jdbc.update("UPDATE outbox SET attempts = attempts + 1, last_error = ? WHERE event_id = ?",
      truncate(e.getMessage(), 500), row.eventId());
    log.error("outbox_publish_failed", kv("event_id", row.eventId()), e);
  }
}

SKIP LOCKED lets multiple relay instances run without double-claiming a row. Waiting for the broker ack matters: marking published_at before the ack recreates the original bug inside the relay.

Consumer side: at-least-once, made safe

Delivery from Kafka or SQS is at-least-once. The consumer must assume duplicates and order is not guaranteed across partitions. It inserts event_id into an inbox table in the same transaction as the send record. If the insert hits a primary key conflict, the event was already handled and the consumer acks without sending again. Retryable failures (email provider returns 429 or 503) go back to the queue with exponential backoff, for example 30 seconds, 2 minutes, 10 minutes, 30 minutes. After 5 attempts the message moves to a dead-letter queue with the payload, error, and attempt count preserved. A human or an automated replay tool can inspect and re-drive it. Poison messages that fail parsing land in the DLQ on the first attempt, since retrying them will never succeed.

Worked trace

TimeEventState after step
10:00:00User signs document D-1042Transaction commits: signature row plus outbox row e_91
10:00:00Process crashes before relay runsOutbox row still unpublished, nothing lost
10:00:04Relay restarts, claims e_91Publishes to queue, broker acks, sets published_at
10:00:05Consumer receives e_91, inserts into inboxSends email, acks queue message
10:00:06Queue redelivers e_91 after a timeoutInbox conflict, consumer acks, no second email
10:00:07Reconciliation job runsCounts match: 1 signature event, 1 notification

Detection, because retries alone are not enough

Three signals catch what the code misses. First, outbox lag: alert if unpublished rows older than 60 seconds exceed a small threshold, which points at a stuck relay or a down broker. Second, DLQ depth: any message in the DLQ pages the owning team, since it represents a notification that will never send without intervention. Third, the reconciliation query, run every 5 minutes: count signature_events with event_type = SIGNATURE_COMPLETED in the last hour against distinct event_id values in the inbox for the same window. A mismatch creates an incident with the missing IDs attached, rather than waiting for a customer to complain.

Logging changes too. Every log line in this path carries event_id, document_id, and attempt. Exceptions are logged with the stack trace and never caught-and-ignored. That turns "silently dropped" into a queryable failure: filter logs by event_id and you see publish attempts, consumer handling, and the final outcome.

Trade-offs I would name in the loop

The outbox adds a table, a relay process, and a small delay, typically under a second at low volume and a few seconds under load. In exchange, the notification path survives crashes at any point. I would not use exactly-once transactions across the database and the broker, since Kafka transactions and database transactions do not share an atomic commit in most Atlassian stacks, and the inbox pattern gives the same user-visible result with simpler operations. If notification volume grew past what a polling relay handles comfortably, I would switch the relay to change-data-capture from the database log, keeping the same outbox table and consumer contract. The design stays the same; only the mechanism that reads the outbox changes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14Given an organization hierarchy with users and groups, design thread-safe add and remove operations?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

Assume a tree of groups under an org, users at the leaves, and groups can contain users and other groups. Membership is transitive: if Alice is in Engineering and Engineering is in All Staff, Alice is effectively in All Staff. The operations are addUser(user, group), removeUser(user, group), addGroup(child, parent), and removeGroup(child, parent). Thread safety has to hold across multiple app servers, so the database is the source of truth and in-memory locks alone are not enough.

I would make every operation idempotent and enforce the invariants in the database, then use ordered row locks in the transaction to serialize writers on the affected subtree.

Java
// Java 17, Spring Data / JDBC style. One transaction per operation.
@Transactional
public void addUserToGroup(UUID userId, UUID groupId) {
    // Lock the group row first. This serializes writers for this group.
    Group group = groupRepo.findByIdForUpdate(groupId)
        .orElseThrow(() -> new NotFoundException("group", groupId));
    userRepo.findByIdForUpdate(userId)
        .orElseThrow(() -> new NotFoundException("user", userId));

    // Unique constraint on (user_id, group_id) makes a retry a no-op.
    membershipRepo.insertIgnore(userId, groupId);
    cache.invalidateGroup(groupId); // after commit, via TransactionSynchronization
}

For nested groups the cycle check is the hard part. Adding child under parent must reject the change if parent is already a descendant of child. That check and the insert have to run under the same locks, otherwise two concurrent adds can create a cycle: thread A adds X under Y while thread B adds Y under X, and each check passes before either insert commits.

Java
@Transactional
public void addGroupToGroup(UUID childId, UUID parentId) {
    if (childId.equals(parentId)) throw new ValidationException("cycle");
    // Lock in a fixed global order (by UUID) to prevent deadlock.
    List<UUID> ids = Stream.of(childId, parentId).sorted().toList();
    groupRepo.findAllForUpdate(ids);

    if (hierarchyRepo.isDescendant(parentId, childId)) {
        throw new ValidationException("cycle"); // parent is inside child
    }
    hierarchyRepo.insertIgnore(childId, parentId);
}

Why ordered locking matters

Without a fixed order, deadlock is routine. Trace with two concurrent requests:

TimeThread 1: add A under BThread 2: add B under A
t1locks row Alocks row B
t2tries to lock row B, blockstries to lock row A, blocks
t3deadlock detector kills one, client retriessame

Sorting the ids before locking removes that cycle. The loser of a race on the same group simply waits on SELECT ... FOR UPDATE, then sees the winner's committed row. With a hypothetical 5 ms lock hold and 200 writes/sec against one popular group, the queue grows to roughly 1 s of wait at p99, which is the signal to shard writes or move membership writes to a queue. That figure is illustrative, not a benchmark.

Failure modes and how I would detect them

FailureCauseDetection and response
Deadlock under loadLocks taken in request orderCount deadlock_detected in Postgres logs, alert above 0.1% of transactions, retry once with jitter
Cycle slips throughCheck outside transaction, or read committed snapshotNightly job walks the hierarchy and asserts acyclicity, page on any cycle found
Stale effective permissionsCache invalidated before commit, or a replica laggingInvalidate on commit only, version each group, and have permission checks fall back to the primary when the version is unknown
Duplicate membership on retryClient retries after a timeoutUnique constraint on the membership pair, INSERT ... ON CONFLICT DO NOTHING, return success

Alternatives I would mention

A single global ReentrantReadWriteLock per JVM is simpler and fine for a single instance, but it does nothing across servers and it blocks reads during writes. Optimistic locking with a version column on the group works for removeUser races, but it does not stop the two-thread cycle case, because neither thread modifies the same row version. That is why I keep the cycle check under FOR UPDATE locks and treat the unique constraints as the final arbiter. For very high write volume I would move membership changes through a per-group queue so each group has one writer, and keep the same database constraints underneath.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15Implement an LRU cache?

Reported in Atlassian Software Engineer Interview Questions & Rounds

The 90-second answer

I would build it from a hash map plus a doubly linked list. The map gives O(1) lookup by key. The list keeps entries ordered by recency, with the most recently used entry at the head and the least recently used at the tail. A get or a put moves that entry to the head. When a put would exceed capacity, I evict the tail.

That split is the whole design. The map alone cannot tell me which entry is oldest without scanning every key. The list alone cannot find an entry by key without scanning. Together they give O(1) get and put, with O(capacity) memory.

Java
// Checked against Java 17
import java.util.HashMap;
import java.util.Map;

class LRUCache<K, V> {
    private static class Node<K, V> {
        K key;
        V value;
        Node<K, V> prev, next;
        Node(K key, V value) { this.key = key; this.value = value; }
    }

    private final int capacity;
    private final Map<K, Node<K, V>> map = new HashMap<>();
    // Sentinel head/tail remove null checks on insert and delete.
    private final Node<K, V> head = new Node<>(null, null);
    private final Node<K, V> tail = new Node<>(null, null);

    LRUCache(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException("capacity must be positive");
        this.capacity = capacity;
        head.next = tail;
        tail.prev = head;
    }

    public V get(K key) {
        Node<K, V> node = map.get(key);
        if (node == null) return null;
        moveToHead(node);
        return node.value;
    }

    public void put(K key, V value) {
        Node<K, V> node = map.get(key);
        if (node != null) {
            node.value = value;
            moveToHead(node);
            return;
        }
        node = new Node<>(key, value);
        map.put(key, node);
        addToHead(node);
        if (map.size() > capacity) {
            Node<K, V> lru = tail.prev;
            remove(lru);
            map.remove(lru.key);
        }
    }

    private void addToHead(Node<K, V> node) {
        node.next = head.next;
        node.prev = head;
        head.next.prev = node;
        head.next = node;
    }

    private void remove(Node<K, V> node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void moveToHead(Node<K, V> node) {
        remove(node);
        addToHead(node);
    }
}

Worked trace, capacity 3

Order below runs most recently used to least recently used.

OperationList after operationEffect
put(A,1), put(B,2), put(C,3)C, B, ACache full
get(A)A, C, BA promoted, B now oldest
put(D,4)D, A, CB evicted from tail
put(C,5)C, D, AExisting key updated in place, no eviction
get(B)C, D, AMiss, returns null, order unchanged

The update path matters. A put for an existing key must refresh recency and replace the value without growing the map. Missing that check is the most common bug in this interview question, because the cache then evicts a live entry on a duplicate put.

Complexity and alternatives

ApproachGetPutProblem
Hash map + doubly linked listO(1)O(1)Pointer bookkeeping, needs locking for concurrent use
Hash map + array listO(1)O(n) on move or evictShifting entries on every access
LinkedHashMap with accessOrder=trueO(1)O(1)Shorter code, but eviction hooks into removeEldestEntry and ordering is harder to inspect or customise

I would mention LinkedHashMap in the interview and then write the explicit version. It shows I know the shortcut and can still explain the mechanism an interviewer is testing.

Failure modes I would raise before being asked

Concurrency. The code above is single threaded. Two threads can interleave get and put and corrupt the list links, or both evict the same tail node. For a shared cache in a service like Jira I would guard get and put with a single ReentrantLock, or use a concurrent structure designed for this, such as Caffeine, rather than hand rolling locks around a hash map and a list. A single lock keeps the map and list consistent, at the cost of serialising hits.

Capacity and memory. Capacity bounds entry count, not bytes. If values vary in size, as issue or page payloads do, 10,000 entries can still exhaust heap. I would state that assumption and, for a production cache, switch the bound to weight in bytes and evict until under the byte limit.

Null and sentinel handling. The sentinel nodes carry null keys, so the map must never store a null key from user input, or eviction could remove a sentinel. I would reject null keys explicitly or document that restriction.

Hash collisions degrade the map toward O(n) per lookup in the worst case, though with a well distributed hash function this stays theoretical. The list operations stay O(1) regardless, which is why the recency order does not depend on hash quality.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-16Merge k sorted lists?

Reported in Atlassian Software Engineer Interview Questions & Rounds

The 90-second answer

Assume k sorted lists, N total elements, ascending order, and I can mutate or rebuild the output. I would push the head of each non-empty list into a min-heap keyed by value, repeatedly pop the minimum, append it to the result, and push that list's next element. Each pop and push costs O(log k), so total time is O(N log k) and extra space is O(k) for the heap plus O(N) for the output. If the lists are linked lists and I must reuse nodes, the same heap works and I relink instead of copying values.

That beats the naive options. Scanning all k heads per output element is O(Nk), which collapses when k is large. Merging pairwise in a divide-and-conquer tree is also O(N log k) and often faster in practice because sequential merges are cache friendly and can be parallelised, but the heap version is simpler to get right live and handles iterators that cannot be re-read.

Python
# Python 3.12, lists are sorted ascending; returns a new list
import heapq
from typing import Iterable

def merge_k_sorted(lists: list[list[int]]) -> list[int]:
    heap: list[tuple[int, int, int]] = []  # (value, list_index, position)
    for i, lst in enumerate(lists):
        if lst:
            heapq.heappush(heap, (lst[0], i, 0))
    out: list[int] = []
    while heap:
        value, i, pos = heapq.heappop(heap)
        out.append(value)
        nxt = pos + 1
        if nxt < len(lists[i]):
            heapq.heappush(heap, (lists[i][nxt], i, nxt))
    return out

The tuple includes list_index as a tie breaker. Without it, equal values compare the next field and, for linked list nodes or custom objects, that comparison can fail or order unpredictably. With the index, duplicates are emitted in list order, which gives a stable result for equal keys.

Worked trace

Input: [1,4,7], [2,5,8], [3,6,9], so k = 3 and N = 9.

StepHeap before pop (values)PopPush backOutput so far
11, 2, 3141
22, 3, 4251, 2
33, 4, 5361, 2, 3
44, 5, 6471, 2, 3, 4
55, 6, 7581, 2, 3, 5
66, 7, 8691, 2, 3, 5, 6
77, 8, 97none1, 2, 3, 5, 6, 7
88, 98none1, 2, 3, 5, 6, 7, 8
999none1, 2, 3, 5, 6, 7, 8, 9

Heap size never exceeds k = 3, and each of the 9 elements is pushed and popped once: 9 * log2(3) is about 14 comparisons, versus 9 * 3 = 27 head scans for the naive approach. The gap widens fast. At k = 1,000 and N = 1,000,000, the heap does roughly 1,000,000 * 10 = 10 million comparisons, the naive scan does 1 billion.

Alternatives and when I would switch

ApproachTimeExtra spaceWhen it wins
Min-heap over headsO(N log k)O(k)Default. Works on streams and iterators, one pass.
Pairwise divide and conquerO(N log k)O(N) per merge levelLists are in memory arrays and k is huge. Better locality, easy to parallelise across pairs.
Balanced BST of headsO(N log k)O(k)Rarely. Same bound as the heap with worse constants and more code. Only if I need order statistics or deletions from the middle, which merging does not.
Concatenate and sortO(N log N)O(N)k is tiny (2 or 3) and N is small. Simplicity beats asymptotics, but I would not offer it as the main answer.

Failure modes I would name before being asked

Empty lists and None entries: skip them at seeding, as the code does, or the first pop raises. A list that is not actually sorted silently produces a wrong merge, so if the input comes from a service I would validate the invariant at the boundary rather than inside the loop. If k exceeds N, most lists contribute one element and the heap degenerates to a sort of the heads, still correct. If the lists are generators, I must not call len() or index them, so I would switch the heap entries to iterators and pull with next(). For very large N that does not fit in memory, building the output list is the real problem, so I would yield values one at a time and let the caller stream them, for example into a paginated feed merge in a Jira activity stream.

If the interviewer pushes on linked lists specifically, I would keep the heap, store node references instead of values, and relink next pointers, which drops the O(N) output allocation to O(k).

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-17Design a simple snake game where a snake moves in a given direction?

Reported in Atlassian system design interview: the tagging system and code design rounds

The 90-second answer

I would separate three things: game state, the tick loop, and rendering. State is a deque of grid cells for the snake, head first, plus a direction, a food cell, and a score. Every tick, say every 150 ms, I compute the next head as head plus direction, check it against walls, the snake body, and food, then update the deque. Input never mutates the snake directly. It pushes a requested direction into a small queue, and the tick consumes at most one per step. That matters for fast double turns, explained below.

Assumptions I would state up front: fixed grid, for example 20 by 20, one snake, one food at a time, no wrap-around walls, and a single player. If wrap-around or levels were required, only the collision check and food placement change.

Python
# Python 3.11, no dependencies. Grid coordinates are (x, y), origin top-left.
from collections import deque

DIRS = {"up": (0, -1), "down": (0, 1), "left": (-1, 0), "right": (1, 0)}
OPPOSITE = {"up": "down", "down": "up", "left": "right", "right": "left"}

class SnakeGame:
    def __init__(self, width=20, height=20):
        self.width, self.height = width, height
        self.snake = deque([(5, 10), (4, 10), (3, 10)])  # head first
        self.direction = "right"
        self.pending = deque(maxlen=3)
        self.score = 0
        self.alive = True
        self.won = False
        self.food = self._place_food()
        self.won = self.food is None

    def queue_direction(self, name):
        if name in DIRS:
            self.pending.append(name)

    def step(self):
        if not self.alive or self.won:
            return "dead" if not self.alive else "won"
        # Consume one queued turn, ignoring a 180-degree reversal.
        while self.pending:
            nxt = self.pending.popleft()
            if nxt != OPPOSITE[self.direction]:
                self.direction = nxt
                break
        dx, dy = DIRS[self.direction]
        hx, hy = self.snake[0]
        head = (hx + dx, hy + dy)
        if not (0 <= head[0] < self.width and 0 <= head[1] < self.height):
            self.alive = False
            return "wall"
        # Tail cell frees up this tick unless the snake grows.
        eating = head == self.food
        body = self.snake if eating else list(self.snake)[:-1]
        if head in body:
            self.alive = False
            return "self"
        self.snake.appendleft(head)
        if eating:
            self.score += 1
            self.food = self._place_food()
            if self.food is None:
                self.won = True
                return "won"
            return "ate"
        self.snake.pop()
        return "moved"

    def _place_food(self):
        free = [(x, y) for x in range(self.width) for y in range(self.height)
                if (x, y) not in self.snake]
        if not free:
            return None  # board full: win state, not an error
        return free[len(free) // 2]  # deterministic stub; use seeded random in prod

Rendering stays a pure function of snake, food, and score, so the logic is testable without a UI.

Worked trace

Snake starts [(5,10), (4,10), (3,10)], direction right, food at (7,10).

TickQueued inputDirection usedNew headResult
1noneright(6,10)moved, tail (3,10) removed
2noneright(7,10)ate, length 4, score 1, tail kept
3up, then left fastup(7,9)moved, left stays queued
4noneleft(6,9)moved, legal turn from up

Tick 3 is the case interviewers probe. Two key presses arrive inside one 150 ms window. If both were applied before the next step, each would pass a check against the previous direction: left is not opposite up. But no step happened between them, so the net direction is left, which is opposite the actual direction of travel, right. The head would move to (6,10), the neck, and die. Consuming one queued direction per tick forces a step in the up direction first, after which left is a genuine legal turn.

Design choices and failure modes

ChoiceWhyAlternative and when it wins
deque for the bodyappendleft and pop are O(1)A list is fine for length under about 50, but shifting on every tick is O(n) and pointless here
Fixed timestep tickMovement, collision, and input stay deterministic and testableEvent-driven movement on each keypress is simpler for a toy, but speed then depends on the player and self-collision timing gets messy
Bounded input queue, maxlen 3A held key or key repeat cannot flood memory or queue ten turnsAn unbounded queue is acceptable only if you also cap tick rate and drop stale inputs

Three failures I would call out. First, the tail exception: moving into the cell the tail just vacated is legal when not eating, and illegal when eating, because the tail stays. The code above handles that by checking collision against the body minus the tail on a non-eating tick. Second, tick drift: sleep(150) in a loop drifts under load, so a real loop accumulates elapsed time and steps zero or more fixed ticks per frame. Third, food spawning on the snake: picking a random cell without checking occupancy creates an unreachable food cell and a soft lock, so placement must sample from the free set, and an empty free set means the player has filled the board. That is handled explicitly above by returning None and setting won, rather than indexing into an empty list.

For follow-ups: speed-up per food item is just shortening the tick interval, for example max(60, 150 - 5 * score) ms. Persistence is a separate concern, storing score and snake as JSON on game over. Multiplayer or a shared leaderboard would move state server-side and make the tick authoritative, but for this prompt a single-process, UI-agnostic core is the right scope.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18Design a file system that supports getting the size of any directory, extended to report the top n directories?

Reported in Atlassian system design interview: the tagging system and code design rounds

The 90-second answer

Model the filesystem as a tree of nodes. A file node stores its own byte size. A directory node stores the sum of its children, so size(dir) is maintained, not recomputed. On any change to a file, walk from that file up to the root and adjust each ancestor by the delta. A query for any directory is then a single lookup, O(1), and an update costs O(depth) instead of scanning the whole subtree.

For top-n, keep a global min-heap of the n largest directory sizes. Every ancestor touched by an update is a candidate, so push its new size and evict the smallest entry when the heap exceeds n. That gives O(depth log n) per write and O(n log n) to return the sorted list.

Assumptions I would state up front: sizes are known at write time, hard links are out of scope for the first version, and moves are treated as a delete plus a create. I would revisit hard links later because they break the tree into a graph.

Core structure

Python
# Python 3.11, single-process version
class Node:
    def __init__(self, name: str, is_dir: bool, size: int = 0):
        self.name = name
        self.is_dir = is_dir
        self.size = size          # file: own bytes; dir: subtree total
        self.parent: Node | None = None
        self.children: dict[str, Node] = {}

    def add_child(self, child: Node) -> None:
        child.parent = self
        self.children[child.name] = child

def apply_delta(node: Node, delta: int) -> None:
    # Propagate a size change from a file up to the root.
    cur = node.parent
    while cur is not None:
        cur.size += delta
        cur = cur.parent

def write_file(path: list[str], new_size: int, root: Node) -> None:
    node = root
    for part in path:
        node = node.children[part]
    delta = new_size - node.size
    node.size = new_size
    apply_delta(node, delta)

def dir_size(path: list[str], root: Node) -> int:
    node = root
    for part in path:
        node = node.children[part]
    return node.size

Worked trace, with a hypothetical tree where /a/b holds files of 10 and 20 bytes and /a/c holds 5 bytes:

StepOperation/a/b size/a size/ size
1initial state303535
2grow file in /a/b by 7374242
3delete file in /a/c (5 bytes)373737
4dir_size(["a", "b"])373737

Step 4 reads the stored aggregate. No traversal happens at query time.

Top-n maintenance

File write or delete Compute delta Walk ancestors, update sizes Push each ancestor into min-heap Heap over n: pop smallest Query: sort heap, return top n

With depth 6 and n = 10, an update touches 6 ancestors and does 6 heap pushes, roughly 6 x log(10) comparisons. A naive query that scans every directory would visit, say, 200,000 directories for a filesystem with a million files. The maintained aggregate trades a small write cost for fast reads, which fits a workload where size queries are frequent, for example quota checks on Confluence spaces or attachment storage reporting.

Two details matter in the heap. First, entries go stale: a directory pushed at size 100 may later shrink to 40, leaving a dead entry at the top. Store a version or re-check the live size when popping, and discard entries that no longer match. Second, a directory that falls out of the top n can re-enter on a later write, so the heap must receive every ancestor update, not only directories already in the heap.

Failure modes and scale

Moves are the classic bug. Moving a subtree from /a to /b needs a delta of minus subtree size applied to every ancestor of /a and plus subtree size applied to every ancestor of /b, with the lowest common ancestor adjusted once. Doing it as two independent updates double counts at the shared root if the order is wrong. A crash mid-move can leave the tree and the aggregates disagreeing, so in a durable system I would write the move as a single journal entry and replay it on recovery, then run a periodic verifier that recomputes a sample of subtrees from the leaves.

Concurrency needs care. Two writers in the same subtree updating a shared ancestor counter can lose an update with a plain read-modify-write. Options are a lock per directory node, atomic increments on the counter, or sharding writes by top-level directory so contention stays local. I would pick per-node locking first and measure contention before adding complexity.

At scale, a single root counter becomes a hotspot. Shard by top-level directory, keep per-shard aggregates, and compute the global top n by merging shard heaps at query time. That keeps writes parallel and makes the merge cost proportional to the number of shards times n, which is small in practice.

When would I not maintain aggregates? If writes vastly outnumber reads, or sizes change constantly, the O(depth) write cost and heap churn may cost more than an occasional scan. In that case I would answer size queries with a cached scan and a short TTL, and accept stale numbers. The choice hinges on the read to write ratio, so I would ask the interviewer which side dominates before committing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19Implement an in-memory solution for a stream of timestamped commodity prices that supports out-of-order and duplicate timestamps while efficiently retrieving the maximum price?

Reported in Atlassian Software Engineer Interview Questions & Guide 2026

The 90-second answer

I would clarify one thing first: a duplicate timestamp is a correction, so the later price replaces the earlier one for that timestamp. With that rule, I need two structures. A TreeMap<Long, Double> keyed by timestamp stores the current price per timestamp and handles out-of-order arrival naturally, because insertion is by key, not arrival order. A max-heap of (timestamp, price) entries gives me the maximum in amortized O(1). Updates push a new heap entry and overwrite the map. Queries clean stale heap entries from the top until the top matches the map. That keeps update at O(log n) and query at O(1) amortized.

Java
import java.util.*;

public class PriceStream {
    private record Entry(long ts, double price) {}

    private final TreeMap<Long, Double> byTimestamp = new TreeMap<>();
    private final PriorityQueue<Entry> maxHeap =
        new PriorityQueue<>((a, b) -> Double.compare(b.price(), a.price()));

    public synchronized void update(long timestamp, double price) {
        byTimestamp.put(timestamp, price);
        maxHeap.offer(new Entry(timestamp, price));
    }

    public synchronized double maxPrice() {
        while (!maxHeap.isEmpty()) {
            Entry top = maxHeap.peek();
            Double current = byTimestamp.get(top.ts());
            if (current != null && Double.compare(current, top.price()) == 0) {
                return top.price();
            }
            maxHeap.poll(); // stale: superseded by a correction for this timestamp
        }
        throw new NoSuchElementException("no prices recorded");
    }
}

Why lazy deletion works here

The heap never shrinks on update. A correction leaves the old entry in place, and maxPrice() discards it only when it reaches the top. Each entry is pushed once and popped at most once, so total cleanup across all queries is O(n log n) and the amortized cost per query stays O(1) when the top is already valid. Memory grows with the number of updates, not the number of distinct timestamps, which is the main weakness. If the stream runs for days, I would bound it: either expire timestamps older than a window from both structures, or rebuild the heap from byTimestamp when stale entries exceed, say, twice the map size. Rebuild is O(n) and rare.

Worked trace, prices in dollars:

StepCallbyTimestampHeap top after callmaxPrice()
1update(100, 42.0){100: 42.0}(100, 42.0)42.0
2update(90, 55.0){90: 55.0, 100: 42.0}(90, 55.0)55.0
3update(100, 61.0){90: 55.0, 100: 61.0}(100, 61.0)61.0
4update(100, 38.0){90: 55.0, 100: 38.0}(100, 61.0) stale55.0, after popping the stale 61.0
5update(90, 55.0) duplicateunchanged(90, 55.0)55.0

Step 2 shows out-of-order handling: timestamp 90 arrives after 100 and still lands correctly. Step 4 is the case a naive "track the max seen so far" fails, because the correction lowers the price at timestamp 100 below the current maximum at timestamp 90.

OperationCostNotes
updateO(log n)one map put, one heap offer
maxPriceO(1) amortizedpops only stale entries
memoryO(u)u = total updates, including stale heap entries

Follow-ups I would expect

If the interviewer asks for the maximum in a time range, say between t1 and t2, the heap approach no longer works. I would switch to a segment tree or a Fenwick tree for prefix maxima over timestamp-compressed coordinates, giving O(log n) per update and per range query. If prices arrive from multiple threads, the synchronized methods above are the simple correct answer; at higher contention I would shard by timestamp range or use a ReentrantReadWriteLock so queries can run concurrently. If duplicate timestamps should keep the highest price instead of the latest, the only change is in update: store Math.max(existing, price) in the map, and the stale-entry check still works because the heap entry matches the map only when it equals the stored value.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20Describe a situation where you demonstrated one of our company values?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

Pick one value, name it in the first sentence, and tell one story with a decision in it. Do not list values. The example below is a template to adapt with your own real experience, not a story to copy as fact.

"I demonstrated Play as a team on a search indexing change. The trade-off was between shipping a latency fix quickly and not leaving support to handle the fallout during a customer peak."

Situation. In a hypothetical version of this story, a team owns issue search in Jira. Search p95 is 2.4 seconds at peak. A shard rebalance would cut it to about 400 ms, but needs a 40 minute reindex window. The proposed window is Tuesday 09:00 AEST, when large enterprise customers run morning triage and support is already at capacity.

Task and trade-off. My job was to run the migration. The fast option was a standard change ticket on Tuesday morning. That would deliver the latency win two days earlier. The cost was predictable: if search degraded, tickets would arrive faster than support could answer them, and the on-call engineer would be paged during the peak. I chose the slower option, a 01:30 AEST window, and accepted the delay cost. Two days of slow search for everyone, against a concentrated risk of a bad morning for the customers who pay the most and the team who would have to clean it up.

Action. I made the night window safer instead of just moving the risk. I replayed the previous week's production queries in staging to check the new index returned the same results. I wrote the rollback threshold in advance: roll back if p95 stays above 900 ms for 10 minutes after the flag reaches 10 percent. I drafted the status note and the runbook update before the change, and I stayed on the bridge for the first hour even though it was not my on-call week, because I had written the reindex script.

CheckThresholdHypothetical result
Index health sample0 missing documents in 50,000Passed at 01:52
p95 at 10 percent trafficRoll back above 900 ms for 10 min610 ms at 02:10
p95 at 100 percent trafficSame threshold380 ms at 02:35

Result. In this example, p95 fell from 2.4 seconds to 380 ms and support took no search tickets that morning. The point I would close on is the decision, not the metric: playing as a team meant treating the support roster and the customer peak as design constraints, and putting the rollback plan in front of the people who would absorb the failure before I asked for the window.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-21Describe a conflict or disagreement with a peer or lead and how you persuaded them?

Reported in Atlassian Software Engineer Interview Questions & Rounds

The 90-second answer

I disagreed with my tech lead about caching a search endpoint in Jira. He wanted Redis in front of it before a launch. I thought the endpoint had an N+1 query and a missing index, and that a cache would hide the problem while adding invalidation risk. I did not win that argument in the review thread. I won it a week later with a profile, a prototype, and a rollback plan he could approve.

The endpoint listed issues for a project board. At 40,000 issues per project in our test tenant, GET /rest/api/3/search took p99 1,900 ms. The lead's concern was legitimate. Launch traffic would spike, and the database was already at 70% CPU at peak. His proposal was a 60-second Redis cache keyed by query hash.

My concern was correctness. Board filters changed often, and permission checks ran per issue. A stale cache could show an issue a user no longer had access to, or hide one they had just been granted. I had seen that class of bug before, and fixing it would have meant cache invalidation on every permission change.

So I asked for two days to test the alternative. I ran EXPLAIN ANALYZE on the query and found a sequential scan on the issue table plus one query per issue to load labels. I added a composite index on (project_id, status, updated_at) and batched the label load into a single WHERE issue_id IN (...) query.

StepWhat I measuredResult
---------
Baseline, 2,000 requests, 50 concurrentp99 1,900 ms, DB CPU 71%timeouts at 2 s client limit
Index onlyp99 620 ms, DB CPU 48%scan became index scan
Index plus batched labelsp99 210 ms, DB CPU 31%9 queries per request became 2
Lead's cache on top of baselinep99 45 ms on hit, 1,900 ms on misshit rate 61% in replayed traffic

The cache looked faster on average, but 39% of requests still hit the slow path, and p99 across all requests stayed above 1,200 ms once misses were included. The index fix helped every request, including misses.

Disagreement in review Agree on metric: p99 and permission correctness Profile query and replay production traffic Prototype index and batch fix behind flag Share numbers and cache risks in one page Lead decides, ship with dashboard and rollback

I wrote that up in a short doc, linked the query plans, and proposed shipping the index first with the cache code behind a flag if p99 stayed above 400 ms after launch. He approved it. We shipped the index and batch fix, p99 in production settled at 240 ms, and we never turned the cache on.

What I took from it: I started by arguing about architecture, which made it a preference contest. Once I reframed it around a shared metric and a test he could check himself, he could change his mind without losing face. I also kept his launch deadline as a hard constraint and gave him an escape hatch, which made the experiment low risk for him to accept.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-22Tell me about a time you failed to meet expectations and what you changed afterward?

Reported in Atlassian Software Engineer Interview Process · TrueInterview

The 90-second answer

I missed a launch date I had committed to, and the miss was mine, not the team's. I was the engineer owning real-time presence for a Confluence-like editor. I told my manager we could ship in six weeks. We shipped in nine. The feature worked, but I had estimated the happy path and left out the load test, the reconnect storm, and the accessibility pass. After that I changed how I commit: I break a date into dated milestones, I flag the riskiest unknown in week one, and I do not give a single date until the load test passes in CI.

What happened

Presence meant showing avatars and cursor positions for up to 50 editors in a page, updating every two seconds. My plan was a WebSocket fan-out through our existing pub/sub layer. I prototyped it in four days and it looked done. I reported green status for three weeks based on that prototype.

The prototype ran against one editor and one server. Production had reconnects. When a laptop slept and woke, the client reconnected and re-subscribed, and 200 clients reconnecting at once pushed p95 presence update latency from 180 ms to 2.4 s. I found that in week five, during a load test I should have run in week two. The fix took two weeks: batch updates per page, cap subscriptions per connection, and add a fallback to polling every 15 seconds when the socket dropped.

WeekWhat I reportedWhat was true
1Prototype works, on track for week 6Prototype tested with 1 client
3Fan-out doneNo reconnect or load test yet
5Load test shows latency problemp95 2.4 s at 200 reconnecting clients
6Original ship dateFix in progress, date missed
9Shippedp95 210 ms at 500 clients, fallback in place

I owned the miss in the team update the day I found the latency, not at the original date. I told my manager the six-week date was no longer credible, gave the nine-week estimate with the two-week fix itemised, and moved the launch comms myself. No one else had to discover the slip from a dashboard.

What I changed afterward

First, estimates now name the unknown. I write the riskiest assumption at the top of the design doc and schedule a test for it in the first sprint. For presence that would have been: "200 clients reconnecting within 10 seconds keeps p95 under 500 ms." If that test fails, the date moves then, not four weeks later.

Second, I added a gate I can run before I quote a date. It is a small load check in CI that fails the build if p95 breaks the budget:

Python
# tools/presence_load_check.py, run in CI before a release date is quoted
import json, sys

result = json.load(open("presence_load_result.json"))
# result: {"clients": 500, "reconnects": 200, "p95_ms": 210}
budget_ms = 500
assert result["p95_ms"] <= budget_ms, f"p95 {result['p95_ms']} ms over {budget_ms} ms budget"
print(f"ok: p95 {result['p95_ms']} ms at {result['clients']} clients")

Third, I stopped reporting status as a single colour. I report three lines: what is done and measured, what is still untested, and the date impact if the untested part fails. That sounds slower in the meeting. It made the week-five surprise impossible, because the untested line would have read "reconnect storm: untested" from week one.

The next project I led used the same rule. We quoted eight weeks, tested the reconnect case in week one, found a smaller problem early, and shipped in week eight. The change was not working harder. It was moving the test that could kill the date to the front of the plan, and telling people the moment that test failed.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-23Tell me about a time you helped a teammate through a challenge?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

A teammate on my squad, Priya, was blocked for two days on a Jira issue search endpoint we owned. It was returning the right results in local tests and timing out in staging, and she had started rewriting the query. I paired with her for an afternoon instead of taking the ticket. We reproduced it with production-sized data, found an N+1 hidden behind pagination, fixed it, and added a regression test she now owns. The endpoint went from p95 2.4 s to 180 ms in staging, and she shipped the fix herself.

What actually happened

Priya had joined the team three months earlier. Her task was to add a filter to GET /rest/api/3/search for our internal tooling. Locally, with 200 issues, it was instant. In staging, with roughly 400,000 issues, it timed out at 30 s. She had already tried adding an index and splitting the query, and she was close to asking for a rewrite.

I asked what she had ruled out, not what she wanted to try next. That took ten minutes and saved us repeating work. She had ruled out a missing index on the filter column. She had not checked how many database calls the endpoint made per request.

We added query logging and ran one request with a page size of 50. The trace made the problem obvious:

StepCallsTimeWhat it showed
1140 msSearch query returns 50 issue IDs
2501,900 msOne query per issue to load labels
350380 msOne query per issue to load assignee
Total1012,320 msp95 in staging, matches the timeout reports

The pagination was correct. The loading was not. Each issue was hydrated individually inside the loop, so cost scaled with page size. At page size 200, which one client used, it was over 9 s.

Priya suggested batching. I asked her to write the failing test first, with 50 issues and an assertion on the number of queries, so the fix had a target she could defend in review. She wrote it. Then we changed the loader to fetch labels and assignees for the whole page in two queries.

Java
// Before: called once per issue inside the loop
for (Issue issue : page) {
    issue.setLabels(labelDao.findByIssue(issue.getId()));
    issue.setAssignee(userDao.findById(issue.getAssigneeId()));
}

// After: two batched calls for the page, then map in memory
List<Long> ids = page.stream().map(Issue::getId).toList();
Map<Long, List<String>> labelsByIssue = labelDao.findByIssueIds(ids);
Map<Long, User> usersById = userDao.findByIds(assigneeIds(page));
page.forEach(issue -> {
    issue.setLabels(labelsByIssue.getOrDefault(issue.getId(), List.of()));
    issue.setAssignee(usersById.get(issue.getAssigneeId()));
});

I stayed for the review but did not comment as the author. She explained the trace, the query count test, and why she had not rewritten the search. The reviewer asked about memory at large page sizes, and she answered with the numbers: two maps holding 200 entries, not 200 queries.

What I did not do

I did not take the ticket over. That would have unblocked the endpoint and left her blocked on the next performance issue. I also did not just tell her the answer in a chat message. The challenge was not only the N+1. She had lost confidence after two failed attempts and was defaulting to a rewrite because that felt safer than debugging. Pairing in person, with her driving the keyboard, kept the fix hers.

Follow-through

We added the query count assertion to the endpoint test suite, and Priya added the same check to a second endpoint she found with the same pattern. In the retro she said the useful part was the first ten minutes, ruling out what was already tried. That is the habit I try to pass on: reproduce with realistic data, count the calls, then change code.

If I were doing it again I would involve her earlier, before she had spent a day on the index. The technical fix took an hour. The delay came from her working alone because she did not want to bother anyone. Naming that in the retro mattered more than the code change.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-24You're given access to an unfamiliar codebase in an IDE with an AI coding agent. How would you debug existing issues and implement new features using the agent?

Reported in Atlassian Software Engineer Interview Questions | Screna AI

The 90-second answer

I would treat the agent as a fast reader and a scoped editor, not as the owner of the change. First I orient myself in the repo, reproduce the bug or read the feature spec, then I give the agent one narrow task at a time with the files it may touch and the tests that must pass. I review every diff line by line, run the relevant tests myself, and check the behaviour in the running app. If I cannot explain the final diff without the agent, I have not finished the task.

For an Atlassian codebase, say a Jira issue view or a Confluence page service, that discipline matters because the surface area is large and the conventions are local. The agent will happily invent a helper that looks plausible and breaks a tenant isolation rule three packages away.

How I work in practice

Orientation comes before any prompt. I look at the entry point, the module boundaries, recent commits touching the failing area, and the existing tests. I note how errors are returned, how logging is structured, and which abstractions the team already uses. That takes ten minutes and saves an hour of agent-generated code that fights the codebase.

For a bug, I reproduce it first. I write or find a failing test, or I drive the UI path and capture the request and response. Only then do I ask the agent to help. A useful prompt names the symptom, the reproduction, the suspected area, and the constraint.

Task: find why GET /rest/api/3/issue/{key} returns stale status after a workflow transition.
Scope: read packages/issue-service and its tests. Do not edit files yet.
Output: list the call chain from the REST handler to the status cache, with file and line references, and name the most likely invalidation gap.
Evidence: cite the code that writes the cache and the code that should invalidate it.

That forces the agent to show its working. I check the cited lines myself. If the chain is wrong, I correct the scope instead of letting it patch from a false premise.

For a feature, I split the work into small, reviewable steps: add the domain logic, add the API or UI wiring, add tests. Each step gets its own prompt and its own diff. I keep the agent inside a file list. A prompt that says "implement notifications" invites a sprawling change. A prompt that says "in NotificationService.ts, add markRead(userId, notificationId) following the existing markSeen pattern, and add two unit tests" produces something I can review in minutes.

TypeScript
// Test I would expect the agent to add, and that I would run myself
it('does not mark another user\'s notification as read', async () => {
  const other = await seedNotification({ ownerId: 'user-b' });
  await expect(service.markRead('user-a', other.id))
    .rejects.toMatchObject({ code: 'NOT_FOUND' });
  expect(await store.get(other.id)).toMatchObject({ readAt: null });
});

Verification and failure modes

The agent's summary is not evidence. I run the targeted tests, then the broader suite for the touched package, then a type check and lint. I also check the diff for the failure modes I see most often: hallucinated internal APIs, imports from a package the module does not depend on, tests that assert the mock instead of the behaviour, and changes to files outside the stated scope. I search the diff for TODOs, commented-out code, and weakened assertions.

StepWhat I checkSignal to stop and re-scope
OrientationEntry point, conventions, existing testsAgent cites files that do not exist
ReproductionFailing test or captured requestAgent proposes a fix before a repro exists
Scoped editDiff stays inside the file listUnrelated files change, or a new abstraction appears
VerificationTests, types, lint, manual runTests pass only because an assertion was loosened
ReviewI can explain each hunkI need the agent to explain my own change
No Yes Orient: entry point, tests, conventions Reproduce bug or read spec Scoped agent task with file list Review diff line by line Run targeted tests, types, lint Run app and check behaviour Explains the diff? Ship with tests and notes

Two more habits help in a live loop. I keep the agent away from secrets, customer data, and anything that needs a product decision. If the spec is ambiguous, I ask the interviewer rather than letting the agent guess. And I narrate my checks out loud, because the loop is assessing judgement, not typing speed. The agent makes me faster at reading and drafting. The decision about what ships stays mine.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25Find the lowest common ancestor of two employees, then of any set, in an org chart where groups contain people and other groups?

Reported in Atlassian Software Engineer Interview Process · TrueInterview

The 90-second answer

I would first pin down the shape of the chart, because the algorithm changes with it. If every person and group has exactly one parent, it is a tree rooted at the company, and lowest common ancestor is the deepest node that is an ancestor of both. If a person can sit in two groups, or a group can report to two parents, it is a DAG, and there may be several lowest common ancestors. I would state that assumption, solve the tree case, then show how the DAG case differs.

For a tree, I do not walk both nodes to the root on every query if queries are frequent. I preprocess parent pointers and depth once, then answer each query by lifting the deeper node up, then lifting both together.

Python
# Python 3.11, tree case: parent[node] is its immediate parent, root maps to None
import math

class LCA:
    def __init__(self, parent: dict[str, str | None]):
        self.parent = parent
        self.depth: dict[str, int] = {}
        for node in parent:
            d, cur = 0, node
            while parent[cur] is not None:
                cur = parent[cur]
                d += 1
            self.depth[node] = d
        self.LOG = max(1, math.ceil(math.log2(len(parent) + 1)))
        self.up = [dict(parent)]
        for _ in range(1, self.LOG):
            prev = self.up[-1]
            self.up.append({n: prev[prev[n]] if prev[n] is not None else None for n in parent})

    def lift(self, node: str, steps: int) -> str | None:
        bit = 0
        while steps:
            if steps & 1:
                node = self.up[bit][node]
                if node is None:
                    return None
            steps >>= 1
            bit += 1
        return node

    def of_two(self, a: str, b: str) -> str | None:
        if self.depth[a] < self.depth[b]:
            a, b = b, a
        a = self.lift(a, self.depth[a] - self.depth[b])
        if a == b:
            return a
        for k in range(self.LOG - 1, -1, -1):
            if self.up[k][a] != self.up[k][b]:
                a, b = self.up[k][a], self.up[k][b]
        return self.parent[a]

    def of_set(self, nodes: list[str]) -> str | None:
        result = nodes[0]
        for node in nodes[1:]:
            result = self.of_two(result, node)
            if result is None:
                return None
        return result

Folding pairwise works for a tree because LCA is associative there: the deepest node covering the whole set must cover the first two, then cover that result and the next node, and so on. Preprocessing is O(n log n) time and memory, each query is O(log n), and the simple ancestor-set version is O(depth) per query, which is fine for a one-off question and worse for a service answering thousands of queries.

Worked trace

Chart: Company contains Eng and Sales. Eng contains Backend and Frontend. Alice is in Backend, Bob is in Frontend, Carol is in Backend.

QueryStepsAnswer
Alice, BobLift Alice from depth 3 to depth 3, then lift both together to EngEng
Alice, CarolLift both together to BackendBackend
Alice, Bob, CarolLCA(Alice, Bob) = Eng, then LCA(Eng, Carol) = EngEng
Alice, AliceEqual after depth liftAlice
Company Eng Sales Backend Frontend Alice Carol Bob

If the chart is a DAG

The fold above can return a wrong or arbitrary node, because a pair can have two incomparable lowest common ancestors. Example: Alice is in Backend and Platform, Bob is in Frontend and Platform, and Backend and Frontend both sit under Eng while Platform sits under Eng too. The common ancestors are Platform and Eng, and Platform is lower, so the answer is Platform. If Alice is in Backend and Bob is in Frontend with no shared group below Eng, the answer is Eng. If Alice and Bob share two groups at the same depth with no path between them, there is no single lowest node. I would return the set of maximal common ancestors, computed by intersecting ancestor sets and discarding any ancestor that is itself an ancestor of another common ancestor. That is O(size of ancestor sets) per query, so I would only use it when the data model actually allows multiple parents, and I would say so in the API contract.

Failure modes I would name

A cycle in the parent pointers, from a bad import or a concurrent move, makes depth computation loop forever. I would detect it during preprocessing with a visited set and reject the chart. A node missing from the map, or two disconnected roots, means there is no common ancestor, and the API should return null rather than raising. Concurrent moves during a query can make parent and depth disagree, so for a live service I would snapshot the parent map per query or version it, and rebuild the binary lifting table on each committed move. For a static org chart exported nightly, rebuilding on load is simpler and cheaper than incremental updates.

Curated: · Written: · Reviewed:

Difficulty: Hard

Curated: · Written: · Reviewed: