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.
Before introducing a database, we will give our Python data a proper structure and complete the voting functionality. We will then make the entire application state persistent.
1. Giving our data a structure
Our server currently stores polls as dictionaries. This works well for passing data between Python and JavaScript, but as we start working with the data in Python, we would like our editor to know what fields exist and what types they contain.
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. It handles conversion between native Python types and serialized formats such as JSON and MessagePack, and validates incoming data against our type definitions.
Add msgspec to our project:
uv add msgspec
Msgspec is also a core dependency of Kanta, so when starting a project with Kanta, there is no need to install msgspec separately. We are doing so here to explore its capabilities independently of the database.
Defining our data model
We already have TypeScript interfaces describing our polls and their options. Let’s give Python equivalent definitions.
Import msgspec in backend/poll_box/app.py:
import msgspec
Replace our global polls = {} with the following:
class Option(msgspec.Struct):
label: str
votes: int = 0
class Poll(msgspec.Struct):
question: str
options: list[Option]
class PollData(msgspec.Struct):
polls: dict[UUID, Poll] = {}
data = PollData()
These are ordinary Python objects with constructors generated from the field definitions. We can create an option with Option("Library") and access its vote count through option.votes.
The entire shared state of our application is now described by PollData. Notice that we can use actual UUID objects as dictionary keys rather than converting them to strings ourselves.
Unlike ordinary Python dictionaries, these structures give our editor enough information to provide field completion and detect many programming errors.
Receiving structured data
FastAPI already decodes the JSON body of our POST request into a dictionary. How do we turn that dictionary into a Poll object?
Msgspec provides a convert function for converting existing Python data into a specified type, validating its contents in the process.
Replace the create_poll endpoint:
@app.post("/api/polls/{poll_id}", status_code=201)
async def create_poll(poll_id: UUID, poll: dict):
if poll_id in data.polls:
raise HTTPException(409, "Poll already exists")
try:
new_poll = msgspec.convert(poll, type=Poll)
except msgspec.ValidationError as error:
raise HTTPException(422, str(error)) from error
for option in new_poll.options:
option.votes = 0
data.polls[poll_id] = new_poll
await broadcast(data.polls)
return {"id": str(poll_id)}
Msgspec converts the nested dictionaries into Option and Poll objects, checking their types and required fields. The server also initializes the vote counts, rather than accepting votes supplied by the client.
Validation takes place when converting or decoding data. Ordinary construction and modification of structs do not perform automatic type validation, allowing our Python code to work with them efficiently.
Sending structured data
Our browsers still expect the same JSON as before. However, the standard JSON encoder used by FastAPI’s WebSocket methods does not understand our new structs or UUID keys.
Msgspec has its own JSON encoder that handles both. We can also decode JSON directly into a specified Python type.
The encoder produces UTF-8 bytes. As we are communicating with the browser using WebSocket text messages, we need to turn those bytes into a Python string before sending them.
In our broadcast function, replace the send_json call with:
await ws.send_text(msgspec.json.encode(msg).decode())
Similarly, change the initial message sent in our WebSocket handler:
await ws.send_text(msgspec.json.encode(data.polls).decode())
We can also use msgspec to decode incoming messages. Replace await ws.receive_json() with:
msg = msgspec.json.decode(await ws.receive_text())
Although our Python data now contains structs and UUID objects, msgspec encodes them as ordinary JSON objects and strings. Our Vue application does not need to know about this change.
Try creating polls in two browser windows again. Everything should work exactly as before, but we now have structured and validated data on the server.
2. Casting votes
We can create polls and share them with other browsers. Now we want to let everyone participate.
When someone votes, we must not send an entire modified poll back to the server. Someone else may have voted in the meantime, and we would risk overwriting their vote.
Instead, we only need to tell the server which poll and which answer we voted for. The server can then increment its current vote count.
Defining a command
Just as we defined structures for our application data, we can define structures for the messages we exchange over WebSocket.
Add another struct alongside our existing definitions in app.py:
class Vote(msgspec.Struct, tag="vote"):
poll_id: UUID
option: int
The tag adds a type field to the JSON representation, identifying the kind of message being sent.
Our voting command will look like this:
{
"type": "vote",
"poll_id": "8bd203fe-81be-49b2-b8da-7af250ea239c",
"option": 0
}
If we introduce other commands later, msgspec can use these tags to distinguish between different message types.
Processing votes
Our WebSocket handler currently prints the messages it receives. We can now decode them directly into Vote objects, ready to use in Python.
We also want to remember which polls have already been voted on during a connection. Add a local variable inside poll_updates, before the try block:
voted: set[UUID] = set()
Unlike our shared data variable, this set belongs to an individual WebSocket connection.
Replace the contents of the receive loop:
while True:
try:
vote = msgspec.json.decode(
await ws.receive_text(), type=Vote
)
except msgspec.DecodeError:
continue
poll = data.polls.get(vote.poll_id)
if poll is None or vote.poll_id in voted:
continue
if not 0 <= vote.option < len(poll.options):
continue
poll.options[vote.option].votes += 1
voted.add(vote.poll_id)
await broadcast(data.polls)
Msgspec checks that the message has the expected structure and converts the poll ID into a UUID. We then check that the poll and selected option exist and that this connection has not already voted.
Notice how much easier it is to work with our structured data. Incrementing the vote count is simply an ordinary Python attribute modification.
Sending votes from Vue
In frontend/src/stores/polls.ts, our original submitVote action incremented the vote count directly in Pinia. Now we only need to send a command to the server.
Replace the action:
submitVote(id: string, index: number) {
if (this.votedPollIds.includes(id)) return
if (socket?.readyState !== WebSocket.OPEN) return
socket.send(JSON.stringify({
type: 'vote',
poll_id: id,
option: index,
}))
this.votedPollIds.push(id)
},
We still remember which polls we have voted on for the purposes of our interface, but we leave the actual vote counts to the server. The updated polls arrive through our existing WebSocket message handler.
In PollCard.vue, remove the temporary disabled attribute from the answer buttons and restore their click handler:
@click="polls.submitVote(id, index)"
Open the application in two browser windows and create a poll. Vote for different answers in each window and watch the results update.
We now have a working multi-user polling application.
For simplicity, we restrict voting to once per poll per connection. Reconnecting allows another vote. Identifying individual users and implementing reliable voting restrictions are beyond the scope of this tutorial.
3. Making our data permanent
Create a few polls, cast some votes and restart the development server.
Everything is gone.
Our entire application state still lives in a Python variable. We could serialize it to a file after every modification and load it again at startup, but we would also need to handle interrupted writes, failures and the growing cost of repeatedly writing the entire collection.
These are problems that a database can solve for us.
Introducing Kanta
Kanta is an embedded NoSQL database designed for asynchronous Python applications. It keeps application data in memory and records modifications in an append-only file, restoring the state when the application starts again.
Unlike conventional database systems, Kanta works directly with our msgspec structures. There is no separate database server, query language or additional data model to maintain.
Add Kanta to our project:
uv add kanta
Import Kanta in app.py:
from kanta import Kanta
Replace data = PollData() with:
db = Kanta("polls.kantadb", PollData())
The PollData object defines the database’s structure and its initial state when creating a new database.
Opening and closing the database
Our generated FastAPI application already has a lifespan handler, which prepares the frontend when the server starts.
We also need to open the database at startup and close it properly at shutdown. Extend the existing handler:
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator:
async with db:
await frontend.load()
yield
The database remains open throughout the application’s lifetime. When the application shuts down, leaving the context closes the database and finishes pending writes.
Reading from the database
Kanta makes its current state available through db.data. This is still a PollData object, so we can access its contents just as we did before.
Replace all references to data.polls in our HTTP and WebSocket handlers with db.data.polls.
There is no query to execute and no conversion from database records into application objects. Reading from the database is simply accessing Python objects already in memory.
Recording changes
Reading data requires no special operation, but Kanta needs to know when we are making changes that should be recorded.
We group modifications into a transaction. If the transaction succeeds, Kanta records the changes. If an exception occurs within it, the changes are rolled back.
In create_poll, replace the assignment that stores the new poll with:
with db.transaction(action="create_poll") as state:
state.polls[poll_id] = new_poll
Similarly, in the WebSocket receive loop, replace the line incrementing the vote count with:
with db.transaction(action="submit_vote") as state:
state.polls[vote.poll_id].options[vote.option].votes += 1
Leave the broadcasts outside the transactions.
Transactions are synchronous. We modify ordinary Python objects, and Kanta determines what has changed and records those changes in the background.
A transaction can also contain several related modifications that must succeed or fail together. This allows us to maintain consistent data without having to implement our own recovery mechanisms.
That is all we need to change to make our application persistent. Our Vue application, HTTP API and WebSocket messages remain exactly as they were.
Testing persistence
Create some polls and cast a few votes. Stop the development server normally, start it again and open the application.
This time, our polls and vote counts are still there!
You should also find a new file, polls.kantadb, in the project’s working directory. Add it to .gitignore, as it contains application data rather than source code.
Exploring the database
Open polls.kantadb in your editor. Unlike many database formats, Kanta’s default format is human-readable, with JSON records separated by newlines.
Rather than storing only the latest state of our application, the database contains a history of its changes. The action names we provided in our transactions help us identify what happened.
Kanta also comes with a command-line tool for exploring this history. From the project directory, run:
uv run kanta polls.kantadb
We can inspect the transactions and see which values changed.
When did you last grep your database’s transaction history?
uv run kanta polls.kantadb --grep submit_vote
Or look at changes from the last hour:
uv run kanta polls.kantadb --range 1h
We can also reconstruct the current state and export it as JSON:
uv run kanta polls.kantadb --quiet --output -
Explore the other available options with:
uv run kanta --help
The CLI can also reconstruct historical states, making the transaction history useful for investigating problems and understanding how our data has evolved.
Where we are now
We have built a complete polling application with a reactive Vue interface, shared application state in FastAPI, live WebSocket communication and persistent storage.
The same structured Python objects serve as our application data, our database schema and the source of the JSON sent to our browsers.
Our application is ready to run outside the development environment. In the next part, we will build and deploy it as a Python package.