Back to Home

FastAPI + Marzban: automation of VPN service

Service automates issuance of VPN keys: registration, payment, vless from Marzban. Uses FastAPI async, PostgreSQL, YUKassa webhooks with idempotency, Cloudflare. Code details: models, caching, trial, background tasks.

Building VPN service: FastAPI, Marzban, async SQLAlchemy
Advertisement 728x90

Automated VPN Protection Service with FastAPI, Marzban, and Docker Integration

A FastAPI backend integrates with Marzban for VPN user creation, YooKassa for payments, and Resend for email. Users register, verify their email, pay, and instantly receive a vless key. The async SQLAlchemy architecture enables parallel processing of webhooks, Marzban API requests, and email sending without blocking.

Tech stack: Python 3.11, FastAPI, PostgreSQL, React 18 + Vite + Tailwind, XRay-core via Marzban, Docker Compose + Nginx + Cloudflare.

System Architecture

Traffic flows through Cloudflare → Nginx: static React on :3000, API on :8080. FastAPI routers (/auth, /configs, /payment) interact with PostgreSQL, Marzban REST API, Resend, and YooKassa/Plisio.

Google AdInline article slot

Marzban runs on a host outside Docker; containers communicate via a bridge interface.

User
    ↓ HTTPS
Cloudflare
    ↓
Nginx
  / → frontend:3000
  /api/ → backend:8080
    ↓
FastAPI → PostgreSQL | Marzban | Resend | YooKassa

Database Models

Key entities:

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    email: Mapped[str] = mapped_column(unique=True, index=True)
    hashed_password: Mapped[str]
    is_verified: Mapped[bool] = mapped_column(default=False)
    marzban_username: Mapped[str | None] = mapped_column(unique=True, nullable=True)
    referral_code: Mapped[str] = mapped_column(unique=True, default=lambda: secrets.token_urlsafe(8))
    trial_used: Mapped[bool] = mapped_column(default=False)
    email_verify_token: Mapped[str | None] = mapped_column(nullable=True, index=True)

class Subscription(Base):
    __tablename__ = "subscriptions"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    plan: Mapped[str]
    status: Mapped[str]  # active | expired | pending
    devices: Mapped[int] = mapped_column(default=1)
    started_at: Mapped[datetime] = mapped_column(server_default=func.now())
    expires_at: Mapped[datetime]
    marzban_expire_ts: Mapped[int]

class Payment(Base):
    __tablename__ = "payments"
    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    provider: Mapped[str]  # yookassa | plisio
    external_id: Mapped[str]
    amount: Mapped[float]
    status: Mapped[str]  # pending | paid | failed
    plan: Mapped[str]
    months: Mapped[int]

Marzban Integration

API Token Caching

The Marzban token expires after an hour. A 55-minute cache with asyncio.Lock prevents race conditions:

Google AdInline article slot
class MarzbanService:
    def __init__(self):
        self._token: str | None = None
        self._token_expires_at: float = 0
        self._lock = asyncio.Lock()

    async def get_token(self) -> str:
        async with self._lock:
            if self._token and time.time() < self._token_expires_at:
                return self._token
            self._token = await self._fetch_token()
            self._token_expires_at = time.time() + 55 * 60
            return self._token

Creating a VPN User

async def create_user(self, username: str, months: int, days: int = 0) -> dict:
    expire_ts = _months_to_timestamp(months)
    if days:
        expire_ts = int(datetime.now(timezone.utc).timestamp()) + days * 86400

    payload = {
        "username": username,
        "proxies": {"vless": {"flow": "xtls-rprx-vision"}},
        "inbounds": {"vless": ["VLESS Reality"]},
        "expire": expire_ts,
        "data_limit": 0,
        "data_limit_reset_strategy": "no_reset",
    }
    async with httpx.AsyncClient(timeout=15) as client:
        resp = await client.post(
            f"{settings.MARZBAN_URL}/api/user",
            json=payload,
            headers=await self._headers(),
        )
        resp.raise_for_status()
        return resp.json()

Marzban returns a ready vless://... in the links field.

Subscription Renewal

For expired subscriptions, renewal starts from the current time:

async def extend_subscription(self, username: str, months: int) -> dict:
    user = await self.get_user(username)
    current_expire = user.get("expire") or 0
    base = max(current_expire, int(time.time()))
    base_dt = datetime.fromtimestamp(base, tz=timezone.utc)
    # PUT /api/user/{username} with new expire

YooKassa Webhook Handling

Idempotency is critical: YooKassa duplicates webhooks if delays exceed 10 seconds.

Google AdInline article slot
async def activate_subscription(payment: Payment) -> None:
    async with AsyncSessionLocal() as session:
        result = await session.execute(select(Payment).where(Payment.id == payment.id))
        fresh_payment = result.scalar_one()
        if fresh_payment.status == "paid":
            logger.info(f"Payment {payment.id} already activated, skipping")
            return
        try:
            await _do_activate(fresh_payment, session)
        except Exception as e:
            await session.rollback()
            logger.error(f"Activation failed: {e}", exc_info=True)
            raise

A fresh DB session, independent of the webhook, is used.

IP whitelist for Cloudflare:

client_ip = request.headers.get("CF-Connecting-IP") or request.headers.get("X-Forwarded-For", "").split(",")[0].strip() or request.client.host
allowed_prefixes = ("185.71.76.", "185.71.77.", "77.75.153.", "77.75.154.", "77.75.156.")
if client_ip not in {"77.75.156.11", "77.75.156.35"} and not any(client_ip.startswith(p) for p in allowed_prefixes):
    raise HTTPException(403)

Trial and Verification

3 days of VPN after email confirmation:

  • User registers, receives a token via email.
  • GET /verify-email/{token} activates is_verified=True.
  • A background task creates a Marzban user with days=3, marks trial_used=True.

Check: no active subscription and trial not used.

Dynamic Subscriptions and Devices

Additional device purchases (+99₽ each) are preserved upon renewal:

extra_devices = max(0, existing_sub.devices - plan_cfg["devices"])
existing_sub.devices = plan_cfg["devices"] + extra_devices

Price: base + extra_devices * DEVICE_ADD_PRICE.

Background Tasks

APScheduler for automation:

  • Daily report (8:00).
  • Expiration reminders (9:00).
  • Pending payment checks (every 5 minutes).
scheduler = AsyncIOScheduler(timezone="Europe/Moscow")
scheduler.add_job(send_daily_report, CronTrigger(hour=8, minute=0), id="daily_report")

Docker Compose Issues

v1.29 on Ubuntu 22.04 crashes on rebuild: KeyError: 'ContainerConfig'. Solution:

docker-compose stop service
docker-compose rm -f service
docker-compose up -d service

Key Takeaways

  • Async FastAPI + SQLAlchemy ensures concurrency without GIL issues.
  • Webhook idempotency prevents duplicate subscriptions.
  • Marzban token caching with locks minimizes API requests.
  • Cloudflare requires explicit CF-Connecting-IP verification for YooKassa.
  • Trial via email verification limits abuse.

— Editorial Team

Advertisement 728x90

Read Next