Part 4: Structured data and database persistence

In Part 3, we connected our Vue application to FastAPI. Everyone sees the same poll and receives live results over a WebSocket. But how permanent is our shared state?

Cast a vote and reload the page. The vote count is still there, but the application lets you vote again. Now stop the development server, start it again and reload the page. Even the vote count has disappeared.

Remember the three kinds of state we introduced in Part 3:

  • The interface state in Pinia belongs to the browser page.
  • The local variable voted belongs to a running WebSocket handler. A new connection starts with a new variable.
  • Our shared Python variable poll belongs to the FastAPI process. Restarting the process recreates the original example poll.

We will make the poll data permanent, remember votes across connections and bring back the creation and editing features from Part 2.

Pinia state is lost on page reload, the WebSocket voted flag is lost with its connection, and in-memory FastAPI data is lost on server restart; local storage and Kanta persist

1. Giving our data a structure

Look at the line in our WebSocket handler that increments a vote count:

poll["options"][option]["votes"] += 1

We have to know which keys exist in the dictionaries, what kind of value each contains and how they are nested. Neither the dictionaries nor their type annotations currently describe the structure of a poll.

This will become increasingly inconvenient as we bring back more functionality. If we accidentally write "vote" instead of "votes", for example, nothing in our data definition tells the editor that we have made a mistake.

Python has several ways to represent structured data. If you have used dataclasses or Pydantic models before, the idea behind msgspec structs will be familiar: we describe the fields of an object using type annotations, and the library generates the constructor and other common methods for us. We also get serialization and validation of incoming data.

Install msgspec in our project:

uv add msgspec

In backend/voting_app/app.py, define the two structures that make up a poll:

import msgspec
class Option(msgspec.Struct):
    label: str
    votes: int = 0


class Poll(msgspec.Struct):
    id: str
    question: str
    options: list[Option]

An option has a label and an integer vote count, which defaults to zero. A poll contains a list of these options. We can now construct an option with Option(label="Library") and refer to its properties using ordinary attribute access, such as option.votes.

For the complete application we will need a collection of polls. Rather than giving each poll its own global variable, define one object to contain all our shared data:

class PollData(msgspec.Struct):
    polls: dict[str, Poll] = msgspec.field(default_factory=dict)

We still use a dictionary here, because the poll IDs are dynamic keys, not predefined fields. The type annotation tells us that every key is a string and every value is a Poll. The default factory gives each new PollData its own empty dictionary.

Replace the original global poll dictionary with the following object:

data = PollData(polls={
    "demo": Poll(
        id="demo",
        question="Where should we meet?",
        options=[Option("Library"), Option("Community hall")],
    ),
})

Converting between Python objects and JSON

Structs are ordinary Python objects, but our browsers still expect the same JSON as before. We don’t need to change the frontend just because we have changed how the server represents its data.

Msgspec provides several useful conversions. To see how they work, open a Python interpreter with uv run python:

import msgspec


class Option(msgspec.Struct):
    label: str
    votes: int = 0


option = Option("Library")
msgspec.to_builtins(option)
# {'label': 'Library', 'votes': 0}

msgspec.json.encode(option)
# b'{"label":"Library","votes":0}'

msgspec.json.decode(b'{"label":"Library"}', type=Option)
# Option(label='Library', votes=0)

Try decoding a message in which votes is a string instead of an integer. Msgspec raises a ValidationError. It also checks nested structures and required fields. We can perform the same kind of conversion on already-decoded Python data:

msgspec.convert({"label": "Library"}, type=Option)
# Option(label='Library', votes=0)

Conversions can also be configured to accept some alternative representations, for example msgspec.convert({"label": "Library", "votes": "2"}, type=Option, strict=False) converts the numeric string to an integer. We will keep the default strict validation for incoming application messages.

Unlike Pydantic models, ordinary construction and attribute assignment on a msgspec struct do not automatically check the annotated types. Validation happens when we decode or convert incoming data. This allows our trusted application code to work directly with the objects without repeated validation.

Msgspec encodes an Option struct as JSON, decodes valid JSON into an Option, and rejects a non-integer vote count

Using the structures in FastAPI

Add a small helper for turning our collection of polls into JSON-compatible Python objects:

def poll_list():
    return msgspec.to_builtins(list(data.polls.values()))

Use it in our existing HTTP endpoint:

@app.get("/api/polls")
async def list_polls():
    return poll_list()

In the WebSocket handler from Part 3, replace both occurrences of "polls": [poll] with "polls": poll_list(). Inside the receive loop, after reading the message, retrieve our example poll and use attribute access in place of dictionary keys:

poll = data.polls["demo"]

The option range check becomes 0 <= option < len(poll.options) and the increment inside async with lock becomes:

poll.options[option].votes += 1

Reload the browser. The example poll and live voting should work exactly as before. Our application still runs entirely in memory, but it now has a well-defined data model that we can use independently of any database or web framework.

2. Making our data permanent

Restart FastAPI once more. The structs have made our code easier to work with, but they have not solved the problem of losing our data.

We could serialize our PollData object to JSON and write it to a file after each change. However, we would need to deal with interrupted writes, restoring the previous state at startup and keeping related modifications together. As our data grows, rewriting the whole file after every vote would also become wasteful.

These are problems that a database can take care of for us.

Kanta is an embedded NoSQL database for Python applications. It keeps our data in memory and records changes in a file, so there is no separate database server to install or connect to. On startup, it reconstructs the saved state from that file.

One particularly useful property of Kanta is that it can work with the msgspec structures we have just created. We do not have to define tables, write queries or introduce an object-relational mapper (ORM) to translate between our application objects and a database schema. Our existing PollData is already the schema.

uv add kanta

Import Kanta and change the initialization of data into a database initialization, using the very same PollData object:

from kanta import Kanta
db = Kanta("polls.kantadb", PollData(polls={
    "demo": Poll(
        id="demo",
        question="Where should we meet?",
        options=[Option("Library"), Option("Community hall")],
    ),
}))

The example data is used when the database is first created. On subsequent openings, Kanta loads the saved data instead. Our previous in-memory votes are not imported.

Opening and closing the database

FastAPI already uses a lifespan function in our project to load the frontend at startup. The database is another resource whose lifetime should match the lifetime of the application.

Extend the existing lifespan function:

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

Entering the context opens the database; leaving it during an orderly shutdown closes the database and finishes pending writes.

Add /polls.kantadb to .gitignore if the development server is run from the project root. This file is application data, not source code.

Reading and writing data

Our database exposes its current state as db.data. Since that state is still a PollData object, the changes required in our application are very small.

In poll_list, read from the database instead of our old global variable:

def poll_list():
    return msgspec.to_builtins(list(db.data.polls.values()))

Similarly, change the example poll lookup in the WebSocket handler to poll = db.data.polls["demo"].

But what happens when we change a field? Kanta needs to know which changes belong together and when they are finished. We mark a group of modifications using a transaction.

In the WebSocket handler, inside the existing async with lock block, replace the vote increment with:

with db.transaction(action="submit_vote") as state:
    state.polls["demo"].options[option].votes += 1

Leave the voted = True assignment and the existing broadcast after the transaction. There is no need to change the code in Vue.

A successful transaction records the changes for persistence. If an exception escapes the transaction block, Kanta rolls back the changes. Transactions are synchronous; keep asynchronous operations such as WebSocket sends outside them.

Cast a vote, stop the development server normally, start it again and reload the application. This time the vote count survives!

With Kanta’s default JSON format, we can also open polls.kantadb in a text editor and inspect the recorded changes. The database writes changes in the background, so they may not appear in the file immediately.

3. Remembering who has voted

Our vote counts are permanent now, but reloading the browser still allows us to vote again. The local voted variable still disappears when the WebSocket disconnects.

A database alone does not solve this problem. Even if we stored that variable, how would we know which browser it belonged to when a new connection arrived?

We need an identifier that survives across connections. For our anonymous application, we can generate a random ID in the browser and keep it in local storage. The browser will present the same ID when reconnecting.

This is not authentication: a user can clear local storage or supply a different ID to vote again. We are demonstrating persistent browser identity, not enforcing one vote per person.

Storing voting history

Extend our existing PollData structure with a new field:

class PollData(msgspec.Struct):
    polls: dict[str, Poll] = msgspec.field(default_factory=dict)
    voted: dict[str, list[str]] = msgspec.field(default_factory=dict)

The keys of voted are browser IDs. Each value lists the IDs of polls that browser has voted on. We use a list of poll IDs rather than a single boolean because we are about to support multiple polls.

The new field has an empty default, so it can also be initialized when reading our existing database. Votes cast before we introduced this field cannot be attributed to individual browsers and remain anonymous in the totals.

PollData contains a dictionary of polls and a separate voting history mapping browser IDs to poll IDs

Beside the module-level socket declaration in frontend/src/stores/polls.js, add a helper to obtain the browser ID:

function getVoterId() {
  let id = localStorage.getItem('voting-app:voter')
  if (!id) {
    id = crypto.randomUUID()
    localStorage.setItem('voting-app:voter', id)
  }
  return id
}

In connect, after creating the WebSocket URL and setting its protocol, add the ID as a query parameter before constructing the WebSocket:

url.searchParams.set('voter', getVoterId())

The browser ID is deliberately local to this browser profile and origin. crypto.randomUUID() is available on localhost and secure (HTTPS) origins.

Describing a WebSocket message

Our previous vote messages contained just an option index. With multiple polls, that index will no longer be sufficient to identify a vote.

In the backend, define the message we expect from a voting client:

class VoteInput(msgspec.Struct):
    poll_id: str
    option: int

Change the message sent by submitVote in Pinia to include the poll ID:

socket.send(JSON.stringify({ poll_id: poll.id, option }))

We can use msgspec to decode and validate this message, instead of manually checking for dictionaries, keys and integers as we did in Part 3.

Returning each browser’s voting history

Previously, we maintained a set of WebSocket connections and sent a voteAccepted flag to the connection that cast the vote. That only tells us about the latest operation. We now want each browser to receive its own complete voting history, including when it first connects.

Change the set of connections to a dictionary associating each WebSocket with its browser ID:

clients: dict[WebSocket, str] = {}

Keep the existing lock = Lock(). Extract the snapshot and broadcast operations into reusable functions, to be called while holding that lock:

async def send_snapshot(client: WebSocket, voter: str, polls: list[dict]):
    await client.send_json({
        "polls": polls,
        "votedPollIds": db.data.voted.get(voter, []),
    })


async def broadcast_polls():
    polls = poll_list()
    for client, voter in tuple(clients.items()):
        try:
            await send_snapshot(client, voter, polls)
        except (WebSocketDisconnect, OSError, RuntimeError):
            clients.pop(client, None)

The poll data is identical for everyone. Only the voting history differs. We do not send the entire database to every browser, since other browsers’ IDs and voting histories are not needed by the interface.

Now replace the WebSocket handler. FastAPI can obtain query parameters from a WebSocket URL just as it does from an HTTP URL. Annotating voter as a UUID allows FastAPI to validate the identifier before the handler runs.

from uuid import UUID
@app.websocket("/api/ws")
async def poll_updates(websocket: WebSocket, voter: UUID):
    await websocket.accept()
    voter_id = str(voter)

    try:
        async with lock:
            await send_snapshot(websocket, voter_id, poll_list())
            clients[websocket] = voter_id

        while True:
            raw = await websocket.receive_text()
            try:
                vote = msgspec.json.decode(raw, type=VoteInput)
            except msgspec.DecodeError:
                continue

            async with lock:
                poll = db.data.polls.get(vote.poll_id)
                if poll is None or not 0 <= vote.option < len(poll.options):
                    continue
                if vote.poll_id in db.data.voted.get(voter_id, []):
                    continue

                with db.transaction(action="submit_vote") as state:
                    state.polls[vote.poll_id].options[vote.option].votes += 1
                    state.voted.setdefault(voter_id, []).append(vote.poll_id)

                await broadcast_polls()

    except WebSocketDisconnect:
        pass
    finally:
        clients.pop(websocket, None)

There are two related changes in our transaction now: incrementing the vote count and recording that this browser has voted. If we only recorded one of them, the data would become inconsistent. Putting them in the same transaction ensures that they succeed or fail together.

A valid vote increments the count and records voting history in one Kanta transaction before broadcasting the snapshot

The WebSocket handler still has local variables, but we no longer rely on them to store permanent voting history. Invalid or duplicate vote messages are ignored as in Part 3; a production protocol could return explicit error messages.

Finally, update connection.onmessage inside the existing Pinia connect action to use the voting history provided by the server instead of the old voteAccepted flag:

connection.onmessage = event => {
  if (socket !== connection) return

  const message = JSON.parse(event.data)
  this.replacePolls(message.polls)
  this.votedPollIds = message.votedPollIds
}

Because onmessage is an arrow function, this still refers to the Pinia store inside this callback.

We can keep resetting votedPollIds at the start of connect; the first snapshot restores the server’s record. No changes to the vote count or voting history should be made in submitVote itself.

Try voting and reloading the page. The application should now remember that you have voted, even after restarting FastAPI. Open another tab of the same browser and verify that it shares your voting history. To simulate a different voter, use a private window or a different browser profile, not just another tab.

4. Creating new polls

So far we have been working with a single example poll. Restore the PollForm import and <PollForm /> tag in App.vue from Part 2. Keep the onMounted and onUnmounted WebSocket hooks that we added in Part 3.

Try creating a poll. Our original creation action can still construct a poll locally in Pinia, but that poll disappears when we reload the page or receive the next WebSocket snapshot. The server has no record of it.

We already have an open WebSocket for voting and receiving updates. We could extend its message protocol to handle poll creation too, but an HTTP request is a convenient fit for an independent operation with a success or error response. We will use HTTP for creating and editing polls and the WebSocket to deliver their results to everyone.

What data does the server need to create a poll? A question and a list of option labels. The server should generate the ID and initialize the vote counts itself.

Define another msgspec structure in the backend:

class PollInput(msgspec.Struct):
    question: str
    options: list[str]

This structure describes what a client may submit, rather than the full object we store in the database.

Validating an HTTP request body

In Part 3, we used path and query parameters to transmit individual values. Now we want to send a JSON object in the body of the request.

We can use FastAPI’s Request object to obtain that body and decode it directly with msgspec. Type validation is not quite sufficient: an empty string is still a perfectly valid string, but it is not a useful poll question. We need to check our application rules as well.

Import Request and HTTPException from fastapi (the latter may already be imported from Part 3):

async def read_poll_input(request: Request) -> PollInput:
    try:
        data = msgspec.json.decode(await request.body(), type=PollInput)
    except msgspec.DecodeError as error:
        raise HTTPException(422, str(error)) from error

    data.question = data.question.strip()
    data.options = [label.strip() for label in data.options]

    if not data.question or len(data.options) < 2 or not all(data.options):
        raise HTTPException(422, "A poll needs a question and two or more non-empty options")

    return data

We validate on the server even though Vue already checks the form. The browser’s form is only one way of calling our API; someone could send an invalid request directly. This helper will also be useful when editing a poll.

Creating the database object

Import uuid4 alongside UUID and add a POST endpoint:

@app.post("/api/polls", status_code=201)
async def create_poll(request: Request):
    data = await read_poll_input(request)
    poll = Poll(
        id=str(uuid4()),
        question=data.question,
        options=[Option(label) for label in data.options],
    )

    async with lock:
        with db.transaction(action="create_poll") as state:
            state.polls[poll.id] = poll

        await broadcast_polls()

    return {"id": poll.id}

The same transaction and broadcast mechanism now serves both our WebSocket voting handler and our HTTP creation endpoint. Both use the same lock to order changes and snapshots, and neither requires a separate database model.

Test the endpoint using the browser console before modifying the frontend form:

const response = await fetch('/api/polls', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    question: 'What should we eat?',
    options: ['Pizza', 'Pasta', 'Salad'],
  }),
})
await response.json()

The new poll should appear in the interface automatically, since the frontend is already listening for snapshots. Vote on either poll. Unlike in Part 3, voting on one no longer prevents you from voting on the other.

Try sending a request with just one option. It should fail with HTTP status 422 and leave the database unchanged.

Connecting the creation form

In frontend/src/stores/polls.js, replace the original local createPoll action:

async createPoll() {
  if (!this.canCreate) return

  const response = await fetch('/api/polls', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      question: this.question,
      options: this.options.map(label => label.trim()).filter(Boolean),
    }),
  })

  if (!response.ok) throw new Error('Could not create poll')

  this.question = ''
  this.options = ['', '']
},

Notice what is missing: we do not push the created poll into the local polls array. The WebSocket already delivers the updated collection to all clients, including the one that sent the POST request. Updating the array independently could introduce duplicates.

The only state we change directly is our own creation form, and only after a successful response. The form remains local while the user is typing.

Open two browser windows and create a poll in one. It should appear immediately in both and survive a server restart.

A poll created through FastAPI appears through the WebSocket snapshot and the local creation form resets

5. Editing polls without overwriting votes

Restore the editing form, its <template v-else> wrapper and the Edit button from Part 2. Keep the separate results condition from Part 3: results should appear whenever any option has votes, not only when this browser has voted.

Just as with creation, saving an edit currently only modifies the local copy of a poll.

There is an additional complication now. Imagine starting to edit a poll while someone else casts a vote. If we sent our entire edited copy back to the server, we could overwrite the vote counts with older values.

Instead, send only the question and option labels. We already have a structure and validation function for exactly this information.

@app.put("/api/polls/{poll_id}")
async def edit_poll(poll_id: str, request: Request):
    data = await read_poll_input(request)

    async with lock:
        poll = db.data.polls.get(poll_id)
        if poll is None:
            raise HTTPException(404, "Poll not found")
        if len(data.options) != len(poll.options):
            raise HTTPException(422, "Changing option count is not supported")

        with db.transaction(action="edit_poll") as state:
            edited = state.polls[poll_id]
            edited.question = data.question
            for option, label in zip(edited.options, data.options, strict=True):
                option.label = label

        await broadcast_polls()

    return {"id": poll_id}

We update the labels of the existing options rather than replacing the option objects. Their vote counts remain unchanged.

For simplicity, editing is limited to the question and existing option labels. Since votes refer to options by their index, we must not add, remove or reorder options in the editing form. Changing what an option means after voting has begun is also undesirable in a real voting system; our demonstration supports wording corrections, not changing the meaning of a vote.

Replace the existing saveEdit action with an asynchronous API version. Keep the guard and validation from Part 2, but send only the question and labels instead of modifying the shared poll:

async saveEdit() {
  if (!this.editing) return

  const poll = this.polls.find(poll => poll.id === this.editing.pollId)
  if (
    !poll ||
    !this.editing.question.trim() ||
    this.editing.options.some(option => !option.label.trim())
  ) {
    return
  }

  const response = await fetch(`/api/polls/${poll.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      question: this.editing.question,
      options: this.editing.options.map(option => option.label.trim()),
    }),
  })

  if (!response.ok) throw new Error('Could not edit poll')
  this.editing = null
},

Our startEdit action already initializes this.editing.options with independent copies using poll.options.map(option => ({ ...option })). Keep that copying: a WebSocket update should not replace the values we are currently editing, and typing into the form should not modify the shared poll before saving.

Again, we do not change the shared poll in the HTTP action. We let the next WebSocket snapshot update the interface. The response only tells us whether we can close the editing form.

Open a poll for editing in one browser and cast a vote from a different browser profile. Save the edit. Both browsers should display the new wording without losing the vote that was cast while the edit was in progress.

Where we are now

Try using the completed application with two different browser profiles. Create polls, vote on each of them, correct their labels and watch updates appear in both browsers. Restart the development server and check that the polls, vote counts and each browser’s voting history are restored.

Votes from two browser profiles appear in the same live results while each keeps its own voting history

Our application still has different kinds of state, but now each has a purpose:

State Where it lives Lifetime
Unfinished forms and vote selections Pinia Browser page
Anonymous browser ID Browser local storage Across page reloads
Active connections and lock FastAPI memory Server process / WebSocket connection
Polls, vote counts and voting history Kanta Across server restarts

The database is not a replacement for the Pinia store or for the WebSocket connection. It solves a different problem: preserving our shared application data. Msgspec gives that data a structure which we can use throughout the application, FastAPI provides operations on it, and Vue makes it interactive.

Vue and Pinia keep local drafts, FastAPI handles HTTP operations and WebSocket broadcasts, and Kanta persists PollData in polls.kantadb

The six browser/API milestone tests cover creation, voting, editing, reload recovery, independent browser identities, live synchronization and invalid input. With the application running, execute them from voting-app/frontend:

npx playwright test e2e/polls.spec.js

We have kept the implementation deliberately small: one FastAPI worker owns the embedded database, every update sends a full snapshot, and a disconnected browser needs a page reload to reconnect. The anonymous ID is not a secure voting identity, and concurrent edits use the last saved wording. These limitations are acceptable for our demonstration, but would need further design for a real voting service.

In Part 5, we will turn the completed application into a self-contained Python package and run it independently of our development checkout.