Kanta

Structured application data and persistent storage with msgspec and Kanta.

Our polls are now shared between browsers, but they disappear whenever we restart the server. We also have yet to make voting work across browsers.

We will give our Python data a proper structure, make it persistent and complete the voting functionality.

1. Giving our data a structure

Our server currently stores polls as dictionaries. This was convenient when all we did was pass data between browsers, but now we need to work with that data in Python.

Consider how we would record a voter’s selected answer:

polls[poll_id]["votes"][voter] = index

Wouldn’t it be nicer to work with named fields, with tab completion and type checking in our editor?

polls[poll_id].votes[voter] = index

Python provides dataclasses for this purpose, and libraries such as Pydantic and msgspec extend the idea with serialization and validation.

Msgspec is a particularly fast library for working with structured data, converting between native Python types and formats such as JSON and MessagePack.

uv add msgspec

Msgspec is a core dependency of Kanta, so normally we would not need to install it separately. Here we will explore its capabilities before introducing the database.

Defining our data model

We already have TypeScript interfaces describing our polls and their options. Let’s give Python equivalent definitions in a new module, backend/poll_box/db.py:

from uuid import UUID

import msgspec

class Poll(msgspec.Struct):
    question: str
    options: list[str]
    votes: dict[str, int] = {}

class Master(msgspec.Struct):
    polls: dict[UUID, Poll] = {}

master = Master()

These are ordinary Python objects with constructors generated from the field definitions. We can create a Poll("Where?", ["Library", "Hall"]) and record votes in its votes dictionary. The keys will be IP addresses and the values zero-based option indices.

Our Master structure serves much the same purpose as our Pinia store, holding all our application data.

Note: we can use UUID, datetime, bytes and many other types that msgspec automatically converts to JSON and back as needed. Our variables remain normal Python objects — no monkey business there.

Moving our application state

Our global polls = {} dictionary in app.py now lives inside master in db.py, which will also become the home of our database.

Remove the original dictionary and import our new module into app.py with from . import db, along with an import of msgspec.

All references to the polls collection will now go through db.master.polls. However, the collection expects Poll objects rather than dictionaries, so we also need to adapt the way data enters and leaves our server.

Receiving structured data

FastAPI decodes the JSON body of our POST request into a dictionary. We could construct our objects from it field by field:

db.Poll(
    question=poll["question"],
    options=poll["options"],
    votes=poll["votes"],
)

But we have already described the entire structure to msgspec. Its msgspec.convert function can do this for us, validating the data in the process.

Revisit our poll creation endpoint, converting the incoming dictionary into a Poll object before storing it. We can now also use the UUID directly as a dictionary key.

@app.post("/api/polls/{poll_id}", status_code=201)
async def create_poll(poll_id: UUID, poll: dict):
    db.master.polls[poll_id] = msgspec.convert(poll, type=db.Poll)
    await broadcast(db.master.polls)
    return {"id": str(poll_id)}

Sending structured data

Our browsers still expect the same JSON as before, but the encoder used by send_json does not understand our structs or UUID keys.

Msgspec comes with its own JSON encoder, doing all the funky types our structs now use. It produces UTF-8 encoded bytes, which FastAPI WebSocket doesn’t accept for sending as a text frame, and we don’t want to use binary frames either. This requires a slightly cumbersome encode-decode path to recover str for sending with send_text.

We’ll turn the loss into a win by making our broadcast function encode the message just once for all recipients, making it also in this way faster than the old send_json was.

async def broadcast(msg):
    text = msgspec.json.encode(msg).decode()
    for ws in list(clients):
        try:
            await ws.send_text(text)
        except (RuntimeError, WebSocketDisconnect):
            clients.discard(ws)

Apply the same principle to the initial message in our WebSocket handler, taking into account the new location of our polls dict.

@app.websocket("/api/ws")
async def poll_updates(ws: WebSocket):
    await ws.accept()
    clients.add(ws)
    try:
        await ws.send_text(msgspec.json.encode(db.master.polls).decode())
        async for text in ws.iter_text():
            print("Received:", text)
    finally:
        clients.discard(ws)

Try creating polls in two browser windows again. Everything should work exactly as before. We have changed the server’s data model without touching the frontend.

2. Making our data permanent

Create a few polls and restart the development server.

Everything is gone.

Now that we can serialise our application data, we could save it to a JSON file after every change. But what happens if we interrupt the program while it is writing? And do we really want to rewrite the entire collection whenever something changes?

Introducing Kanta

Kanta is an embedded NoSQL database for asynchronous Python applications. It keeps our data in memory while recording changes in an append-only file, from which it restores the data at startup.

Kanta works directly with msgspec structures. In fact, we have already defined our database schema: Master.

uv add kanta

We can now bolt the database onto our existing master object. Our db.py becomes:

import msgspec
from kanta import Kanta
from uuid import UUID

class Poll(msgspec.Struct):
    question: str
    options: list[str]
    votes: dict[str, int] = {}

class Master(msgspec.Struct):
    polls: dict[UUID, Poll] = {}

master = Master()
kanta = Kanta("master.kantadb", master)

Kanta restores previously stored data into our master object. Reading from the database remains as simple as accessing db.master.polls.

Managing the database lifetime

The database needs to remain open while our server is running. Our generated FastAPI application already has a lifespan handler for managing resources at startup and shutdown.

Kanta provides an asynchronous context manager, which fits neatly around our existing lifespan code:

@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator:
    async with db.kanta:
        await frontend.load()
        yield

The database opens before yield and closes when the server shuts down, finishing any pending writes.

Recording changes

While we can read our data as before, Kanta needs to know when we modify it.

We group modifications into a transaction. If the transaction succeeds, Kanta records the changes. If an exception occurs, the changes are rolled back.

There is currently only one place where we modify our application data: the poll creation endpoint. We need to perform the assignment within a transaction.

While recording what changed, why not also record who did it and what they were doing? Kanta lets us associate user and action metadata with each transaction. As we have no user accounts, we will use the client’s IP address.

FastAPI gives us access to this information through a Request parameter. Import Request from fastapi and revisit our endpoint:

@app.post("/api/polls/{poll_id}", status_code=201)
async def create_poll(poll_id: UUID, poll: dict, request: Request):
    new_poll = msgspec.convert(poll, type=db.Poll)
    with db.kanta.transaction(
        user=request.client.host,
        action="create_poll",
    ):
        db.master.polls[poll_id] = new_poll
    await broadcast(db.master.polls)
    return {"id": str(poll_id)}

Within the transaction, we work with our familiar Python objects.

Notice there is no await in transactions. Transactions happen synchronously, without anything else having a chance to happen during them, and you should prepare your data before entering a transaction. Kanta determines what changed and records the modifications in the background, not blocking your app for disk I/O.

Testing persistence

Create some polls and restart the development server once more.

This time, our polls are still there! We have a database without having written a single database query.

You should find master.kantadb in the project’s working directory. Add it to .gitignore, as it contains application data rather than source code.

3. WebSocket command channel

Our polls are now shared and persistent. Let’s make voting work again.

In our browser-only application, voting was simply a matter of recording the selected option in the Pinia store. Could we send the modified poll back to the server?

Imagine two people voting at the same time. Both browsers send their own copy of the poll, and the second copy overwrites the first voter’s record. Replacing an entire options list for every vote would cause the same problem.

Rather than telling the server what the data should look like, we should tell it what happened and let the server modify its own master data. Storing votes separately from the option labels means each vote changes only one entry in the votes dictionary.

Defining commands

We already have a bidirectional WebSocket connection. While the server uses it to distribute application data, browsers can use it to send commands.

A voting command only needs to identify the poll and the selected answer:

{
  "type": "vote",
  "poll_id": "8bd203fe-81be-49b2-b8da-7af250ea239c",
  "option": 0
}

The type field identifies which command we are sending. Msgspec supports this through tagged structs, allowing us to exchange different kinds of messages over the same connection.

Let’s create backend/poll_box/cmd.py for our commands:

from uuid import UUID

import msgspec

from .db import master

class Vote(msgspec.Struct, tag="vote"):
    poll_id: UUID
    option: int

    def apply(self, voter: str):
        master.polls[self.poll_id].votes[voter] = self.option

The tag="vote" defines the value of the type field in JSON. As we add more command types, we can join them with the pipe character (|) when specifying the type to decode into. Msgspec will pick the appropriate struct based on the tag.

Notice that we have also given our command an apply method. Much like our Pinia actions, it contains the logic for modifying our master data. This keeps application logic separate from the code handling network communication.

Remember the nested dictionary access at the beginning of this chapter? We now have tab completion and type checking all the way from the incoming command to the voter’s record. Assigning to the voter’s key also means that voting again replaces their previous choice instead of adding another vote.

Receiving commands

Our WebSocket handler currently just prints the messages it receives. With msgspec.json.decode we can turn them directly into command objects.

The handler only needs to decode the message, call its apply method within a database transaction and broadcast the updated polls. We pass the client’s IP address as the voter identifier and also use it with the command’s class name as transaction metadata.

Import our new module into app.py with from . import cmd and revisit the handler:

@app.websocket("/api/ws")
async def poll_updates(ws: WebSocket):
    await ws.accept()
    clients.add(ws)
    try:
        await ws.send_text(msgspec.json.encode(db.master.polls).decode())
        async for text in ws.iter_text():
            command = msgspec.json.decode(text, type=cmd.Vote)
            with db.kanta.transaction(
                user=ws.client.host,
                action=type(command).__name__,
            ):
                command.apply(ws.client.host)
            await broadcast(db.master.polls)
    finally:
        clients.discard(ws)

Adding new commands will be a matter of defining their structs and including them in the decoder’s accepted types.

Could we fsking get the polling done yet?!

Back in frontend/src/stores/master.ts, our submitVote action should no longer modify the vote count itself. Instead, it constructs a voting command and sends it over the WebSocket.

We still keep track of the polls we have voted on for the purposes of our interface.

    submitVote(id: string, index: number) {
      if (socket?.readyState !== WebSocket.OPEN) return

      socket.send(JSON.stringify({
        type: 'vote',
        poll_id: id,
        option: index,
      }))

      this.votedPollIds.push(id)
    },

Receiving the updated results requires no further work. Our existing WebSocket message handler updates the store, and Vue takes care of updating the interface.

Restore the answer buttons in PollCard.vue, removing their temporary disabling and reconnecting the click handler to master.submitVote(id, index).

Open two browser windows, create a poll and vote. Watch the results update in both windows. Since both windows have the same IP address, reloading and voting for another answer replaces your previous choice.

Live voting results in two browser windows

Restart the server and verify that the votes are preserved.

We assume well-behaved clients throughout this tutorial. Authentication, voting restrictions and comprehensive error handling are left for another day.

4. Exploring our database

Open master.kantadb in your editor. Yes, in your text editor!

Not only can we read the contents of our database, but we can also see how it came to be. Every poll created, every vote cast, along with when it happened, the action name and the client’s IP address. Need a rollback? Remove lines you want reverted (removing lines at the end is safe, in the middle be careful).

But let’s instead have a little fun with Kanta’s command-line tool:

kanta master.kantadb
Kanta CLI showing poll and vote history

Have you ever grepped your database’s transaction history?

kanta master.kantadb --grep Vote

What happened in the last hour?

kanta master.kantadb -r 1h

Or perhaps just dump the full JSON at some point in history?

kanta master.kantadb -r 4 --quiet --output=-

We can even go back in time and reconstruct earlier states of our database. See kanta --help for more options. Read only access via CLI tool is permitted even while the app is using it and has it locked.

You may use uv tool install kanta to have the command installed to your system, or use uvx kanta to run anywhere.

5. Optional: Deep dive into Kanta

There is one thing we could improve in our polling application. As we broadcast the entire polls dictionary to every connected browser, we are also revealing the IP addresses of everyone who voted.

Instead of using IP addresses directly, let’s derive voter keys from the IP address, the current minute and a random server secret. Votes from the same IP within a minute still replace each other, but the keys themselves reveal no IP addresses to other voters.

This gives us a good excuse to explore how a Kanta database evolves alongside our application.

Automatic schema migration

First, we need somewhere to keep our server secret. Import token_urlsafe from secrets and extend our Master structure:

class Master(msgspec.Struct):
    polls: dict[UUID, Poll] = {}
    secret: str = token_urlsafe(9)

But wait — our existing database doesn’t contain this field. Do we need to migrate it?

Save the file and watch the backend reload. Kanta automatically adds the missing field using its default value. Removing a field similarly removes it from the current database state. Many changes to our data model require no migration code at all.

We are generating a new secret at every startup, only to have Kanta restore the existing one when opening the database. For more expensive initialisation, Kanta provides @kanta.bootstrap, which runs only when creating a new database.

Custom log formatters

Did you notice the migrate:msgspec entry in your terminal? It just printed our new secret!

Kanta lets us customise how individual fields appear in logs. Add a formatter to db.py:

@kanta.logfmt(path="secret")
def hide_secret(value: str) -> str:
    return "<hidden>"

Formatters are also handy for making logs more readable, such as displaying a poll’s question instead of its UUID. By accepting prev and/or state arguments, a formatter gains access to the state dict before and after the logged change.

The Kanta CLI also respects our formatters when invoked with -k ./backend/poll_box/db.py (or poll_box.db).

Explicit database migrations

We would like to use binary hashes instead of IP address strings as our vote keys. Changing the type definition is easy enough, but what happens to all the votes already in our database?

Msgspec represents bytes as base64 strings in JSON. Our existing keys were not written in that format, so we need to transform them before loading the data into our new structures.

This is where explicit migrations come in. Create backend/poll_box/migrations.py:

def migrate_v1(data: dict) -> None:
    """Replace old voting records' IP addresses"""
    for poll in data["polls"].values():
        poll["votes"] = {
            f"{index:04x}": option for index, option in enumerate(poll["votes"].values())
        }

Migrations operate on raw JSON-like dictionaries, before msgspec decodes them into our structs. There is no need to maintain old versions of our Python structures.

Functions named migrate_v1, migrate_v2 and so on form an ordered sequence. Kanta tracks the database version, so we can simply modify the data in place without worrying about running the same migration twice.

Let Kanta know where our migrations live when constructing the database in db.py:

kanta = Kanta("master.kantadb", master, migrations="poll_box.migrations")

Save and inspect the database again. Our votes are still there, but their keys have been replaced with sequential strings that conveniently double as valid base64.

Working with binary data

With our existing data prepared, we can change the type of our vote keys from str to bytes:

class Poll(msgspec.Struct):
    question: str
    options: list[str]
    votes: dict[bytes, int] = {}

We are no longer limited to strings as keys, even though our database uses JSON internally. Recording of new votes still needs to be fixed:

# New imports
from datetime import datetime
from hashlib import sha256

# Updated apply function
class Vote(msgspec.Struct, tag="vote"):
    ...
    def apply(self, voter: str) -> None:
        # Vote key: hash of server secret, current minute and voter IP
        minute = datetime.now().strftime("%Y-%m-%dT%H:%M")
        key = sha256(f"{master.secret} {voter} {minute}".encode()).digest()[:3]
        # Store or update the vote
        master.polls[self.poll_id].votes[key] = self.option

Cast a few votes and have a look at your terminal to see them recorded.

While we work with binary keys in Python, msgspec takes care of their base64 representation both in our database and in the JSON sent to browsers. We haven’t had to touch the frontend!

Where we are now

We started with a small Vue application running entirely in the browser. We now have a multi-user application with live communication, persistent storage and an evolving database schema.

There is much more to Kanta than we could cover here. Explore the Kanta introduction and documentation to learn more.

One last thing remains: getting our application onto the Internet. In the next part, we will build and deploy it for production.