nastaranmehri
فارسی
Let's work together
All work

Provisio

A VPN subscription store on one FastAPI backend, built so that no payment is processed twice and no order is activated twice.

A customer picks a plan on the website or in a Telegram bot, and the website sends them to Zarinpal to pay. A background worker then creates their account on a Marzban panel, and a second one disables it when it expires. Every fact — who paid, what is active, when it ends — lives in the backend and its PostgreSQL database, and the website, the bot and the operator's admin panel all go through it. AI features are planned for a later version; none are in the code yet.

Role
Sole developer
Period
2026
Status
Source available
Stack
  • Python
  • FastAPI
  • SQLAlchemy
  • PostgreSQL
  • Alembic
  • aiogram
  • Next.js
  • TypeScript
  • Docker
  • Marzban
  • Zarinpal

Outcomes

  • A customer on the website goes from a plan to a working VPN account without an operator stepping in, and sees each step as it happens.
  • Recovers from its own failures: an order a dead worker left half-done is claimed again, a failed panel call is retried with backoff, and a missing database is reported as degraded instead of crashing the API.
  • Deploys as seven containers with migrations as an explicit step, and its whole test suite runs with neither Marzban nor Zarinpal reachable.
  • 353 automated tests, all passing how this was measured
    method
    python -m pytest over the full suite: 25 test modules, 353 collected, 0 skipped
    measured
    sample
    repository at commit 185b9ab
    environment
    local machine, Python 3.13.7, pytest 8.4.1, PostgreSQL 18
  • 0 lint and type errors how this was measured
    method
    ruff check app/ bot/ tests/ alembic/; tsc --noEmit and eslint . in website/ (one ESLint warning, no errors)
    measured
    sample
    repository at commit 185b9ab
    environment
    ruff 0.11.13, TypeScript 5.7.2, ESLint 9.17.0

Screenshots

  1. Three plan cards side by side, CarbonNet Starter, Pro and Ultra, each with a price in toman, its validity in days, a traffic allowance, a number of connections and a Buy VPN access button. (open full size)
    Plans Read from the backend's public plan list. An operator creates and edits plans, and switches them on and off, from the admin panel.
  2. The Create your CarbonNet account form: an email field, a password field noting it must be between 8 and 128 characters, a confirmation field and a Create account button. (open full size)
    Account An email and an Argon2 password hash, or a Telegram id. A check constraint refuses a user row with neither, and a password without an email.
  3. The checkout page before payment starts: a status card reading Ready to start purchase, a payment-details panel holding only a placeholder line, a Start checkout button, and an order summary for a 90-day, 200 GB plan. (open full size)
    Checkout Starting checkout opens a purchase intent, an order and a payment attempt, each at most once, and hands the customer to Zarinpal.
  4. A customer dashboard listing two subscriptions: one active, with a data-usage bar at 41.3 of 200 GB and an expiry date, and one expired with a prompt to buy a new plan. (open full size)
    Dashboard After payment a worker creates the account on the Marzban panel, and the subscription row keeps its username and subscription link.

The repository's own screenshots of the website, which carries the storefront name CarbonNet, captured from the running application with demo plans.

Engineering highlights

  • One purchase, however many taps

    A double tap, a bot restart or a repeated callback still ends in one order and one payment, because the database refuses the duplicate at every stage.

    See how : One purchase, however many taps
  • Paying never waits on the VPN panel

    A payment is confirmed on its own, and the VPN account is created afterwards by a separate worker, so a slow or unreachable panel delays an activation instead of failing a payment.

    See how : Paying never waits on the VPN panel
  • Expiry never leaves a working account behind

    The account is disabled on the VPN panel before the database marks it expired, so the database never says expired while the account still works.

    See how : Expiry never leaves a working account behind
  • Tokens never reach the browser

    The website keeps both login tokens in HttpOnly cookies and sends every protected call through its own server, so no script on the page can read them.

    See how : Tokens never reach the browser

How a purchase works

A purchase is four backend records created in order, and each step is idempotent on a key of its own:

  1. A purchase intent records that a user wants a plan, under a key the client supplies.
  2. An order is created from the intent. An intent can produce at most one.
  3. A payment attempt is opened on the order under a second key and, from the website, handed to Zarinpal, which answers with an authority the attempt keeps. When the gateway calls back, the backend checks the payment against the amount it stored and marks the order paid. The request path ends here.
  4. The provisioning worker claims the paid order, creates the account on the Marzban panel, stores the username and subscription link on a subscription row unique to that order, and marks the order active.

The website shows the customer each of these states by polling a status endpoint through its own route handler. The Telegram bot creates the same first three records through the same services.

What the database guarantees

The two promises in the subtitle, that no payment is processed twice and no order is activated twice, do not depend on the website or the bot behaving correctly. The database and a state machine enforce them.

  • Orders move through nine states and payments through four. Each model has one transition function that refuses any change missing from its table of allowed transitions; the only exceptions are two recovery branches that set an order active when its subscription already exists and is active.
  • Every place a duplicate could be created has a unique constraint: an intent per user and idempotency key, an order per intent, a payment per idempotency key, per gateway authority and per gateway reference, an intent per token, and a subscription per order.
  • A subscription is tied to its order by two composite foreign keys, on order and user and on order and plan, so it cannot point at another customer’s order or at a different plan.
  • Money is an integer number of toman, with the currency fixed by a check constraint. A payment whose amount differs from its order’s total is refused before it starts and again before it is verified.

Website, Telegram bot and admin panel

Website. The Next.js site never holds a token in the browser. Both tokens live in HttpOnly cookies, and every protected call from the browser goes through a route handler that adds the bearer header, spends the single-use refresh token exactly once on a 401 and retries, and writes the new pair back as cookies. Server-rendered pages read the plan list and the current user directly, and recover an expired session through a dedicated refresh route. A guard cookie stops a broken session looping between that route and the login page, and the address to return to after login is checked so that it cannot send the user to another site.

Telegram bot. Built on aiogram, it runs in polling mode as a single replica, authenticates to the backend with a service token and passes the Telegram user id as a header. It keeps no purchase state of its own (see the second design decision), and it rejects a stale or mismatched flow token before it calls any purchase API.

Admin panel. Server-rendered with Jinja over the same admin API and the same JWT authentication, with the token carried in an HttpOnly cookie. Its scope is deliberately narrow: viewing users, orders, payments and subscriptions, managing plans, changing a user’s status and cancelling a subscription. The first admin is created by a command-line tool that needs a one-time token and refuses to run if an admin already exists.

Deployment

Production runs seven processes, each in its own container from the production compose example: the API, the bot, the provisioning worker, the expiry worker, the website, PostgreSQL and Redis. The Python image runs as a non-root user, and in production the application refuses to start with debug on or with a placeholder still set for any secret its settings manage. Migrations run as a separate step, explained in the last design decision below.

Limitations of this version

The project’s scope document leaves five features for after the first version, and the code shows one more gap, listed first:

  • Paying from the Telegram bot. The bot creates the order and the payment attempt but cannot yet send the customer to Zarinpal, so for now a purchase is paid for on the website.
  • Renewal. A purchase can already name the subscription it renews, but there is no screen where a customer can renew.
  • Linking a Telegram account to a website account. The backend can issue a link code on the website side and accept it from Telegram; the website has no page for it yet.
  • Payment history for customers.
  • Support tickets with replies from an admin, and manual payment verification by an admin.

Design decisions

Activation runs in a background worker, not inside the payment request

When Zarinpal confirms a payment, the order is marked paid. Creating the account on the Marzban panel is a network call to a second system that can be slow or down, and it has to happen exactly once per order.

Also considered
Activating in the payment callback — The deployment notes rule it out in as many words: do not rely on web requests to activate paid orders. A callback has the gateway and the customer waiting on it, and a panel outage would turn a successful payment into a failed request.

Chosen

A separate provisioning process claims one paid order at a time with SELECT … FOR UPDATE SKIP LOCKED, writes a claim token, commits, and only then calls the panel. Completion and failure both check that the token is still current before they touch the order.

  • A worker that dies after claiming is recovered: its claim can be taken again after five minutes by default, and the panel call's timeout must be shorter than that, so a hung call cannot outlive its claim.
  • Two provisioning workers can run at once. SKIP LOCKED keeps them off the same row, and the claim token stops a stale one from completing an order the other has taken over.
  • A failed call is retried with exponential backoff up to a set ceiling, and the last error is stored on the order.

Duplicate purchases are stopped by the database, not by the bot

A Telegram user can tap Pay twice, the bot can restart mid-flow, and a callback can be delivered more than once. Something has to remember that this purchase already exists.

Also considered
Holding purchase state in the bot — The README forbids it by name: the bot's state is disposable and must not store order, payment, subscription or lifecycle state. Anything the bot remembered would be gone on restart, and a second tap would be a second order.

Chosen

One unique constraint per stage: purchase intents on (user, idempotency key), one order per purchase intent, one payment per idempotency key. The bot keeps only a flow token, the plan id, a generated key and a timestamp, for fifteen minutes.

  • Repeating a pay callback returns the same intent, the same order and the same payment attempt. A replay that reuses a key with a different plan is rejected as a conflict rather than silently reused.
  • The website goes through the same purchase service and the same constraints, so neither client has its own notion of a duplicate.

On expiry, the panel account is disabled before the database row changes

An expiry worker finds active subscriptions whose date has passed and has to change two systems, the Marzban account and the database row, without ever leaving them disagreeing in the customer's favour.

Also considered
Marking the subscription inactive first — If the disable call then failed, the database would say the subscription had ended while the account still worked, which is the exact state the service's own docstring says it exists to prevent.

Chosen

Claim one expired, still-active row with SKIP LOCKED, call disable while the lock is held, and only on success set it inactive and move the order to expired. A failed disable returns without writing, so the row stays active and is claimed again on the next pass.

  • The failure mode is bounded to one direction: the panel may be disabled before the row says so, but the row is never marked expired while the account still works.
  • Retrying is safe by construction, because only active rows are ever claimed.
  • Expiry is its own process with its own poll interval, separate from provisioning and from the API.

Only the external systems sit behind an interface

The backend makes outbound calls to two external systems it does not control: the Marzban panel and the Zarinpal gateway.

Also considered
An interface in front of every layer — The README's architecture note draws the line: port interfaces only for the external integrations that need to be swappable. Routes, services and models are one codebase and gain nothing from a seam between them.

Chosen

Two abstract ports, each with one adapter: VPNProvider to provision, renew, disable and read an account, and PaymentProvider to start and verify a payment. The provisioning and expiry services take a provider as an argument and never import Marzban.

  • The provisioning, expiry and payment tests inject fakes for both ports, so the whole suite runs with no panel and no gateway reachable.
  • Replacing the gateway is one adapter; the state machines above it do not change.

Database migrations run as their own deploy step

The API and both workers share one PostgreSQL database, and each restarts on its own schedule.

Also considered
Running the upgrade when the API starts — The README rules it out: startup does not run migrations, and on every deploy with schema changes the upgrade is a required step before the new application containers start.

Chosen

A migrations service in the production compose file, behind a profile, run between starting the database and starting the application services. The API starts without a database and reports degraded on its health endpoint rather than crashing.

  • A deploy with schema changes is three commands in a fixed order, and a container restart can never alter the schema.
  • The health endpoint answers 503 with a component-level body when the database is unreachable, so an orchestrator can tell a dead process from a missing dependency.

Nastaran's assistant

Ask me about Nastaran's work, skills and services, or how to reach her — in English or Persian. I answer only from what is published on this site, and I'll say so when it doesn't cover something.

Try one of these: