Skip to content

FastAPI + PocketBase: my go-to backend stack

When there's a backend, an internal tool or a SaaS platform to build, I almost always reach for FastAPI plus PocketBase. Here's the architecture, the projects, and the mistakes that taught me the most.

It has become my default because it's quick to get started with and still holds up as the project grows. I've used it for an energy platform with physical devices, a travel app with live updates, access control for gyms, monitoring of 3D printers and several internal tools. The pattern is the same every time, and that pattern is what this post is about.

The two parts

FastAPI

FastAPI is a Python framework for APIs. I write a route as a plain Python function, describe input and output with Pydantic models, and get validation, error messages and OpenAPI documentation for free. It's async from the ground up, uses type hints everywhere and needs very little setup.

What I value most is that the API describes itself. The OpenAPI spec is generated from the code, so the frontend can have types generated straight from it. When a route changes shape, it becomes a type error in the client instead of a bug for the user.

PocketBase

PocketBase is a lightweight backend in a single binary. It contains a SQLite database, users and login, file handling, an admin panel and realtime subscriptions. There's no separate database server to run, no auth service to keep updated and no file store to set up. It runs in one container with one volume.

For many projects, that is exactly the amount of infrastructure needed. You get a real database with a schema, access rules and backups, without spending the first week setting up Postgres, an auth solution and object storage.

The most important decision: clients never talk to PocketBase directly

PocketBase is built so clients can talk to it directly. It's tempting, because it's fast. I don't do it anymore, and the reason is a specific project.

Luggage Log's first app was built in Flutter and talked directly to PocketBase. That worked fine until the project needed a web version. Then it turned out that the business logic lived in Dart inside the app, and PocketBase calls were spread across more than 15 files. A web version would mean writing all that logic again in another language and keeping the two in sync forever.

The fix was to put FastAPI in between. The app was switched over by replacing the implementation behind its existing database interface, so it talked to the new API instead of to PocketBase. The web got the same API. Since then the app has been rebuilt in Ionic Vue, and the new app is just another client of the same API.

Today all my projects follow the same rules:

  • FastAPI is the only public boundary. Web, app, devices and integrations call FastAPI. PocketBase sits on the internal network.
  • The admin key never leaves the backend. FastAPI talks to PocketBase as a superuser, and clients never see that key.
  • Business logic lives in one place. Rules about who can do what, calculations and integrations live in Python. New clients reuse them.
  • PocketBase is the data layer. It stores data, enforces the schema and delivers realtime. It doesn't decide what a user is allowed to do.

What a request looks like

It helps to follow a single request all the way through:

  1. The user logs in to the app. The app sends email and password to FastAPI, never to PocketBase.
  2. FastAPI asks PocketBase to check the password. PocketBase just answers yes or no.
  3. If the answer is yes, FastAPI issues its own token with the permissions the user has.
  4. The app sends that token on every following call. FastAPI checks the token and the permissions before anything happens.
  5. FastAPI reads or writes data in PocketBase over an internal HTTP connection and returns a response shaped for the client.
  6. If the client needs live updates, it opens a WebSocket to FastAPI, and FastAPI handles the subscription to PocketBase behind it.

That's one extra hop compared with letting the client talk to the database directly. In return there's only one place where access is decided, and that place is ordinary Python code you can test.

Auth: PocketBase checks passwords, FastAPI owns the session

On Watt-E, auth is split so PocketBase only does what it's good at: storing users and checking passwords safely. Everything after that belongs to FastAPI. It issues its own tokens, signed with its own key.

That gives a freedom PocketBase's own tokens don't. Watt-E can, for example, issue scoped tokens to integrations and AI tools. Such a token only gets the permissions that both the user has and the integration asks for. The intersection of the two, never more. If an integration only needs to read data, it can't write, no matter which user granted access.

On the access-control platform for gyms, the need is different. There are several tenants, and each tenant can have its own way of logging in: some through a subscription system with signed requests, others with ordinary PocketBase login. Because auth sits in FastAPI, these are just different implementations behind the same interface. The rest of the system doesn't care how the user got in.

How FastAPI talks to PocketBase

There is a Python SDK for PocketBase, but it's unofficial and has been unstable. In newer projects I use a thin async HTTP client built on httpx instead. PocketBase's REST API is simple and well documented, so a small client with the calls the project actually uses is easy to write and easy to understand.

Watt-E still has an older part that uses the SDK, next to the new client. It's a good example that you don't have to rewrite everything at once. New code uses the new client, and old code moves over when it needs touching anyway.

The most expensive mistake: sync calls in async code

The most important lesson here cost an outage. One place in Watt-E used a synchronous HTTP client inside an async FastAPI route. In an async framework, all requests run on the same event loop. When one route makes a blocking call, everyone else waits too. The health endpoint ended up hanging for 764 seconds in production.

The fix was simple: async all the way down, including the client for PocketBase. It can be hard to spot, because the code works fine locally with one user. That's why I now have one shared async client per project and no other way of calling PocketBase.

Realtime without overloading the database

PocketBase can push changes to subscribers with Server-Sent Events. The naive approach is to let every client subscribe directly. Luggage Log does it differently.

A packing list for a trip can be open for many people at once. Instead of each of them having their own connection to PocketBase, the backend has one subscription per trip. When a change comes in, FastAPI fans it out to every connected client through asyncio queues and WebSockets. If there are several backend workers, Redis can act as a shared channel between them, so a change reaches everyone no matter which worker the client is connected to.

Two details make it robust:

  • Short-lived stream tokens. A WebSocket can't send headers the way an ordinary call does. The client first asks for a short-lived token for that one connection and uses it in the handshake. The normal login token never ends up in a URL.
  • One source, many receivers. The number of connections to PocketBase depends on the number of active trips, not the number of users.

On Watt-E, realtime is a different story, because physical devices are involved. Messages go to and from the devices over MQTT, and the backend has both a publisher and a subscriber on that message bus. The device firmware lives in the same repository, so the protocol can be changed in one place.

Migrations and schema

Schema is where PocketBase has surprised me the most. There are three things to know.

The admin panel can write files that disappear

PocketBase can automatically write migration files when you change the schema in the admin panel. That sounds handy, but on a server PocketBase runs in a container. Those files are written inside the container and vanish on the next deploy. Then you have a database whose schema doesn't exist in git.

On Watt-E that automation is turned off. Instead, the schema is set up by a script when the backend starts. Luggage Log goes the other way and keeps its migrations as JavaScript files in git, 39 of them so far. Both work. The point is that the schema belongs in the code, not in some clicked-together state on the server.

Migrations marked as applied that didn't work

Luggage Log had an incident that still puzzles me a little. The migrations were marked as applied, the files were on disk, but four collections had never been registered in the running PocketBase. The API answered as if they didn't exist. A restart didn't help. A redeploy didn't help either.

The fix was to import the schema explicitly through PocketBase's API, with a setting that makes sure existing collections aren't deleted. The lesson has become a fixed rule: after every schema change I check with a real call to the API that the new thing actually exists. A migration reporting success isn't enough.

Pin the version

Another lesson from the same project: the PocketBase image was set to :latest. One day production had quietly drifted to a newer version. Rolling back isn't simple, because once the database file has been opened by a newer version it may have been upgraded. Going back would mean downgrading a database.

Today the image is pinned to an exact digest, and upgrades are a deliberate step with a backup before and a test after.

Hooks: when something must happen exactly once

PocketBase supports hooks written in JavaScript that run inside the database. I use them sparingly, because logic should preferably live in FastAPI. But there is one kind of problem where they're the right tool: when something must happen exactly once, even if several things try at the same time.

On the treatment platform, tasks come in through a message queue. The queue can deliver the same message more than once, which is normal behavior for many message queues. If two workers take the same task, it happens twice. The fix is a hook that, in a single transaction, checks whether the task is still free and marks it as taken. The first one wins, the second gets a no. The access-control platform uses the same technique to make sure something can only be claimed once.

It could be done in FastAPI with locks, but it's safest to do it where the data lives, in the same transaction.

Clean architecture on the treatment platform

The treatment platform is built with clean architecture. The domain layer, which holds the rules for treatments and courses, never imports FastAPI or PocketBase. FastAPI is the only public boundary, and PocketBase is hidden behind repository interfaces.

That might sound academic, but it has two very practical benefits. The domain logic can be tested without a database. And the day a project outgrows PocketBase, it's the adapter that gets replaced while the business logic stays put.

Where I've used it

Watt-E

Watt-E has FastAPI and PocketBase at the core of the platform, together with Redis and MQTT for the physical devices. FastAPI handles login, access, tokens and integrations. PocketBase stores the data. The platform runs on its own Hetzner server via Coolify.

Luggage Log

Luggage Log uses the same combination, with Redis, a background worker for jobs that shouldn't block a request, and rate limiting on the API. This is where the realtime architecture with one subscription per trip was built.

Access control for gyms

A platform with several tenants, several ways to log in and integration with smart locks and static PIN codes. PocketBase hooks make sure things that may only happen once only happen once.

IoT monitoring of 3D printers

A Raspberry Pi next to the printers acts as a proxy and sends data over Tailscale to a server with FastAPI, MQTT and a time-series database. Printer data goes through an ingest service, and a React frontend shows the status.

Office scheduling

An internal scheduling tool for a laboratory, built in FastAPI and PocketBase to replace an older Google Apps Script setup. A good example that the stack also fits small tools where the operational burden needs to be close to zero.

When I don't choose PocketBase

PocketBase isn't the answer to everything. I choose something else when:

  • There are many concurrent writes. SQLite is fast, but writes one thing at a time. For systems with heavy, concurrent writing, Postgres is a better choice.
  • Data has to be shared by several services. If several systems need to read and write the same database directly, a classic database server fits better.
  • Advanced SQL features are needed, like heavy reports, complex joins across large tables or extensions for time-series or geodata.
  • The client already has Postgres and a team that knows it.

In those cases I keep FastAPI and swap the data layer, usually for Postgres. Because the clients have never talked to PocketBase directly, and because the domain sits behind interfaces, it's a matter of replacing an adapter. That's the whole point of the split. My websites and webshops run on Postgres through Payload and Medusa anyway, because those needs are different.

Operations on your own server

Many of the hardest bugs I've met weren't in the code. Watt-E has taught me a handful of things about running a platform on your own server:

  • Build cache fills the disk. Docker keeps layers from every build. At one point they filled the disk and the database went down. Disk usage and build-cache cleanup are now a fixed part of operations.
  • Deploys can get stuck. A deploy that hung in "in progress" blocked the queue for every deploy after it. You need to know how to cancel it.
  • Placeholders aren't secrets. Strings like "Set VAR" ended up as real values in environment variables. Validate configuration at startup, so a missing key gives a clear error instead of strange behavior.
  • Use PocketBase's own backup. When the platform moved to its own server, the data was moved with PocketBase's backup and restore API. It was the most painless part of the move.

My checklist before a deploy

  1. Is the PocketBase image pinned to an exact version?
  2. Are all schema changes in git, and is automatic migration generation turned off on the server?
  3. Has a backup been taken before a migration or an upgrade?
  4. Does all code that talks to PocketBase use the shared async client?
  5. Is PocketBase only reachable on the internal network?
  6. Does the health endpoint answer quickly?
  7. Are all environment variables set to real values, and does startup fail clearly if one is missing?
  8. Is there space left on the disk?
  9. After the deploy: do the new collections and fields actually exist when you call the API?

What you get out of it

  • Fast development. From idea to running API in hours, not weeks.
  • Low operational overhead. One PocketBase container instead of a separate database, auth service and file store.
  • Realtime without extra infrastructure. Live updates out of the box, and an architecture that scales with the number of trips, devices or rooms rather than the number of users.
  • A clean boundary. Every client goes through the same API, so a new app or a web version doesn't need a new backend.
  • A way forward. If the project outgrows PocketBase, the data layer gets swapped and the rest stays.

Working in the same stack?

Do you use FastAPI and PocketBase yourself, or are you considering it for a project? I'm happy to share experience with auth, realtime, migrations and running things on your own server. Get in touch.