Anthropic logo

Anthropic Software Engineer Interview Questions

19 practice questions for Anthropic Software Engineer interviews

Anthropic software engineer interviews cover algorithms, data structures, system design, and coding problems drawn from real interview rounds.

Software Engineer Backend Engineer Frontend Engineer Full Stack Engineer Mobile Engineer Data Engineer Data Scientist ML Engineer DevOps Engineer DevOps Engineer Product Manager SRE Security Engineer Engineering Manager Data Analyst UX/UI Designer QA Engineer
9
Coding
1
System Design
coding Hard Verified Question #1

1. OA[CodeSignal] Cloud File Storage System


Category: Graph coding problem

Question Your task is to implement a simple in-memory cloud storage system that maps objects (files) to their metadata (name, size, etc.). You...

Input: Graph (nodes and edges)
Output: Array
Want to practise this one?
Create a free account to open the full question and practise Anthropic questions with AI.
Sign up free
coding Hard Verified Question #2

2. OA[CodeSignal] Design Banking System


Category: Graph coding problem

Question Design a banking system that supports account management, transactions, and various financial operations.

Input: Graph (nodes and edges)
Output: Computed result
coding Medium Verified Question #3

3. Convert Stack Samples To A Trace


Category: Interval-based coding problem

Description Sampling profilers capture the call stack at periodic intervals to analyze program performance. However, most trace visualization tools...

Input: List
Output: Computed result
coding Medium Verified Question #4

4. Find Duplicate Files


Category: String coding problem

Description Given a list of file paths in a directory system, find all duplicate files. Two files are considered duplicates if they have identical...

Input: List
Output: Array
coding Hard Verified Question #5

5. Multi Threaded Web Crawler


Category: Graph coding problem

Description Given a URL startUrl and an interface HtmlParser, implement a concurrent web crawler to discover all unique URLs that share the...

Input: Graph (nodes and edges)
Output: Array
coding Hard Verified Question #6

6. OA[CodeSignal] In-Memory Database


Category: Graph coding problem

Description Implement a simplified in-memory database that supports record manipulation with various operations. The system should handle basic...

Input: Graph (nodes and edges)
Output: Array
coding Medium Verified Question #7

7. Service Log Aggregator


Category: Trie-based coding problem
A distributed system emits log entries from multiple services and worker threads. Each log entry is a colon-separated string in the format...
Input: Array
Output: Computed result
coding Hard Verified Question #8

8. Distributed Statistics Engine


Category: String coding problem
A large dataset of integers is distributed across k workers (indexed 0 to k-1). Each worker holds an unsorted, roughly equal slice of the data....
Input: String
Output: Printed output
coding Medium Verified Question #9

9. Longest Match Tokenizer


Category: Array coding problem
You are given a text string text and a dictionary array where each element is in the format "<key>:<id>". Here key is a token string and id...
Input: Array
Output: Computed result
system design Hard Verified Question #10

10. System Design - Inference API


Category: Queue-based system design problem
You need to design a high-concurrency inference API system. This system must handle many requests happening at the same time. You are given an API...
Input: Number(s)
Output: Computed result
coding Hard graph #1

1. [AI Enabled Coding] Claude Serving Admission Router


Scenario
Anthropic engineers operating Claude need a deterministic admission router that keeps sessions on the same serving worker when possible without exceeding worker capacity. Implement an in-memory simulation for testing these decisions; then extend it with shared organizational quotas that may overlap through a hierarchy. You may use an AI assistant while coding, but you must explain and test its output.
Part 1 — Capacity-aware sticky routing
  • workers and events are lists of maps with string keys and string values. A worker has worker_id, model, and capacity_tokens; model is a logical serving-pool name such as sonnet.

  • A start event has action, request_id, session_id, model, and tokens. Tokens represent a reservation held until a corresponding finish event, not a billing measurement.

  • Initially, every worker has zero reserved tokens and there are no sticky assignments. Process events in input order.

  • A worker is eligible when its model matches and its current reservation plus the requested tokens is at most capacity_tokens. Equality is allowed.

  • Prefer the previously assigned worker for the pair (session_id, model) if it is eligible. Otherwise, choose the eligible worker with the greatest remaining token capacity before admission; break ties by lexicographically smallest worker_id.

  • An accepted start reserves tokens and updates that session/model pair's sticky assignment. Emit {"request_id": ID, "status": "ACCEPTED", "worker_id": WORKER}. A rejected start changes no state and emits {"request_id": ID, "status": "REJECTED", "reasons": ["NO_CAPACITY"]}.

  • A finish event has only action and request_id. If that request is active, release its reservation and emit status RELEASED with its worker ID. Otherwise, emit {"request_id": ID, "status": "NOOP"}. Finishing a request does not clear its sticky assignment.

  • Implement route_requests(workers: list[dict[str, str]], events: list[dict[str, str]]). The return type is up to you; the examples show its required JSON representation as an ordered list of event results.


Example 1:
Input:
{
  "workers": [
    {"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
    {"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
  ],
  "events": [
    {"action": "start", "request_id": "r1", "session_id": "s1", "model": "sonnet", "tokens": "6"},
    {"action": "start", "request_id": "r2", "session_id": "s1", "model": "sonnet", "tokens": "5"},
    {"action": "start", "request_id": "r3", "session_id": "s2", "model": "sonnet", "tokens": "5"},
    {"action": "finish", "request_id": "r1"},
    {"action": "start", "request_id": "r4", "session_id": "s1", "model": "sonnet", "tokens": "3"}
  ]
}

Output:
[
  {"request_id": "r1", "status": "ACCEPTED", "worker_id": "w1"},
  {"request_id": "r2", "status": "ACCEPTED", "worker_id": "w2"},
  {"request_id": "r3", "status": "REJECTED", "reasons": ["NO_CAPACITY"]},
  {"request_id": "r1", "status": "RELEASED", "worker_id": "w1"},
  {"request_id": "r4", "status": "ACCEPTED", "worker_id": "w2"}
]

Explanation: r1 leaves 4 tokens available on w1. Its session's next request needs 5, so r2 falls back to w2, leaving 3 there. Neither worker can admit r3. After r1 finishes, w1 has 10 available, but r4 still chooses sticky worker w2, reaching exactly its capacity of 8.
Part 2 — Overlapping hierarchical admission policies
Other Claude infrastructure teams now need shared reservation limits across projects and organizations. A worker-only admission decision cannot enforce these overlapping budgets.
  • Add quotas, another list of string-to-string maps. Each record has quota_id, limit_tokens, and parents. parents is a comma-separated list of quota IDs, or the empty string. The graph is a directed acyclic graph; a quota can have multiple parents.

  • Every Part 2 start also has quota_ids, a comma-separated list of directly charged quota IDs, possibly empty. Charge each direct quota and every reachable ancestor exactly once per request, even if there are multiple paths or overlapping direct memberships.

  • For each charged quota q, reject if current_usage[q] + tokens > limit_tokens[q]. Its reason is QUOTA:<quota_id>. Equality is allowed.

  • Evaluate worker capacity and all applicable quotas independently against the state before the event. A rejection must report every violated quota and, if applicable, NO_CAPACITY, with the complete reason list sorted lexicographically. Do not stop at the first violation.

  • Admission is atomic: either reserve on the selected worker and every charged quota, updating stickiness, or change nothing. Finishing an active request releases exactly its original worker and quota reservations.

  • Keep all Part 1 routing and finish behavior. The Part 2 JSON result is an object with results, containing the ordered event results, and quota_usage, mapping every configured quota ID to its final integer usage, including zeros.

  • Implement route_requests_with_quotas(workers: list[dict[str, str]], events: list[dict[str, str]], quotas: list[dict[str, str]]). Discuss how the return type changes before implementing it. Structure admission policies so future policy types can be added without rewriting the routing loop; additional quota nodes and parent edges must remain data-driven.


Example 2:
Input:
{
  "workers": [
    {"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
    {"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
  ],
  "quotas": [
    {"quota_id": "org", "limit_tokens": "12", "parents": ""},
    {"quota_id": "team", "limit_tokens": "8", "parents": "org"},
    {"quota_id": "project", "limit_tokens": "7", "parents": "team,org"}
  ],
  "events": [
    {"action": "start", "request_id": "a", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "project,team"},
    {"action": "start", "request_id": "b", "session_id": "s2", "model": "sonnet", "tokens": "3", "quota_ids": "team"},
    {"action": "finish", "request_id": "a"},
    {"action": "start", "request_id": "c", "session_id": "s2", "model": "sonnet", "tokens": "7", "quota_ids": "project"}
  ]
}

Output:
{
  "results": [
    {"request_id": "a", "status": "ACCEPTED", "worker_id": "w1"},
    {"request_id": "b", "status": "REJECTED", "reasons": ["QUOTA:team"]},
    {"request_id": "a", "status": "RELEASED", "worker_id": "w1"},
    {"request_id": "c", "status": "ACCEPTED", "worker_id": "w1"}
  ],
  "quota_usage": {"org": 7, "project": 7, "team": 7}
}

Explanation: a charges project, team, and org once each, giving usages of 6, not 12 or 18. For b, a worker is available, but team usage would be 6 + 3 = 9 > 8; organization usage would be 9 <= 12, and project is not charged. Rejection leaves every usage at 6. Finishing a resets all three to zero; c then reserves 7, satisfying project 7 <= 7, team 7 <= 8, and organization 7 <= 12.
Example 3:
Input:
{
  "workers": [
    {"worker_id": "w1", "model": "sonnet", "capacity_tokens": "10"},
    {"worker_id": "w2", "model": "sonnet", "capacity_tokens": "8"}
  ],
  "quotas": [
    {"quota_id": "org", "limit_tokens": "10", "parents": ""},
    {"quota_id": "team", "limit_tokens": "6", "parents": "org"},
    {"quota_id": "project", "limit_tokens": "6", "parents": "team,org"}
  ],
  "events": [
    {"action": "start", "request_id": "x", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "project"},
    {"action": "start", "request_id": "y", "session_id": "s2", "model": "sonnet", "tokens": "9", "quota_ids": "project"},
    {"action": "finish", "request_id": "y"},
    {"action": "finish", "request_id": "x"},
    {"action": "start", "request_id": "z", "session_id": "s1", "model": "sonnet", "tokens": "6", "quota_ids": "team,project"}
  ]
}

Output:
{
  "results": [
    {"request_id": "x", "status": "ACCEPTED", "worker_id": "w1"},
    {"request_id": "y", "status": "REJECTED", "reasons": ["NO_CAPACITY", "QUOTA:org", "QUOTA:project", "QUOTA:team"]},
    {"request_id": "y", "status": "NOOP"},
    {"request_id": "x", "status": "RELEASED", "worker_id": "w1"},
    {"request_id": "z", "status": "ACCEPTED", "worker_id": "w1"}
  ],
  "quota_usage": {"org": 6, "project": 6, "team": 6}
}

Explanation: After x, workers have 4 and 8 tokens available and every quota has usage 6. Request y needs 9, so neither worker fits; each quota would reach 6 + 9 = 15, exceeding limits 10, 6, and 6. All four reasons must appear, and finishing rejected request y is a no-op. Finishing x releases 6 everywhere. Request z charges each node only once despite overlapping memberships, returning all three usages to exactly 6.
Notes:
  • Assume at most 100,000 events, 2,000 workers, and 500 quota nodes. Token reservations are integers from 1 through 10^9; capacities and quota limits are integers from 0 through 10^12. Explain your complexity rather than assuming worker and quota counts are constants.

  • Inputs are well-formed: worker and quota IDs are unique, every start has a globally unique request ID, referenced quota IDs exist, and quota parents form a DAG. IDs contain no commas or whitespace; finish events may reference any request ID.

  • Each function call starts with empty runtime state. Events are sequential, reservations never expire automatically, and the supplied worker and quota configurations do not change during a call.
Want to practise this one?
Create a free account to open the full question and practise Anthropic questions with AI.
Sign up free
coding Medium concurrency #2

2. [Concurrency] — Build a Concurrent Banking System

Background: At Anthropic, designing reliable systems is crucial, especially when dealing with financial applications where multiple users may perform actions simultaneously. This problem relates to ensuring correctness while allowing concurrent access to user accounts.
Problem statement: You are tasked with creating a simplified banking system that allows for the creation of accounts and performing operations such as deposits, withdrawals, and transfers. All operations should be thread-safe to ensure consistency across multiple concurrent accesses. Use a simple in-memory structure to represent accounts.
Function/class signature:
  • class Bank:

  • def __init__(self) -> None:

  • def create_account(self, account_id: str) -> None:

  • def deposit(self, account_id: str, amount: float) -> None:

  • def withdraw(self, account_id: str, amount: float) -> bool:

  • def transfer(self, from_account: str, to_account: str, amount: float) -> bool:

Example 1:
  • Input:

bank = Bank()
bank.create_account('123')
bank.deposit('123', 200.0)
bank.withdraw('123', 50.0)
  • Output: 150.0 (balance after the operations)

  • Explanation: Account '123' is created with a deposit and a withdrawal is done; the remaining balance reflects the operations.

Example 2:
  • Input:

bank.create_account('123')
bank.create_account('456')
bank.deposit('123', 300.0)
bank.transfer('123', '456', 150.0)
  • Output: (True, 150.0) (Transfer was successful, remaining balance for 123 is 150.0)

Constraints:
  • 1 ≤ account_id.length ≤ 100

  • amount ≥ 0

  • The system should handle at least 1000 concurrent transactions.

  • Assume a maximum of 1000 accounts will be created.
coding Medium concurrency #3

3. Concurrency — Implement a Thread-Safe Banking System

Background: Anthropic is focused on developing safe and aligned AI systems, which includes ensuring that concurrent processes like banking have reliable operations. A banking system requires safe handling of multiple transactions to prevent inconsistencies.
Problem statement: You need to design a basic BankingSystem class that allows for concurrent deposits and withdrawals. The system must ensure thread-safety so that operations do not conflict. Implement the following methods in the class:
  • deposit(accountId: int, amount: float) -> None: Increases the balance of the specified account by the given amount.

  • withdraw(accountId: int, amount: float) -> bool: Decreases the balance by the specified amount if sufficient funds are available; returns True if successful, otherwise False.

  • get_balance(accountId: int) -> float: Returns the current balance of the specified account.

Function/class signature:
  • class BankingSystem:

  • def deposit(accountId: int, amount: float) -> None

  • def withdraw(accountId: int, amount: float) -> bool

  • def get_balance(accountId: int) -> float

Example 1:
Input:
bs = BankingSystem()  
bs.deposit(1, 500.0)  
bs.withdraw(1, 200.0)  
bs.get_balance(1)

Output: 300.0
Explanation: The account with ID 1 initially received a deposit of 500, then 200 was withdrawn, leaving a balance of 300.
Example 2:
Input:
bs.withdraw(1, 400.0)

Output: False
Explanation: Insufficient funds for the withdrawal of 400.
Constraints:
  • 1 ≤ accountId ≤ 10000

  • 0 < amount ≤ 10000

  • The operations may occur in concurrent threads.
coding Hard concurrency #4

4. Concurrency and Fault Tolerance — Implement a fault-tolerant concurrent component

Background: Anthropic is focused on developing reliable AI systems that require concurrent operations to handle high-throughput data streams efficiently. Ensuring that these operations are fault-tolerant is crucial for maintaining system integrity and performance, especially in an AI context.
Problem statement: Implement a concurrent class Counter that counts the number of times a specific event occurs while ensuring thread safety. The increment method should increase the counter when an event happens, and the get method should return the current count. If a failure occurs while incrementing, the system should handle this gracefully without losing the count. Use a lock mechanism to ensure thread safety and implement recovery logic.
Function/class signature:
  • def increment(self) -> None:

  • def get(self) -> int:

Example 1:
Input: Event occurs → increment() called
Output: Count = 1 → Explanation: The counter is increased by one.
Example 2:
Input: Event occurs rapidly 100000 times → get() called
Output: Count = 100000 → Explanation: The counter correctly reflects the total increments of events.
Constraints:
  • Maximum concurrent increments: 10,000

  • Ensure failure handling does not result in lost increments

  • Methods must be executed safely in a multi-threaded environment.
coding Medium hash map #5

5. CODING — Implement a banking system to manage accounts


Background: At Anthropic, managing data integrity and transaction processing efficiently is critical for any banking-related application leveraging AI technologies. This problem simulates a rudimentary banking system.
Problem statement: You need to implement a simple banking system that manages accounts having the following operations: create account, deposit, withdraw, and get total transactions. Additionally, there should be a method to return the n accounts with the most total transactions (both deposits and withdrawals).
Function/class signature:
  • class Bank:

  • def create_account(self, account_id: int) -> None:

  • def deposit(self, account_id: int, amount: float) -> None:

  • def withdraw(self, account_id: int, amount: float) -> bool:

  • def get_total_transactions(self, account_id: int) -> float:

  • def get_top_accounts(self, n: int) -> List[int]:


Example 1:
Input:
bank = Bank()  
bank.create_account(1)  
bank.deposit(1, 100)  
bank.withdraw(1, 50)  
bank.create_account(2)  
bank.deposit(2, 200)  
bank.deposit(2, 80)  
bank.get_top_accounts(1)

Output:
[2]
Explanation: Account 2 has the highest total transactions (280).
Example 2:
Input:
bank.create_account(3)  
bank.deposit(3, 150)  
bank.withdraw(3, 30)  
bank.get_top_accounts(2)

Output:
[2, 3]
Explanation: Account 2 has (280) and account 3 has (120) total transactions.
Constraints:
  • 1 <= account_id <= 10^4

  • 0 <= amount <= 10^6

  • All operations are valid according to the problem constraints.

  • 1 <= n <= 100

  • The number of accounts does not exceed 10^4.

coding Medium array #6

6. Max Consecutive Ones — Count maximum consecutive 1s in binary array


Background: At Anthropic, analyzing streaming binary data is crucial for accurate inference in machine learning models. This problem reflects the need to efficiently process data to gather insights for AI alignment and safety.
Problem statement: Given a binary array nums, return the maximum number of consecutive 1s in the array. For example, in the array [1,1,0,1,1,1], the longest consecutive sequence of 1s is 3. Your function should handle large inputs and provide results quickly, as this operation could be part of a larger data analysis framework.
Function/class signature:
  • def findMaxConsecutiveOnes(nums: List[int]) -> int:


Example 1:
Input: findMaxConsecutiveOnes([1,1,0,1,1,1])
Output: 3
Explanation: The longest sequence of 1s is 111.
Example 2:
Input: findMaxConsecutiveOnes([1,0,1,1,0,1])
Output: 2
Explanation: The longest sequence of 1s is 11.
Constraints:
  • 1 <= nums.length <= 10^5

  • nums[i] is either 0 or 1.


coding Medium concurrency #7

7. Concurrency — Implement a fault-tolerant banking system


Background: Anthropic requires a reliable banking system to manage user accounts and transactions, ensuring data integrity and fault tolerance in high-throughput environments.
Problem statement: Implement a simplified banking system where multiple users can create accounts, make scheduled transfers, and view their account balances concurrently. The system must be fault-tolerant and handle potential race conditions when multiple operations occur simultaneously.
Function/class signature:
  • class BankingSystem:

- def create_account(self, account_id: int) -> None:
- def transfer(self, from_account: int, to_account: int, amount: float, schedule_time: datetime) -> bool:
- def get_balance(self, account_id: int) -> float:
Example 1:
  • Input:

create_account(1)
create_account(2)
transfer(1, 2, 100, datetime(2023, 10, 1, 10, 0))
  • Output: True

  • Explanation: User 1 successfully transfers $100 to user 2.


Example 2:
  • Input:

transfer(1, 2, 50, datetime(2023, 10, 1, 10, 0))
  • Output: False

  • Explanation: The transfer fails because account 1 does not have sufficient funds.


Constraints:
  • Account IDs: 1 to 10^5

  • Transfer amount: 1 to 10^4

  • Number of scheduled transfers: up to 10^4 parallel operations

  • Transfer scheduling: can be set at most 1 week ahead.
system design Hard concurrency #8

8. Design StackTraceReconstructor — reconstruct nested function events from sampled call stacks


Background


Engineers investigating latency in Claude-serving infrastructure need to turn periodic stack samples into timelines that can be inspected by a profiler. Design an in-memory component for that workflow, adapting the stack-trace problem reported in Anthropic interviews. This is a practice design, not a claim about Anthropic's internal profiling implementation.

Requirements


1. Maintain independent state for each thread. A sample contains an integer timestamp and a stack of function names ordered outermost to innermost. The first sample registers the thread; its stack is compared with an empty stack. Subsequent sample timestamps for that thread must be strictly increasing, even when its stack is unchanged or empty. Timestamps across different threads need not be ordered.
2. Reconstruct events using the longest common prefix of the previous and current stacks. Emit end events for the old suffix, innermost first, followed by start events for the new suffix, outermost first. All events use the new sample's timestamp. A frame's depth is its zero-based position in its stack; repeated function names represent distinct recursive frames. Matching prefix frames are assumed to remain active: do not infer unobserved calls between samples.
3. finish(thread_id, timestamp) closes the thread by ending every remaining frame, innermost first. Its timestamp must be at least the thread's latest sample timestamp. Finishing an already finished thread returns false without emitting events or checking the timestamp. Finishing an unknown thread raises ValueError; adding a sample to a finished thread also raises ValueError.
4. Buffer events until drain_events() returns and removes all buffered events. Each event is an object with exactly thread_id, timestamp, kind, function, and depth. Preserve method-call order, not global timestamp order; within a call, preserve the nesting order defined above. A second drain without intervening events returns an empty list. Copy input stacks so later caller mutations cannot change stored state.
5. Make every public operation thread-safe and atomic. Concurrent calls may take effect in any lock-acquisition order, but their events must not interleave. A rejected operation must leave thread state and buffered events unchanged. Keep finished-thread identities so they cannot be reused.

Class API


  • StackTraceReconstructor() — create an empty reconstructor.

  • add_sample(thread_id: str, timestamp: int, stack: list[str]) -> None — register or update a thread and append inferred events; raise ValueError for a finished thread or a non-increasing timestamp.

  • finish(thread_id: str, timestamp: int) -> bool — return true when an active thread is closed, or false if already closed; raise ValueError for an unknown thread or a timestamp earlier than its latest sample.

  • drain_events() -> list[dict[str, str | int]] — atomically return all pending events and clear the buffer.


Example 1


Input sequence:
[
  {"method":"add_sample","args":["worker-1",10,["serve","decode"]]},
  {"method":"add_sample","args":["worker-1",14,["serve","sample"]]},
  {"method":"finish","args":["worker-1",20]},
  {"method":"drain_events","args":[]}
]

Output, one result per call:
[
  null,
  null,
  true,
  [
    {"thread_id":"worker-1","timestamp":10,"kind":"start","function":"serve","depth":0},
    {"thread_id":"worker-1","timestamp":10,"kind":"start","function":"decode","depth":1},
    {"thread_id":"worker-1","timestamp":14,"kind":"end","function":"decode","depth":1},
    {"thread_id":"worker-1","timestamp":14,"kind":"start","function":"sample","depth":1},
    {"thread_id":"worker-1","timestamp":20,"kind":"end","function":"sample","depth":1},
    {"thread_id":"worker-1","timestamp":20,"kind":"end","function":"serve","depth":0}
  ]
]

Explanation: At timestamp 14 the shared prefix is ["serve"], so only decode ends and sample starts. Finishing ends the two remaining frames in reverse depth order.

Example 2


Input sequence:
[
  {"method":"add_sample","args":["A",5,["walk","walk"]]},
  {"method":"add_sample","args":["B",2,[]]},
  {"method":"add_sample","args":["A",6,["walk"]]},
  {"method":"add_sample","args":["B",3,["serve"]]},
  {"method":"finish","args":["A",6]},
  {"method":"finish","args":["A",0]},
  {"method":"drain_events","args":[]},
  {"method":"drain_events","args":[]}
]

Output, one result per call:
[
  null,
  null,
  null,
  null,
  true,
  false,
  [
    {"thread_id":"A","timestamp":5,"kind":"start","function":"walk","depth":0},
    {"thread_id":"A","timestamp":5,"kind":"start","function":"walk","depth":1},
    {"thread_id":"A","timestamp":6,"kind":"end","function":"walk","depth":1},
    {"thread_id":"B","timestamp":3,"kind":"start","function":"serve","depth":0},
    {"thread_id":"A","timestamp":6,"kind":"end","function":"walk","depth":0}
  ],
  []
]

Explanation: Recursive frames are distinguished by depth. Thread B's empty first sample registers it without creating events. Its timestamp-3 event remains after A's timestamp-6 event because calls, rather than timestamps, define buffer order. Repeating finish is a no-op even with an earlier timestamp.

Constraints


  • At most 10,000 distinct thread IDs and 100,000 total sample/finish calls; each stack has at most 1,000 frames.

  • Timestamps are integers in [0, 10^12]; thread IDs and function names are nonempty strings of at most 128 characters. Types and these bounds are guaranteed by callers.

  • At most 1,000,000 events are pending between drains. There are at most 32 concurrent callers, and callers must not mutate an input stack while its call is executing.

  • Use only in-memory state and standard-library facilities; persistence, actual stack sampling, and global timestamp sorting are out of scope.
system design Medium api design #9

9. Design FileStorageSystem — an object-oriented representation of a file storage system


Background: Anthropic requires a scalable file storage system to efficiently manage user files in a way that supports key operations like storing, retrieving, filtering, backing up, and restoring files. This is crucial for data management across various applications.
Requirements:
1. Implement set(file: str, data: bytes) -> None to store a file.
2. Implement get(file: str) -> Optional[bytes] to retrieve file data by name.
3. Implement filter(criteria: Callable[[str], bool]) -> List[str] to return a list of files matching certain conditions.
4. Implement backup(destination: str) -> None to backup all files to a specified location.
5. Implement restore(source: str) -> None to restore files from a backup location.
Class API:
  • set(file: str, data: bytes) -> None: Stores the file file with the content data in bytes.

  • get(file: str) -> Optional[bytes]: Returns the content of the file if it exists, otherwise returns None.

  • filter(criteria: Callable[[str], bool]) -> List[str]: Returns a list of file names that match the given criteria.

  • backup(destination: str) -> None: Backs up the current files to the specified destination.

  • restore(source: str) -> None: Restores files from a backup source.


Example 1:
Input:
  • set('document.txt', b'This is a document.')

  • set('image.png', b'Image data here.')

Output:
  • get('document.txt') returns b'This is a document.'

  • filter(lambda x: x.endswith('.png')) returns ['image.png']

Explanation: The method set is used to store files and get retrieves the content of a specific file. The filter method uses a lambda function to find files with the .png extension.
Example 2:
Input:
  • backup('/backup/location')

  • restore('/backup/location')

Output: No direct output, but files are backed up and restored as needed.
Constraints:
  • Maximum number of files: 1000

  • File name length: up to 255 characters.

  • Data size: up to 1MB per file.


Related Anthropic Software Engineer interview prep

Start practicing Anthropic questions

Sign up for free to access walkthroughs, AI-generated questions, and more.

Get Started Free