TechSchool
Home / Interview questions / AI engineering / Anthropic

Anthropic AI Engineer Interview Questions

Short answers to 37 AI engineering questions asked at Anthropic.

Questions and answers (37)

Answers are written in plain English and reviewed for technical accuracy. Each answer states the point first, then the reason.

1. Build core business logic for a toy banking application: a spec that grows in four progressive levels against a black-box evaluator.

Treat the spec as four separate milestones and keep each level behind a small interface. The evaluator only sees behavior, so you can refactor internals at each level. Add one level at a time and keep the old tests green. A common split is: accounts, transfers, fees, then limits.

2. Build an in-memory database: SET/GET/DELETE first, then filtered scans, then TTL with timestamps, then file compaction.

Start with a dict that maps keys to values and add one feature per level. For TTL, store an expiry timestamp with each value and check it on read. For compaction, write live keys to a new file and swap it in. Keep the scan filter as a predicate function so it composes.

store[key] = (value, expire_at)
if expire_at is not None and now() > expire_at:
    del store[key]
    return None

3. Create a task scheduler.

Use a min-heap ordered by run time and a worker loop that sleeps until the next task. A heap gives O(log n) insert and O(log n) pop. Guard the heap with a lock when more than one thread adds tasks. For cron-like rules, compute the next run time after each execution.

import heapq
heapq.heappush(heap, (run_at, task_id, task))
run_at, _, task = heapq.heappop(heap)

4. Build an OOP system for managing courses, grades and students.

Model Student, Course, and Grade as separate classes and link them by ID, not by nested objects. A Grade holds a student ID, a course ID, and a score. Put GPA math in one service class so the data classes stay small. This avoids deep copy bugs when a student takes many courses.

5. Given a helper method that crawls a URL, write a crawler over a domain: first synchronous, then make it async.

First write a synchronous crawler with a visited set and a queue of URLs on the same domain. Then move the fetch call into an async function and run many fetches with a bounded semaphore. Keep the parsing and the visited set in one place to avoid duplicate work. A limit of 10 to 20 concurrent fetches is a safe start.

async def crawl(url, seen, sem):
    async with sem:
        html = await fetch(url)
    for link in parse(html):
        if same_domain(link) and link not in seen:
            seen.add(link)
            await crawl(link, seen, sem)

6. Convert nested stack traces into discrete start and end events.

Walk the nested trace from the innermost frame outward and emit one start event and one end event per frame. Reverse the order so start events come before end events in time. Use the frame name and a unique span ID as the event keys. This gives a flat stream that a UI can render as a tree.

for frame in reversed(trace):
    emit("start", frame.name, frame.span_id)
for frame in trace:
    emit("end", frame.name, frame.span_id)

7. Build a rate limiter. Every ten minutes I add a requirement: per-tenant limits, burst allowances, then a sliding window. How do you keep the code from collapsing?

Keep the limit check behind one interface and add each new rule as a separate policy object. The core code calls a chain of policies and takes the strictest result. Per-tenant limits become a key prefix, and burst becomes a token bucket. A sliding window replaces the counter without touching callers.

class Policy:
    def allow(self, key, now): ...
class Chain(Policy):
    def allow(self, key, now):
        return all(p.allow(key, now) for p in self.policies)

8. You need to run an LLM call over 50,000 documents. The API allows ~100 concurrent requests and occasionally returns 429s and timeouts. Write the Python.

Use asyncio with a semaphore of 100 and retry on 429 and timeout with exponential backoff and jitter. Write each result to disk as it arrives so a crash does not lose work. Cap retries at about 5 and log the document ID on final failure. This keeps memory flat over 50,000 documents.

sem = asyncio.Semaphore(100)
async def run(doc):
    async with sem:
        for attempt in range(5):
            try:
                return await call_llm(doc)
            except (RateLimit, Timeout):
                await asyncio.sleep(2 ** attempt + random.random())

9. How would you parallelise this task? (Concurrency and data mutation come up repeatedly across rounds.)

Use a worker pool with a bounded queue. Each worker takes one task and writes results to its own buffer. Merge the buffers in one thread at the end. This design avoids locks on shared state and keeps memory use flat.

from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=8) as pool:
    results = list(pool.map(run_task, tasks))
merged = merge(results)  # single-threaded merge

10. SQL: write a query to find the top five pairs of products most frequently purchased together.

Self-join the order lines on order id and keep pairs where the first product id is smaller. Group by the pair and count the orders. Sort the count in descending order and keep five rows.

SELECT a.product_id AS p1, b.product_id AS p2, COUNT(*) AS n
FROM order_lines a
JOIN order_lines b ON a.order_id = b.order_id AND a.product_id < b.product_id
GROUP BY a.product_id, b.product_id
ORDER BY n DESC
LIMIT 5;

11. SQL: determine whether any user has overlapping subscription date ranges.

Self-join the subscriptions table on user id and test for a date overlap. A row pair overlaps when the start of one row is before the end of the other. Return one row if any pair matches.

SELECT DISTINCT s1.user_id
FROM subs s1
JOIN subs s2 ON s1.user_id = s2.user_id AND s1.id < s2.id
WHERE s1.start_date < s2.end_date AND s2.start_date < s1.end_date;

12. SQL: return each employee's current salary after an ETL error inserted a new salary row every year.

Use a window function to rank salary rows per employee by date. Keep only the row with rank one. The ETL error adds one row per year, so the latest date holds the current salary.

SELECT employee_id, salary
FROM (
  SELECT employee_id, salary,
         ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY effective_date DESC) AS rn
  FROM salaries
) t
WHERE rn = 1;

13. What are the key components of a Transformer model and why does each matter?

A Transformer has token embedding, positional encoding, multi-head attention, a feed-forward block, and layer normalization. Attention mixes information across tokens. The feed-forward block adds per-token compute. Normalization keeps activations stable during training.

14. Explain attention-free transformer architectures and their trade-offs.

Attention-free models replace softmax attention with a fixed mixing rule. Examples are state space models and linear recurrent layers. They scale linearly in sequence length and save KV cache memory. The tradeoff is weaker exact recall of distant tokens.

15. Walk me through matrix manipulations relevant to LLM architectures.

Linear layers are matrix multiplies of shape (tokens, d) times (d, d). Attention forms Q, K, and V matrices, then computes softmax(QK^T / sqrt(d)) V. The cost is about 2 * tokens^2 * d FLOPs per head. KV cache stores K and V to avoid recompute at decode time.

Q = X @ Wq  # (T, d)
K = X @ Wk
V = X @ Wv
S = Q @ K.T / (d ** 0.5)
O = softmax(S) @ V

16. Design a batched inference system where 100 requests take the same time as 1.

Use continuous batching with paged attention and a shared KV cache pool. The scheduler adds new requests at each decode step and drops finished ones. A 100-request batch then costs about the same wall time as one long batch. The tradeoff is more complex memory management and a larger tokenizer-side queue.

while queue or running:
    admit(queue, running, free_blocks)
    logits = model.decode(running, kv_cache)
    emit_tokens(running, logits)
    free_blocks += release(running)

17. Design the serving stack for a Claude-scale LLM API. Maximise GPU utilisation without wrecking p99 latency.

Use a disaggregated stack with a router, a prefill pool, a decode pool, and a paged attention KV cache. The router batches requests by token count and sends long prompts to the prefill pool. The decode pool runs continuous batching with a small batch size cap to protect p99 latency. Keep the KV cache paged so memory waste stays low and more sequences fit per GPU.

18. What matters more for an agentic coding tool like Claude Code: the model or the harness? Design the loop.

The harness matters more than the model for most agentic coding tasks. The model sets the ceiling, but the harness decides how often the model reaches it. Design the loop as: read the task, plan, call a tool, observe the result, update the plan, and stop on a clear finish signal. Add a step budget and a context compaction step to bound cost and latency.

19. Design the tool surface for a coding agent: which tools exist, what their schemas look like, and how results come back.

Expose a small set of tools: read file, write file, run shell command, search code, and list directory. Each schema uses a flat JSON object with required string fields and short descriptions. Results come back as plain text with an exit code and a byte limit. Truncate long output and tell the model how many bytes you dropped.

{"name":"read_file","input":{"path":"string"}}
{"name":"run_shell","input":{"cmd":"string"}}
result = {"ok": true, "out": "...", "truncated": 0}

20. Explain Constitutional AI. What does it buy you over vanilla RLHF, and what doesn't it solve?

Constitutional AI trains a model to critique and revise its own outputs against a written set of principles, then uses those revisions for preference learning. It buys you less human labeling and a clear, auditable rule set. It does not solve reward hacking, distribution shift, or principles that are vague or in conflict. It also does not remove the need for red teaming.

21. How do scaling laws influence the safety evaluation of large models?

Scaling laws let you predict loss from model size, data, and compute, so you can plan safety tests before you train. Larger models can show new capabilities at scale, so evaluation must cover many sizes and not just the final model. A common rule is to test at several points on the compute curve and extrapolate risk. Scaling laws predict loss, not behavior, so they cannot replace direct safety tests.

22. Design the Claude chat service.

Build the chat service as a stateless API in front of a stateful store. The API validates the request, loads the thread, calls the model gateway, and streams tokens back. Store messages and the KV cache key in a low latency database. Use a queue for long jobs and return a job id to the client.

23. Design a system that enables a large language model to handle multiple questions in a single thread.

Keep one thread record with an ordered message list and a rolling summary. On each new question, send the summary plus the recent turns to the model. Update the summary when the token count passes a fixed limit. This keeps the prompt bounded and preserves earlier context.

24. Design a distributed search system for 1 billion documents at 1 million QPS.

Shard the index by document id and replicate each shard for read throughput. A query goes to a router, then to one replica per shard, and a merger combines the top results. At 1 million QPS you need many replicas and a cache for hot queries. Use a two tier design with a small hot index in memory and a larger cold index on disk.

25. Design APIs for developers to access Anthropic's models securely and efficiently.

Offer one HTTPS API with scoped API keys, per-key rate limits, and request logging. Put a gateway in front of the models to enforce auth, quotas, and input checks. Stream responses to cut latency, and cache repeated prompts to cut cost. Return clear error codes and usage counts so developers can debug and budget.

26. Design a file-sharing / distribution system.

Store files in object storage and serve them through a metadata service plus signed URLs. The client asks the metadata service for a file, and the service returns a short-lived signed URL. Use chunked uploads and a content hash to resume transfers and drop duplicates. Add a CDN for hot files and set the signed URL lifetime to 15 minutes.

27. How would you design an experiment to test for a specific emergent capability or bias in a large language model?

Define the capability as a measurable task, then compare model outputs against a baseline with a fixed test set. Write the test items before you see model outputs to avoid bias in the test design. Run each item many times with a fixed temperature and report the pass rate with a confidence interval. Use a blinded human rater or a checked automatic grader for scoring.

28. Your agent reads inbound email and can send replies and search internal docs. Walk me through the prompt-injection attack surface and your defences.

Treat all email content as untrusted input and never let it change the agent's goals or tool permissions. An attacker can hide instructions in the email body, in HTML comments, or in a linked document. Defend with a fixed system prompt, a tool allowlist, and a check that blocks sends to new domains. Require human approval for any reply or document fetch that the email text requests.

29. What do you see as the most pressing unsolved problem in AI alignment?

The most pressing problem is scalable oversight of models. These models can become more capable than their evaluators. Current reward models and human labels can miss subtle failures. This gap grows with model capability. We need methods that stay reliable when the model can reason about the test itself.

30. How would you balance performance optimisation with model interpretability?

Set interpretability checks as a release gate, not an optional extra. Measure task quality and a named interpretability metric on the same eval set. Accept an optimisation only when both metrics pass their thresholds. This costs some speed, but it keeps the model debuggable in production.

31. How would you approach designing a system to ensure the safe deployment of AI models in production?

Use staged rollout with offline evals, a canary, and automatic rollback on metric drift. Log inputs and outputs, and run a classifier on traffic for unsafe or off-policy behaviour. Gate each stage on fixed thresholds for quality, latency, and safety. Keep a human on call and a kill switch for the model endpoint.

32. An enterprise customer says “Claude hallucinates too much” in their RAG-based knowledge assistant. You're the applied engineer on the account. What happens in the first 48 hours?

In the first 48 hours I collect failing queries, reproduce them, and split the errors into retrieval misses and generation errors. I check the retrieved chunks for each failure and measure recall at k on a small labelled set. Most RAG hallucinations come from missing context, so I fix retrieval before I touch the prompt. I then report the error split and a fix plan to the customer.

33. How would you make complex AI research findings accessible to a non-technical audience?

Start with the decision that the audience must make. Explain only what that decision needs. Use one concrete example and one number, such as latency in milliseconds. Do not give a full method description. Keep technical terms exact and define each term once in plain words.

34. Walk me through a project you owned end to end. What were the key technical decisions?

I owned a retrieval system for internal search from design to launch. The key decision was to add a KV cache and paged attention to cut serving cost at long context. That change lowered GPU memory use and let one node serve more users. I also chose a fixed tokenizer to keep offline and online scores comparable.

35. Why Anthropic specifically, and where do you disagree with Anthropic?

I want to work at Anthropic because the safety work sits next to the model work, not after it. I disagree with the default of very long context windows for every task. A smaller context with a good KV cache often gives lower latency and lower cost.

36. Tell me about a technical misjudgement that delayed a project.

I misjudged the cost of a full retrain. It delayed a release by three weeks. I assumed that the data pipeline can reuse old shards. But the new tokenizer changed the token counts. The fix was a LoRA run on the old base model. It recovered most of the gain in two days.

37. What are your thoughts on AI safety and the risks of advanced AI systems?

I think advanced AI systems need strong evaluation and clear limits before wide deployment. The main risks are misuse, loss of human oversight, and errors that scale with model size. I support staged release with red-team tests and published model cards. The tradeoff is slower launches, but a failed audit costs more than a short delay.

Related lessons
Ai agent intro Ai agent function calling Agent architecture Ai rag Retrieval augmented generation Vector database