Skip to content
tezvyn:

Design DB transaction middleware and identify the background-task pitfall

Source: fastapi.tiangolo.comHardHow cards are made

Design DB transaction middleware and identify the background-task pitfall

Tests request-scoped DB lifecycle awareness. Strong answer: middleware closes the session on response, yet BackgroundTasks run afterward, so sharing that session causes crashes or leaks. Red flag: saying background tasks can reuse the request transaction.

What's really being asked

This question tests whether you understand that request-scoped database transactions and FastAPI BackgroundTasks have incompatible lifecycles. The interviewer wants to see that you know middleware wraps the request-response cycle, while background tasks execute after the response has already been sent. It also checks if you can spot resource boundary violations and explain why a session closed at response time cannot be reused by deferred work.

The full answer

A good answer hits four things in order. First, describe the middleware pattern: open a session on request, attach it to state or context, commit on success or rollback on exception, then close the session as the response leaves. Second, explain the timing gap: BackgroundTasks are scheduled during the request but only executed after the response returns, so they run after middleware tears down the transaction. Third, name the failure modes: the task tries to use a session whose connection has been returned to the pool, causing closed-connection or detached-instance errors. Fourth, state the fix: background tasks must acquire their own fresh session; pass primitive IDs rather than ORM objects, and let the task open a new session and commit independently.

The mistakes people make

Common wrong answers include saying the background task can simply capture the request session and keep using it. Another red flag is suggesting the middleware should await background tasks before closing the session, because that blocks the response and defeats the purpose. Some candidates propose a global long-lived session per worker, which creates concurrency bugs and leaks. A subtler mistake is arguing the request transaction should rollback if a later background task fails, which confuses separate consistency boundaries.

What usually comes next

Interviewers often ask how to pass data to a background task without holding the session open; pass serializable IDs or DTOs, not ORM instances. They may ask what happens if the background task fails, and the correct line is that the request should not rollback; the task needs its own retry logic. They might ask whether SQLAlchemy async sessions change the pitfall, and the answer is no, because the issue is lifecycle, not the driver.

A concrete example

Imagine an endpoint that creates an order in a request transaction and then schedules a background task to update inventory. The middleware commits and closes the session as soon as the endpoint returns a 201 response. The background task starts moments later and tries to flush an inventory change using the same session object. Because the async connection has already been returned to the pool, the task raises a closed-connection or detached-instance error. The correct design is to pass the order ID to the task, have it open a brand new session, fetch the order again, update inventory, commit, and then send the email. This keeps the request transaction small and gives the background work a valid connection.

Interview question

When middleware manages a request-scoped database session in FastAPI, what is the correct way to handle database work inside a BackgroundTask?

  • a.Maintain one global long-lived session per worker for requests and background tasks to share.
  • b.Await BackgroundTasks in the middleware before closing the session so the task reuses the same transaction.
  • c.Pass the request's active session object to the BackgroundTask because it outlives the response.
  • d.Pass only primitive IDs to the BackgroundTask and have it acquire a fresh, independent session.Correct
Why?

BackgroundTasks execute after the response is sent, so the middleware has already closed the request session and returned its connection to the pool; giving the task only serializable IDs and letting it open a new session avoids detached-instance or closed-connection errors. Reusing the request session fails because the task runs outside the request-response lifecycle.

Just read this? Test yourself on what you have been reading.

Read the original → fastapi.tiangolo.com

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.

See open roles