Employer interviews
Interviews are private. Sign in to see your group interviews.
Sign in…
This interview was not found. Maybe the data in this browser was cleared.
Interviews dashboardEasy questions are at the top, and harder ones sit under their basic question. If a basic question gets a weak score, the questions under it fade.
1. Clones in the cart lookup
Ownership and borrowing in Rust· in roadmap
Question: In our online shop, this function counts how many of the wanted products are already in the cart. A cart can have a few hundred items, and the function runs on every page view.
#[derive(Clone)]
struct CartItem {
sku: String,
quantity: u32,
}
fn find_item(items: Vec<CartItem>, sku: String) -> Option<CartItem> {
items.into_iter().find(|i| i.sku == sku)
}
fn count_in_cart(cart: &Vec<CartItem>, wanted: &Vec<String>) -> u32 {
let mut total = 0;
for sku in wanted {
if let Some(item) = find_item(cart.clone(), sku.clone()) {
total += item.quantity;
}
}
total
}
It compiles and the tests pass. You see it in code review. What do you think? Is there a problem?
Short answer: The function find_item takes ownership of the whole list and of the text, but it only needs to read them. So the caller must clone the whole cart (every item and every String inside it) once for each wanted product. The fix is to borrow: take a slice of items and a string slice, and return a reference to the found item. Then there is no clone at all.
Hint (if the candidate says there is no problem): The developer says: “At first it did not compile, so I added clone until the compiler was happy.” With 300 items in the cart and 20 wanted products, how many Strings are copied on each page view?
Why is this bad? (step by step)
- Passing a Vec by value is a move. The caller still needs the cart for the next loop round, so it cannot give it away. That is why the compiler complained.
- The clone made the error go away, but at a cost. Each call makes a new Vec and a new heap String for every item. With 300 items and 20 products, that is 6,000 String copies per page view, and they are all thrown away right after.
- The signature lies about what the function does. A function that only reads should borrow. Taking ownership says “I will keep or destroy this value”.
- A reference to a Vec or a String as a parameter is also a small smell. A slice parameter accepts more types: a Vec, an array, or a part of a list. A string slice accepts a String, a literal or a part of a text.
The fix:
fn find_item<'a>(
items: &'a [CartItem],
sku: &str,
) -> Option<&'a CartItem> {
items.iter().find(|i| i.sku == sku)
}
fn count_in_cart(cart: &[CartItem], wanted: &[String]) -> u32 {
wanted
.iter()
.filter_map(|sku| find_item(cart, sku))
.map(|item| item.quantity)
.sum()
}
- The result borrows from the cart. The lifetime ’a says: the found item is valid as long as the cart is valid.
- No heap work happens at all. The function only walks the list and compares text.
- CartItem no longer needs Clone for this code.
- If the lookup is still slow for big carts, the next step is a HashMap from SKU to item, but first remove the needless copies.
Follow-up question: When is a clone the right choice?
Follow-up answer:
- When the new owner must really keep its own copy, for example when we send an item to another thread or store it in a struct that lives longer than the cart.
- When the value is cheap to clone, for example an Arc (a clone only adds one to a counter) or a small Copy type.
- When it makes the code much simpler and the code is not on a hot path. Then the clone is a conscious choice, not a way to silence the compiler.
Red flag: Says “clone is how you fix borrow checker errors”, or does not see any cost in cloning a Vec of Strings.
Show answer
2. A label that never goes away
Ownership and borrowing in Rust· in roadmap
Question: Our order service is a long-running web server. A teammate needed a label for each order in the logs and in the order page. The first version did not compile, so they changed it to this:
struct Order {
id: u64,
customer: String,
}
impl Order {
fn label(&self) -> &'static str {
let text = format!("#{} for {}", self.id, self.customer);
Box::leak(text.into_boxed_str())
}
}
The label method is called for every request. It compiles and works. You see it in code review. What do you think? Is there a problem?
Short answer: The Box::leak function gives up ownership of the heap text on purpose and never frees it. That is how it can return a reference that lives forever. So every call leaks one string. In a server that runs for weeks, memory only grows. The simple fix is to return an owned String, or to implement the Display trait so the label is written straight into the log or the response.
Hint (if the candidate says there is no problem): After the deploy, the memory graph of the order service goes up a little with every request and never comes down. It only drops when the pod restarts.
Why does this happen? (step by step)
- The first version returned a reference to the local String. The String dies at the end of the method, so the compiler refused it. That error was right.
- A static reference must be valid until the program ends. No local value can give that.
- The Box::leak function makes it valid by never freeing the memory. The text stays on the heap, and nobody owns it anymore. Rust calls this a safe leak: it is not undefined behavior, but the memory is lost.
- The method runs on every request. One leaked label per request means memory grows without a limit.
The fix:
use std::fmt;
impl fmt::Display for Order {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "#{} for {}", self.id, self.customer)
}
}
impl Order {
fn label(&self) -> String {
self.to_string() // the caller owns the text
}
}
- Returning a String gives the text to the caller. It is freed when the caller is done with it.
- With Display, a call like println with the order writes the label directly, often with no extra String at all.
- The lesson: when the compiler says a reference does not live long enough, the usual fix is to change who owns the data, not to make the data live forever.
Follow-up question: Is Box::leak ever a good idea?
Follow-up answer:
- Yes, for a value that is made once and must live for the whole program, for example configuration read at startup and shared by all threads as a static reference.
- Even then, a OnceLock (or LazyLock) static is often clearer.
- It is never right for something made per request or per item.
Red flag: Thinks Rust programs cannot leak memory, or adds a static lifetime to make a lifetime error go away without asking where the data lives.
Show answer
3. The order total in the release build
Ownership and borrowing in Rust· in roadmap
Question: This function computes one line of an invoice in our shop. Prices are stored in cents. Business customers can order large amounts, for example a million screws.
fn line_total(price_cents: u32, quantity: u32) -> u32 {
price_cents * quantity
}
All unit tests pass, with small numbers like 2 items for 4,999 cents. The service is built with cargo build in release mode. You see this in code review. What do you think? Is there a problem?
Short answer: The result can be bigger than the largest u32 (about 4.29 billion, so about 42.9 million dollars in cents). In a debug build, Rust panics on integer overflow. In a release build, overflow checks are off by default, so the number silently wraps around and the invoice shows a wrong, small total. The fix is a bigger type (u64) and checked math that returns an error on overflow.
Hint (if the candidate says there is no problem): A business customer orders 1,000,000 items for 5,000 cents each. The invoice says 7,050,327.04 dollars, not 50,000,000 dollars. In tests on the developer’s laptop, the same input crashed with “attempt to multiply with overflow”.
Why does this happen? (step by step)
- 5,000 times 1,000,000 is 5 billion. That does not fit in a u32.
- In debug builds, Rust adds an overflow check to plain arithmetic and panics. That is why the laptop test crashed.
- In release builds, the default profile turns these checks off for speed. The multiplication wraps around modulo 2 to the power of 32, and the result is 705,032,704 cents.
- No error, no log. The wrong number goes into the invoice and maybe to the payment provider.
The fix:
#[derive(Debug)]
struct TotalTooLarge;
fn line_total(
price_cents: u32,
quantity: u32,
) -> Result<u64, TotalTooLarge> {
u64::from(price_cents)
.checked_mul(u64::from(quantity))
.ok_or(TotalTooLarge)
}
- Use u64 for money totals. The product of two u32 values always fits in a u64, but sums of many lines can still grow, so keep checked math for sums too (the checked_add method).
- The checked methods return None on overflow. We turn that into a clear error.
- For money, never use floats. Integer cents (or a decimal type) keep the math exact.
- Optionally, turn checks on in release with the setting overflow-checks equal to true in the release profile of Cargo.toml. It costs a little speed and turns silent bugs into loud panics.
Follow-up question: What other options does Rust give for overflow, and when do you use each?
Follow-up answer:
- The checked methods return an Option. Use them when overflow is an error, like money.
- The saturating methods stop at the max or min value. Good for things like a counter that must not go below zero.
- The wrapping methods wrap on purpose. Good for hashes and checksums.
- The overflowing methods return the result and a flag that says if it wrapped.
Red flag: Says “Rust is safe, so overflow cannot happen”, or does not know that debug and release builds behave differently.
Show answer
4. Unwrap in the queue worker
Traits and error handling in Rust· in roadmap
Question: This worker reads new orders from a queue and saves them. Other teams send messages to this queue. The worker runs as one process in Kubernetes, and Kubernetes restarts it if it stops.
fn parse_order(raw: &str) -> Result<Order, ParseError> {
// reads "id,quantity", returns an error for bad input
todo!()
}
fn run(queue: &Queue, db: &Db) {
loop {
let msg = queue.receive();
let order = parse_order(&msg.body).unwrap();
db.save(&order).unwrap();
queue.ack(&msg);
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: The unwrap method turns every error into a panic, and a panic in the main loop stops the whole worker. One bad message from another team (a “poison message”) is enough. Because the message is never acknowledged, the queue gives it again after the restart, the worker panics again, and no order is processed anymore. Errors that come from outside input must be handled as values: log them, move the bad message to a dead-letter queue, and continue.
Hint (if the candidate says there is no problem): Another team sends one message with the text “42,two” by mistake. After that, the pod restarts again and again (CrashLoopBackOff), and the queue gets longer every minute.
Why does this happen? (step by step)
- parse_order already returns a Result. It tells us that bad input is possible and expected.
- The unwrap call says: “this can never fail, crash if it does”. That is not true for input from other systems.
- The panic unwinds and ends the program, before the ack line runs.
- The queue still has the message. After the restart, the worker reads the same message first and crashes again. One bad message blocks all good ones.
- The same is true for the database save. A short network error should be retried, not crash the worker.
The fix:
fn run(queue: &Queue, db: &Db) {
loop {
let msg = queue.receive();
match handle(&msg, db) {
Ok(()) => queue.ack(&msg),
Err(HandleError::BadInput(e)) => {
log::warn!("bad order {}: {e}", msg.id);
queue.dead_letter(&msg); // keep it for a human
}
Err(HandleError::Db(e)) => {
log::error!("save failed: {e}");
queue.retry_later(&msg);
}
}
}
}
- A small handle function uses the question mark operator and returns our own error type.
- Bad input is not retried. It goes to a dead-letter queue, and we keep working.
- Temporary errors (like the database) are retried later, with a limit.
- Only bugs should panic, for example a broken internal rule that should never happen.
Follow-up question: Then when is unwrap or expect fine?
Follow-up answer:
- In tests and small examples.
- When a failure really means a bug in our own code, and we can explain why it cannot happen. Then expect with a clear message is better than unwrap, for example “the regex is a constant and is valid”.
- At startup, for things the program cannot run without, like a missing required setting. Even there, a clear error message is kinder than a panic.
Red flag: Says “Kubernetes will restart it, so a panic is fine”, or does not see that the same message comes back after the restart.
Show answer
5. Payment errors as text
Traits and error handling in Rust· in roadmap
Question: Our payment module talks to a bank. When the bank times out, we want to try again. When the card is declined, we must not try again.
// payment.rs
pub fn charge(order: &Order) -> Result<TxId, String> {
let resp = bank::send(order).map_err(|e| {
if e.is_timeout() {
format!("bank timed out after {}s", 5)
} else {
format!("bank error: {e}")
}
})?;
if resp.declined {
return Err(format!("card declined: {}", resp.reason));
}
Ok(resp.tx_id)
}
// checkout.rs
match payment::charge(&order) {
Ok(tx) => mark_paid(&order, tx),
Err(e) if e.contains("timeout") => retry_later(&order),
Err(e) => show_error(&e),
}
You see this in code review. What do you think? Is there a problem?
Short answer: The errors are plain Strings, so the caller can only guess the kind of error by searching the text. Here the guess is already wrong: the message says “timed out”, but the check looks for “timeout”. So no timeout is ever retried. Even if the words matched, any change to a message would silently break the retry. A library or module should return an error enum (for example with the thiserror crate), so the caller matches on a variant and the compiler checks it.
Hint (if the candidate says there is no problem): Since the last release, customers see “bank timed out after 5s” on the checkout page, and no payment is retried. Nobody changed the checkout code.
Why is this a problem? (step by step)
- A String error has no structure. The only way to make a decision is to parse human text.
- The text and the check are in two different files. One person changes the wording of the message, and the other file breaks, but it still compiles.
- Here they never matched at all: “timed out” does not contain “timeout”.
- The same problem affects data. If the caller needs the decline reason or the waiting time, it must cut it out of the text.
The fix:
use std::time::Duration;
#[derive(Debug, thiserror::Error)]
pub enum PaymentError {
#[error("bank timed out after {0:?}")]
Timeout(Duration),
#[error("card declined: {reason}")]
Declined { reason: String },
#[error("bank error")]
Bank(#[from] bank::Error),
}
pub fn charge(order: &Order) -> Result<TxId, PaymentError> {
todo!()
}
match payment::charge(&order) {
Ok(tx) => mark_paid(&order, tx),
Err(PaymentError::Timeout(_)) => retry_later(&order),
Err(e) => show_error(&e.to_string()),
}
- Each kind of failure is a variant. The caller decides with a match, not with text search.
- The message is still there for logs and users, made by the error attribute.
- The from attribute wraps the lower error and keeps it as the source, so the full chain can be logged.
- If someone adds a new variant, a match without a catch-all arm stops compiling. The compiler shows every place that must decide.
Follow-up question: Then what is the anyhow crate for?
Follow-up answer:
- The anyhow crate is for applications, at the top level, where we usually only log or show the error and do not branch on its kind.
- It holds any error, adds context, and keeps the source chain.
- A common rule: thiserror (typed errors) in libraries and modules whose callers must decide, and anyhow in the main binary, handlers and scripts.
Red flag: Thinks string matching on error text is fine, or uses one Box of dyn Error everywhere and cannot say how the caller would tell a timeout from a decline.
Show answer
6. A startup error with no clue
Traits and error handling in Rust· in roadmap
Question: Our shop loads its price list at startup. This is the code:
use anyhow::Result;
use std::path::Path;
fn load_prices(path: &Path) -> Result<Vec<Price>> {
let text = std::fs::read_to_string(path)?;
let prices = parse_csv(&text)?;
Ok(prices)
}
fn main() -> Result<()> {
let config = load_config()?;
let prices = load_prices(&config.prices_path)?;
let stock = load_prices(&config.stock_path)?;
start_server(prices, stock)
}
You see this in code review. What do you think? Is there a problem?
Short answer: The question mark operator passes the error up exactly as it is. An io error only says what went wrong, not which file or what we were doing. So the only line in the log is “No such file or directory (os error 2)”, and nobody knows which of the many files is missing. The fix is to add context at each step with the context or with_context method of anyhow.
Hint (if the candidate says there is no problem): After a deploy, the service does not start. The only log line is: “Error: No such file or directory (os error 2)”. The on-call engineer has to guess between the config file, the price file and the stock file.
Why does this happen? (step by step)
- std::fs::read_to_string returns an io error. It has a kind (not found) and an OS code, but not the path.
- The question mark operator only converts and returns it. It adds nothing.
- By the time it reaches main, the error has gone through three functions, and none of them said what it was doing.
The fix:
use anyhow::{Context, Result};
use std::path::Path;
fn load_prices(path: &Path) -> Result<Vec<Price>> {
let text = std::fs::read_to_string(path).with_context(|| {
format!("read price file {}", path.display())
})?;
let prices = parse_csv(&text).with_context(|| {
format!("parse price file {}", path.display())
})?;
Ok(prices)
}
Now the log says: “read price file /etc/shop/stock.csv: No such file or directory (os error 2)”. When main returns the error, anyhow also prints the chain of causes.
- The with_context method takes a closure, so the message is only built when there is an error.
- The context method takes a ready value and is fine for a fixed text.
- Each layer adds what it knows: the low layer knows the path, the high layer knows the goal (for example “load startup data”).
Follow-up question: How do you add context in a library that uses thiserror instead of anyhow?
Follow-up answer:
- Put the context into the error variant as fields, for example a ReadPrices variant with the path field and the io error as its source.
- The error attribute can then write a message that includes the path.
- Keep the original error as the source (the source or from attribute), so the chain is not lost.
Red flag: Logs only the outer message, or replaces the original error with a new text and loses the cause.
Show answer
7. A PDF invoice in an async handler
Question: Our shop API runs on Tokio with the default multi-thread runtime (one worker thread per CPU core, the pod has 2 cores). This handler makes the PDF invoice of an order. Making a PDF takes about 300 ms of CPU time.
async fn invoice_handler(
Path(order_id): Path<u64>,
State(app): State<AppState>,
) -> Vec<u8> {
let order = app.db.load_order(order_id).await;
make_invoice_pdf(&order) // a normal, non-async function
}
You see this in code review. What do you think? Is there a problem?
Short answer: The PDF work runs on a Tokio worker thread and does not reach an await for 300 ms. During that time the thread cannot run any other task. With 2 worker threads, two invoice requests at the same time stop the whole API, even simple health checks. Heavy CPU work or blocking calls must move off the worker threads, for example with tokio::task::spawn_blocking.
Hint (if the candidate says there is no problem): At the end of the month, the accounting team downloads many invoices. During that time the product pages also become slow, and Kubernetes restarts the pod because the health check times out.
Why does this happen? (step by step)
- Tokio runs many tasks on a few threads. A task gives its thread back only at an await point.
- make_invoice_pdf has no await. It keeps the thread busy until it ends.
- With 2 threads and 2 invoice requests, both threads are busy for 300 ms. Every other request waits, even if it needs only a microsecond.
- The same is true for any blocking call: std::thread::sleep, reading a big file with std::fs, a blocking database driver, or password hashing.
The fix:
async fn invoice_handler(
Path(order_id): Path<u64>,
State(app): State<AppState>,
) -> Result<Vec<u8>, AppError> {
let order = app.db.load_order(order_id).await;
let pdf = tokio::task::spawn_blocking(move || {
make_invoice_pdf(&order)
})
.await?; // error only if the PDF code panicked
Ok(pdf)
}
- spawn_blocking runs the closure on a separate pool of threads made for blocking work. The worker thread is free to run other tasks.
- The handler awaits the result, so the code still reads top to bottom.
- The blocking pool is big (up to 512 threads by default), so for CPU-heavy work also limit how many run at once, for example with a Semaphore, or use a CPU pool like rayon.
- For files and sleeping, use the async versions in Tokio (tokio::fs, tokio::time::sleep).
Follow-up question: How would you find a blocking call like this in production?
Follow-up answer:
- Look for high latency on all endpoints at the same time, while CPU is high on only a few threads.
- tokio-console shows tasks that run a long time between two await points (“busy” time).
- In tests, a watchdog task that should wake every 10 ms and logs when it is late can show that a worker was blocked.
Red flag: Thinks that anything inside an async function is automatically non-blocking, or suggests adding more worker threads as the only fix.
Show answer
8. A price cache that made the shop slower
Async Rust· in roadmapConcurrency in Rust· in roadmap
Question: Product prices come from a slow pricing service (about 200 ms per call). To make the shop faster, a teammate added this cache. The API runs on Tokio.
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;
#[derive(Clone, Default)]
struct AppState {
prices: Arc<Mutex<HashMap<u64, u64>>>,
}
async fn price(state: &AppState, product_id: u64) -> u64 {
let mut cache = state.prices.lock().await;
if let Some(p) = cache.get(&product_id) {
return *p;
}
let p = pricing::fetch(product_id).await;
cache.insert(product_id, p);
p
}
It compiles, and the tests pass. You see this in code review. What do you think? Is there a problem?
Short answer: The lock guard lives until the end of the function, so the lock is held during the 200 ms network call. While one request waits for the pricing service, every other price lookup waits for the lock, even for products that are already in the cache. All price requests now run one after another. The fix: hold the lock only to read or write the map, and do the network call without the lock.
Hint (if the candidate says there is no problem): Before the cache, a page with 5 new products took about 200 ms, because the 5 calls ran at the same time. With the cache, it takes about 1 second. Pages with only cached products are also slow when a new product is being loaded.
Why does this happen? (step by step)
- The guard named cache is dropped at the end of the function, not after its last use. A guard is a value with a drop, so its scope decides when the lock is released.
- Because this is a Tokio Mutex, holding it across an await compiles. With a std Mutex, tokio::spawn would refuse it, because that guard is not Send.
- Request A takes the lock and waits 200 ms for the network.
- Requests B, C, D wait for the lock, even if their product is in the cache.
- The result: price lookups are serialized. The cache made the app slower under load.
The fix:
async fn price(state: &AppState, product_id: u64) -> u64 {
if let Some(p) = state.prices.lock().await.get(&product_id) {
return *p; // the guard lives only inside this if let
}
let p = pricing::fetch(product_id).await; // no lock held
state.prices.lock().await.insert(product_id, p);
p
}
- Each lock is held only for one map operation. The network call runs with no lock.
- Now a std Mutex is even better here, because the lock is never held across an await. It is faster than the Tokio Mutex for short critical sections.
- Two requests for the same new product may both call the pricing service. That is usually fine. If it is not, use a per-key “in flight” entry or a cache crate like moka that loads each key once.
- The cache also needs a limit and an expiry (for example with moka), or it grows forever and prices become old.
Follow-up question: When do you really need the Tokio Mutex instead of the std Mutex?
Follow-up answer:
- When the lock must be held across an await on purpose, for example to keep one shared connection while we use it.
- The Tokio documentation itself says the std Mutex is usually the better choice for plain data, as long as the guard is never held across an await.
- If the lock must be held across an await, ask first if the design can change, for example one task that owns the resource and gets work through a channel.
Red flag: Thinks the Tokio Mutex makes it fine to hold a lock across slow work, or does not know when a guard is released.
Show answer
9. A timeout around the payment
Question: Checkout must answer within 2 seconds, so we wrapped the payment in a timeout. If it times out, the mobile app shows “Payment failed, try again”.
use std::time::Duration;
use tokio::time::timeout;
async fn pay(order: &Order) -> Result<Receipt, PayError> {
let tx = bank::charge_card(order).await?;
db::save_paid_order(order, &tx).await?;
Ok(Receipt::new(order, tx))
}
async fn checkout(order: Order) -> Result<Receipt, CheckoutError> {
match timeout(Duration::from_secs(2), pay(&order)).await {
Ok(result) => Ok(result?),
Err(_elapsed) => Err(CheckoutError::TryAgain),
}
}
You see this in code review. What do you think? Is there a problem?
Short answer: When the timeout fires, the pay future is dropped at whatever await it is waiting on. If that happens after the card was charged but before the order was saved, the money is taken, the order is not marked as paid, and the user is told to try again, so they may pay twice. A future can stop at any await. Steps that must finish together cannot simply be cancelled in the middle. The fix: make the payment idempotent (an idempotency key from the order), let the critical part finish in its own task, and tell the user “still processing” instead of “failed”.
Hint (if the candidate says there is no problem): On a busy evening, the database is slow. Some customers write to support: “The app said the payment failed, so I paid again. Now my card was charged twice, and I see no order.”
Why does this happen? (step by step)
- A future does work only when it is polled. The timeout polls pay, and when the time is up, it stops polling and drops it.
- Dropping a future cancels it at its current await point. The code after that await never runs.
- The bank call already finished. The money is taken in the bank.
- The save was still waiting. It is dropped, so the order stays “unpaid”.
- The user sees “try again” and pays a second time. A new charge is made, because the bank does not know it is the same order.
The fix:
async fn checkout(order: Order) -> Result<Receipt, CheckoutError> {
let order_id = order.id;
// the task keeps running even if we stop waiting for it
let handle = tokio::spawn(async move { pay(&order).await });
match timeout(Duration::from_secs(2), handle).await {
Ok(joined) => Ok(joined??),
Err(_) => Err(CheckoutError::StillProcessing(order_id)),
}
}
- A spawned task is not cancelled when we stop awaiting its handle. Dropping a JoinHandle only detaches the task. So the charge and the save finish together.
- The user gets “still processing”, and the app checks the order status later instead of paying again.
- The bank call must use an idempotency key made from the order id. If the same order is charged twice for any reason (retries, crashes), the bank returns the first result.
- For real safety, save the order as “payment pending” before calling the bank, and run a background job that fixes orders stuck in that state. A crash of the whole process can still stop any code.
Follow-up question: What does “cancel safe” mean for tokio::select?
Follow-up answer:
- In a select, when one branch finishes, the other futures are dropped.
- A future is cancel safe if dropping it before it finishes loses nothing. For example, receiving from a Tokio mpsc channel is cancel safe: if it is dropped, no message is lost.
- Reading a whole frame with read_exact is not cancel safe: part of the data may already be read into the buffer and is lost. The Tokio docs list which methods are cancel safe.
Red flag: Thinks a timeout stops “the whole operation” cleanly, or wants to retry the charge without an idempotency key.
Show answer
10. A channel for shop events
Async Rust· in roadmapConcurrency in Rust· in roadmap
Question: Every action in our shop (view, add to cart, buy) creates an event. The handlers send the events to one background task that writes them to the analytics database. On a normal day there are about 2,000 events per second.
use tokio::sync::mpsc;
pub fn start_writer(db: AnalyticsDb) -> mpsc::UnboundedSender<Event> {
let (tx, mut rx) = mpsc::unbounded_channel::<Event>();
tokio::spawn(async move {
while let Some(event) = rx.recv().await {
db.insert(event).await; // about 1 ms per insert
}
});
tx
}
// in each handler
app.events.send(Event::AddToCart { product_id }).ok();
You see this in code review. What do you think? Is there a problem?
Short answer: The channel has no limit. The writer can do about 1,000 inserts per second, but the shop sends 2,000 events per second, and even more in a sale. The extra events wait in the channel, in memory, and the queue only grows. After some time the pod runs out of memory and is killed, and every event in the channel is lost. A bounded channel gives backpressure: when it is full, we must decide what to do (wait, drop, or batch) instead of growing forever.
Hint (if the candidate says there is no problem): On Black Friday, the memory of the API pods rises in a straight line for an hour. Then the pods are OOMKilled, one after another. The analytics dashboard also shows a big gap.
Why does this happen? (step by step)
- Sending to an unbounded channel always succeeds at once. It never waits, so the senders never feel that the writer is slow.
- One insert takes about 1 ms, so one writer can do about 1,000 per second.
- 2,000 events come in, 1,000 go out, so 1,000 events per second pile up in memory.
- Nothing stops the growth until the process runs out of memory. Then the events in the queue are lost too.
The fix:
use tokio::sync::mpsc;
pub fn start_writer(db: AnalyticsDb) -> mpsc::Sender<Event> {
let (tx, mut rx) = mpsc::channel::<Event>(10_000);
tokio::spawn(async move {
let mut batch = Vec::with_capacity(500);
// wait for at least one event, then take up to 500
while rx.recv_many(&mut batch, 500).await > 0 {
db.insert_many(&batch).await; // one round trip
batch.clear();
}
});
tx
}
// in each handler: analytics must never slow down a purchase
if app.events.try_send(event).is_err() {
metrics::counter!("events_dropped").increment(1);
}
- A bounded channel keeps memory flat: at most 10,000 events wait.
- We choose the policy when it is full. For analytics we drop and count, so the shop stays fast. For important data we would await send, so the handler waits (real backpressure), or we would use a durable queue like Kafka.
- Batching fixes the real problem: one insert of 500 rows is much faster than 500 single inserts.
- Watch the channel. A metric for dropped events and for the queue length shows the problem early.
Follow-up question: When is an unbounded channel acceptable?
Follow-up answer:
- When the number of messages is limited by design, for example one message per connected admin user, or a few control messages like “shut down”.
- When the producer is slower than the consumer by nature and this is clear in the code.
- Never for traffic that comes from outside users, because they decide the rate, not us.
Red flag: Says “memory is cheap”, or suggests a bigger pod as the fix, or does not see that the events in memory are lost on a crash.
Show answer
11. Two wallets and two locks
Concurrency in Rust· in roadmap
Question: Our shop has a wallet for each customer. Customers can send credit to each other. Many transfers run at the same time on different threads.
use std::sync::Mutex;
struct Wallet {
id: u64,
cents: Mutex<u64>,
}
fn transfer(from: &Wallet, to: &Wallet, cents: u64) {
let mut a = from.cents.lock().unwrap();
let mut b = to.cents.lock().unwrap();
if *a >= cents {
*a -= cents;
*b += cents;
}
}
It compiles with no warning, and Rust promises no data races. You see it in code review. What do you think? Is there a problem?
Short answer: Rust stops data races, but it does not stop deadlocks. Two transfers in opposite directions can each take their first lock and then wait forever for the other one. The fix is to always take the locks in one global order (for example, smaller wallet id first), or to avoid holding two locks at all, for example by doing the transfer in one database transaction.
Hint (if the candidate says there is no problem): Sara sends 10 dollars to Reza, and at the same moment Reza sends 5 dollars to Sara. Both requests never finish. After that, every transfer that touches Sara or Reza also hangs.
Why does this happen? (step by step)
- Thread 1 runs transfer from Sara to Reza. It locks Sara’s wallet.
- Thread 2 runs transfer from Reza to Sara. It locks Reza’s wallet.
- Thread 1 now wants Reza’s lock. Thread 2 holds it, so thread 1 waits.
- Thread 2 now wants Sara’s lock. Thread 1 holds it, so thread 2 waits.
- Both wait for each other forever. A std Mutex has no timeout, and Rust’s type system does not track lock order.
- There is a second bug: a transfer from a wallet to the same wallet locks the same Mutex twice on one thread. That deadlocks or panics.
The fix:
fn transfer(from: &Wallet, to: &Wallet, cents: u64) {
if from.id == to.id {
return; // nothing to move, and no double lock
}
// always lock the smaller id first
let from_first = from.id < to.id;
let (first, second) = if from_first {
(from, to)
} else {
(to, from)
};
let mut g1 = first.cents.lock().unwrap();
let mut g2 = second.cents.lock().unwrap();
let (a, b) = if from_first {
(&mut *g1, &mut *g2)
} else {
(&mut *g2, &mut *g1)
};
if *a >= cents {
*a -= cents;
*b += cents;
}
}
- With one global order, every thread waits in the same direction, so a cycle cannot form.
- The same-wallet case is handled before any lock.
- In a real shop, the balance lives in a database. Then one transaction with both rows (and a fixed order for the row locks, or a single UPDATE) does the same job and also survives a crash.
Follow-up question: What other ways are there to avoid deadlocks in Rust?
Follow-up answer:
- Hold only one lock at a time, and keep the critical section short.
- Give one task or thread ownership of the data, and send it commands over a channel (the actor style). Then there are no shared locks at all.
- The try_lock method lets you give up and retry instead of waiting forever, but it can turn a deadlock into a busy loop, so lock order is still the cleaner fix.
Red flag: Says “Rust prevents all concurrency bugs”, or does not see the opposite-direction case.
Show answer
12. Designing an order processing service in Rust
Async Rust· in roadmapConcurrency in Rust· in roadmapSystem design· in roadmap
Question: We want to rewrite our order processing service in Rust. Today it is a slow Python service. The facts:
- Orders arrive as messages in a Kafka topic, about 3,000 per second, up to 15,000 per second in a sale.
- For each order, the service checks stock in PostgreSQL, calls the payment service over HTTP (50 to 500 ms), and writes the result back to Kafka.
- Orders of the same customer must be processed in order.
- A deploy restarts the pods several times a day. No order may be lost or charged twice.
- The service runs in Kubernetes, 4 pods with 2 CPU cores each.
How would you design this service in Rust? Explain the main parts and your choices step by step.
Short answer: One Tokio runtime per pod. A consumer task reads from Kafka and sends each order to a bounded channel of a worker chosen by the hash of the customer id, so the orders of one customer always go to the same worker and stay in order. A fixed number of async workers do the I/O (database pool, HTTP client with timeouts), and the payment call uses an idempotency key, because a message can be delivered more than once. Offsets are committed only after the result is written. Bounded channels give backpressure, typed errors decide between retry and dead-letter, and a cancellation token gives a graceful shutdown on deploy.
The main parts:
- The runtime. The work is mostly waiting on the network, so async Rust with Tokio fits well. One multi-thread runtime per pod, with the default of one worker thread per core.
- Ordering per customer. The Kafka topic is partitioned by customer id, so one customer’s orders are in one partition. Inside the pod, the consumer picks a worker with the hash of the customer id modulo the number of workers. Each worker handles its own orders one at a time, so the order is kept, while different customers run in parallel.
- Concurrency without overload. For example 64 workers per pod, each with a bounded channel of 100 orders. When the workers are slow, the channels fill, the consumer awaits send, and it stops reading from Kafka. That is backpressure, and memory stays flat. A small connection pool (for example sqlx with about 10 connections per pod) protects PostgreSQL.
- Payments that are safe to repeat. Kafka gives “at least once” delivery: after a crash, some orders come again. The payment request carries an idempotency key made from the order id, and the result table has a unique key on the order id. So a repeated message is detected and does no harm.
- Commit after the work. The consumer commits an offset only when all orders up to that offset are done. Then a crash in the middle means “process again”, never “lost”.
- Timeouts and retries. Every HTTP call has a timeout. Temporary errors are retried with backoff and a limit, and only because the call is idempotent. Bad messages go to a dead-letter topic with the reason, so one bad message does not block the partition.
- Errors as types. An error enum with thiserror (for example StockMissing, PaymentDeclined, Temporary) lets the worker decide with a match: retry, dead-letter, or “order failed” event. The main function uses anyhow for startup errors with context.
- Graceful shutdown. On SIGTERM, a CancellationToken (from tokio-util) tells the consumer to stop reading. The workers finish the orders they already have, offsets are committed, and the pod exits within the Kubernetes grace period.
- Observability. The tracing crate with a span per order (order id, customer id), metrics for queue length, latency per step, retries and dead letters.
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
fn worker_for(customer_id: u64, workers: usize) -> usize {
(customer_id % workers as u64) as usize
}
async fn consume(
queues: Vec<mpsc::Sender<Order>>,
stop: CancellationToken,
) {
loop {
let order = tokio::select! {
_ = stop.cancelled() => break,
order = kafka::next_order() => order,
};
let i = worker_for(order.customer_id, queues.len());
// waits when that worker is full: backpressure
if queues[i].send(order).await.is_err() {
break; // the worker stopped
}
}
}
Trade-offs to mention:
- More workers means more parallel customers, but more load on the database and the payment service. Start small and measure.
- A hot customer (for example a big business account) makes one worker slow. If it becomes a problem, split by order id for customers who do not need strict order.
- Exactly once does not exist end to end. We get “effectively once” with at-least-once delivery plus idempotent writes.
- Rust brings low memory and stable latency with no GC pauses, but the team must learn async Rust. The design must keep blocking work (like a CPU-heavy fraud check) off the worker threads, with spawn_blocking.
Follow-up question: The payment service is down for 10 minutes. What happens to your service, and what should happen?
Follow-up answer:
- The calls time out and are retried with backoff. The workers become slow, the channels fill, and the consumer stops reading. Kafka keeps the orders safe, and the lag grows. Memory stays flat.
- A circuit breaker should open after many failures, so we stop calling the payment service for a while and do not make its recovery harder.
- When it comes back, the lag goes down at a limited speed. An alert on consumer lag tells the team what is going on.
- Orders are not lost and not charged twice, because offsets are committed after the work and the payments are idempotent.
Red flag: Spawns one unbounded task per message with no limit, commits the Kafka offset before the work is done, retries payments without an idempotency key, or forgets the per-customer order.
Show answer
13. A shipping label from a C library
Unsafe Rust and FFI· in roadmap
Question: Our shop prints shipping labels with a C library from the delivery company. A developer wrote this wrapper:
use std::ffi::{c_char, c_int, CString};
unsafe extern "C" {
fn parcel_set_sender(name: *const c_char) -> c_int;
}
pub fn set_sender(name: &str) -> bool {
let ptr = CString::new(name).unwrap().as_ptr();
unsafe { parcel_set_sender(ptr) == 0 }
}
The library docs say: “parcel_set_sender keeps the pointer and uses the name for every label printed later.”
You see this in code review. What do you think? Is there a problem?
Short answer: There are two lifetime bugs and one safety bug. First, the CString is a temporary value: it is dropped at the end of the let line, so ptr already points to freed memory when C gets it. Second, even if we kept the CString in a variable, it would be dropped when set_sender returns, but the library keeps the pointer and reads it later. Both are undefined behavior. Third, unwrap panics if the name has a zero byte inside, and that comes from user input. The fix: give C memory that lives as long as C uses it (for example a CString kept in a static, or into_raw with a matching free later), return an error instead of panicking, and write a SAFETY comment that explains it.
Hint (if the candidate says there is no problem): In tests the labels look fine. In production, some labels show the sender as random characters, and once in a while the label worker crashes.
Why does this happen? (step by step)
- CString::new allocates a copy of the name with a zero byte at the end.
- as_ptr only borrows a pointer. It does not keep the CString alive.
- The CString is a temporary, so it is dropped at the semicolon. Its memory is freed.
- C gets a dangling pointer. It may still see the old bytes for a moment, which is why tests pass.
- Later, other code reuses that memory. When C prints a label, it reads whatever is there now.
The Rust compiler warns about the first bug (the lint about dangling pointers from temporaries), but it cannot see the second one: it does not know that the C library keeps the pointer.
The fix:
use std::ffi::{c_char, c_int, CString};
use std::sync::Mutex;
// The library keeps the pointer, so the string must live
// until we replace it.
static SENDER: Mutex<Option<CString>> = Mutex::new(None);
pub fn set_sender(name: &str) -> Result<(), SenderError> {
let name = CString::new(name).map_err(|_| SenderError::NulByte)?;
let mut slot = SENDER.lock().unwrap();
// SAFETY: name is a valid C string. It is moved into SENDER
// below and stays there until the next call, so it outlives
// every read by libparcel. The lock stops two calls at once.
let code = unsafe { parcel_set_sender(name.as_ptr()) };
if code != 0 {
return Err(SenderError::Library(code));
}
*slot = Some(name); // the old name is freed only now
Ok(())
}
- Moving a CString does not move its bytes, so the pointer stays valid inside SENDER.
- The old name is dropped only after C has the new one.
- The function returns an error for a zero byte instead of panicking.
- If the library has a function to clear the sender, call it before the program frees the last name.
Follow-up question: The library also has a callback: parcel_on_printed(cb), and C calls cb on its own thread. What must the Rust callback care about?
Follow-up answer:
- It must be an extern “C” fn, and it must never let a panic leave it. Since Rust 1.81 that aborts the process. Wrap the body in catch_unwind.
- It runs on a C thread, so any shared data it touches must be thread safe (Mutex, atomics, or a channel to send the event to Rust code).
- It must not keep pointers that C gives it after it returns, unless the docs say they stay valid. Copy the data.
Red flag: Says “it is in an unsafe block, so the compiler checks it”, or fixes the first bug with a local variable and does not ask how long C keeps the pointer.
Show answer
14. A macro that skips order numbers
Question: Order numbers in our shop must start at 1000. A developer wrote a small macro and uses it when an order is created:
macro_rules! at_least {
($value:expr, $min:expr) => {
if $value < $min { $min } else { $value }
};
}
fn create_order(db: &Db, cart: Cart) -> Order {
let id = at_least!(db.next_order_id(), 1000);
Order::new(id, cart)
}
next_order_id reads the next number from a database sequence and moves the sequence forward.
You see this in code review. What do you think? Is there a problem?
Short answer: A macro pastes the expression, it does not compute it once. $value appears two times in the template, so db.next_order_id() runs two times when the id is 1000 or more. Every order uses two numbers from the sequence, so half of the order numbers are skipped, and each order makes two database calls. The fix is to bind each input once inside the macro, or better, not to use a macro at all: a normal function or the max method does the same job.
Hint (if the candidate says there is no problem): The support team asks why the order numbers are 1001, 1003, 1005 and never even.
Why does this happen? (step by step)
- Macros run before type checking. They work on tokens, not on values.
- The call becomes this code: if db.next_order_id() < 1000 { 1000 } else { db.next_order_id() }.
- The first call returns 1000, the check fails, and the else branch calls next_order_id again and gets 1001.
- The order gets 1001. The number 1000 is lost. Next time, 1002 is lost.
The fix:
// Best: no macro needed
let id = db.next_order_id().max(1000);
If a macro is really needed, bind the inputs once:
macro_rules! at_least {
($value:expr, $min:expr) => {{
let value = $value;
let min = $min;
if value < min { min } else { value }
}};
}
- The double braces make the macro one block expression, so the let lines stay inside it.
- Hygiene makes sure value and min do not clash with variables of the same name at the call site.
- You can check the generated code with cargo expand.
Follow-up question: When is a macro really the right tool in a Rust codebase?
Follow-up answer:
- When you must generate new items, like twenty impl blocks for event types, that a generic or trait cannot give you.
- When you need a variable number of arguments or a small syntax, like vec! or a test table.
- When you must read the fields or attributes of a struct, like a derive for serialization. That needs a procedural macro with syn and quote.
- Not for simple logic. A function is easier to read, test and debug, and the compiler gives better errors.
Red flag: Thinks a macro works like a function call, or does not see that the expression runs more than once.
Show answer
Not saved in this browser.