Case study 9 min read

Becan: building a voice tutor for university students

How I built Becan, a voice tutor for university courses: a Next.js app, an Express API, LiveKit rooms, plan limits, usage metering and authentication.

Becan is a voice tutor for university students. A student picks a course their university teaches and opens a chapter. The tutor explains it out loud, writes on a board as it goes, moves through the chapter’s slides, and asks questions to check understanding. The student can interrupt at any point, by voice or by text. Tutoring is available in Arabic and English.

The original product is live at Becan. The minified version is live at Becan-moaz-coe.

This post describes a reduced version of that website. It keeps the core web app and API and leaves some parts of the full product out. I built the original website entirely myself, and I built this reduced version too. The differences are:

  • Google sign-in is removed. Accounts use email and password only.
  • The admin dashboard is a separate app and is not included. The admin endpoints in the API are included.
  • The AI tutor agent is a separate private service and is not included.

The rest of the post explains how the pieces fit together and why I made each decision the way I did.

Architecture overview

The stack is Next.js 16 with React 19, TypeScript and Tailwind CSS for the web app, and Express 5 with TypeScript, PostgreSQL, Drizzle ORM, Better Auth and Zod for the API. LiveKit rooms carry the audio and the board messages.

Browser ──► Web app (Next.js) ──► API (Express) ──► PostgreSQL
   │                                  │  ▲
   │                       mints tokens│  │signed webhooks
   │                                  ▼  │
   └────── audio + board messages ──► LiveKit ◄──► Tutor agent

Three rules shape the design:

  1. The browser only talks to the web app. Next.js proxies /api/auth/* and /api/v1/* to the Express API. The session cookie is therefore first-party, which avoids third-party-cookie problems, and CORS only needs to allow the known app origins. The alternative was to let the browser call the API on its own domain. That works until a browser blocks the cross-site cookie, and then sign-in breaks for some users in ways that are hard to reproduce.
  2. The API owns all state: accounts, sessions, the course catalog, enrollments, plans and usage. It is layered as routes, controllers, services and repositories, so HTTP details stay out of the business rules and SQL stays out of both.
  3. This code never calls the tutor agent directly. The web app and the agent meet inside a LiveKit room. Neither needs to know where the other runs.

Starting a tutor session

The student asks the API for a session:

POST /api/v1/livekit/token

Inside one database transaction, the API checks the enrollment, checks the plan’s remaining allowance while holding a lock on the student’s plan row, records a study session, and returns a LiveKit room token. The lock matters: without it, two requests sent at the same moment could both read “one session left” and both succeed.

The token carries participant attributes: the course, the chapter, the language, and how many seconds the session may last. That attribute set is the contract with the agent. The agent joins the same room, reads the attributes, and teaches. When the granted time is used, the agent ends the session.

I chose attributes on the token over a separate call from the API to the agent. A direct call would couple the two services, and it would need its own failure handling. With the token, the API only has to be correct about what it grants, and the agent only has to read it.

The live session screen

The screen has three areas: a lessons column, the board, and the chapter’s slides. The slides are a PDF rendered in the browser and loaded lazily, page by page, so a long chapter does not block the first paint. Slides and lesson lists are stored in object storage and served through a server-side route.

The agent drives the page with control messages sent through the room:

  • write on the board
  • go to a slide
  • set the lesson and topic
  • show an understanding check with choices
  • announce that the session is ending

All session state lives in a single reducer. The phase shown on screen (connecting, speaking, thinking, listening, question, ending) is not stored separately. It is derived from the room connection and the agent’s state. Storing it would mean keeping it in sync with two other sources, and when they disagree the screen shows the wrong phase. Deriving it removes that class of bug.

The slides follow the tutor, but a student can pick a slide to look at. The pick holds until the tutor moves to another slide, at which point the tutor wins. The alternative, locking the student to the tutor’s slide, is simpler but frustrating when you want to look back at a formula.

Plans and usage limits

There are three plans: Free, Lite and Pro. Each sets four limits:

  • sessions per 30-day period
  • minutes per period
  • a maximum length for one session (30 minutes)
  • how many courses a student can be enrolled in

Limits are enforced when a session starts, not during it. The API grants the session a time budget equal to the smaller of “minutes left” and “longest session”. Cutting a session off mid-explanation from the API side would need a live channel to the agent. A grant fixed at the start needs none.

Measuring usage without trusting the client

Usage is measured from LiveKit’s signed webhooks (participant joined and participant left). It is never taken from anything the browser reports, because the student controls the browser.

Usage is also derived from the study session rows instead of being kept in a counter. Nothing has to reset at the end of a period and no scheduled job runs. The period is just a date filter on the rows.

One failure case needed a deliberate rule. If a “left” event never arrives, the session is charged its full grant. A lost webhook can therefore never charge a student more than the session was allowed to use. The alternative, leaving the session open and unbilled, would let a dropped webhook give free time.

Authentication

Authentication is built on Better Auth, mounted in Express. Sessions are stored in PostgreSQL and carried by an HTTP-only cookie that lasts 30 days and is refreshed daily.

Sign-up has two steps. The first collects name, email and password. The second collects phone number, university and major.

The account features are:

  • TOTP two-factor authentication with backup codes, and a temporary lock after repeated wrong codes
  • password reset by an emailed link, which signs the account out everywhere
  • change email, confirmed from the new address
  • change password
  • account deletion, with a typed confirmation plus the password

A few decisions are worth explaining.

Sessions are read from the database, not the cookie cache. Protected routes look the session up in PostgreSQL on every request. This costs one query, and in return a ban, a role change or a revoked session takes effect on the very next request. With a cookie cache, a banned account would keep working until the cache expired.

Account rules live in database hooks. A mobile number must be valid and unique, and the major must belong to the chosen university. Putting these in hooks means they hold no matter which code path writes the row. Validation only in the sign-up form would leave every other path, such as an email change or an admin edit, unprotected.

Rate limits are stored in the database. They are set per endpoint. In-memory counters would reset on each deploy and would not be shared between instances, so a limit of five attempts would quietly become five per instance.

Emails are sent without blocking the response. If the response waited for the email, a request for an address that has an account would take longer than one for an address that does not, and that timing difference would reveal which addresses are registered.

The web app guards pages twice. A fast cookie check redirects signed-out visitors immediately. Then, before each protected page renders, the app checks the session with the API. The first check is cheap but can be wrong. The second is authoritative.

The admin side of the API

Admin is a role on the same account, not a separate kind of user. Routes check a permission (“may this account do X”), never a role name, so adding a role later does not mean editing every route.

Every admin route requires the permission and two-factor authentication enabled on the account. Removing an account or changing a role also requires a session created in the last ten minutes, so a stolen long-lived session cannot do the most damaging things.

Every admin action is written to an audit log. Removing an account scrubs that person’s details from earlier log entries, so the log stays useful without keeping personal data for someone who asked to be deleted.

The admin endpoints cover:

  • account search
  • enrollments
  • usage
  • study sessions
  • sending a password reset
  • an insights endpoint (sign-ups, active students, sessions and study time over 7, 30 or 90 days)
  • the audit log

The dashboard that uses them is a separate app and is not part of this code.

API design

All routes live under /api/v1 and speak JSON only. Errors have one shape, with a stable code that the web app maps to what the student sees. The codes include NOT_ENROLLED, SESSIONS_USED_UP and MINUTES_USED_UP:

{
  "error": {
    "code": "MINUTES_USED_UP",
    "message": "No minutes left in this period."
  }
}

The web app switches on the code, not on the message text, so the wording can change without breaking the interface, and the same code can be shown in Arabic or English.

Enrolling is idempotent. It returns 201 when the enrollment is created, 200 when the student is already enrolled, and 409 when the plan’s course limit is full. A client that retries after a timeout gets a correct answer instead of an error. Un-enrolling ends the enrollment rather than erasing it, so past study sessions still point to a real record.

Tests

The project has 30 test files, written with Vitest and Supertest. They run against a real PostgreSQL database, not mocks. Many of the rules above live in the database (row locks, hooks, constraints), and a mock would not exercise any of them.

What I would highlight

Two parts were the hardest and the most interesting.

Measuring usage without trusting the client. The browser is the one place the student controls, so it cannot be a source of billing facts. Granting a budget at the start, measuring from signed webhooks, deriving usage from rows, and charging the full grant when a webhook is lost together mean the limits hold without any cooperation from the client, and without a counter that can drift.

Driving the whole session screen from the agent’s messages. The screen has no logic of its own about what to teach. The agent sends control messages, a single reducer applies them, and the phase is derived from the room. That keeps the web app small and puts the teaching behavior in one place. It also means the message set between the agent and the page is an interface that has to stay stable.

I built the original Becan website entirely by myself, and I built this reduced version as well. The original is live at Becan.