Modular Monolith vs Microservices: Why Kuvuty Runs on a VPS with a Separate Worker Service
How Kuvuty runs as a Next.js modular monolith on a VPS, with a PostgreSQL job queue and a separate worker, and what it costs versus managed containers.
Key Takeaways
- Kuvuty is a modular monolith: one Next.js codebase, one PostgreSQL database, one image. Heavy work runs in a separate worker service built from the same code, not in a dozen microservices.
- The background job queues live in PostgreSQL. Workers claim rows with
FOR UPDATE SKIP LOCKED, and long-running ZIP jobs also take a lease, so ZIP indexing and email delivery need no Redis and no broker.- Video goes to Cloudflare Stream and uploads go to Cloudflare R2, so the server never transcodes or streams video.
- On public list prices, the same workload costs about €30 a month on one VPS and roughly $200 to $370 a month as five containerized services on a managed platform. That is an illustrative estimate, not Kuvuty's bill.
- The VPS gives up managed failover and autoscaling. Health checks, encrypted off-site backups and a weekly restore drill make recovery a rehearsed procedure, and we split a workload out only when it earns it, as ZIP processing did.
Kuvuty is a learning platform for university courses and workshops in English and Kiswahili, starting in Tanzania. It works closely with the University of Dar es Salaam and Zanzibar University and is in discussions with UNDP. We designed and built kuvuty.com and the platform behind it, and we run both for the client.
This article covers the architecture and the hosting economics behind it. Its sibling covers how we version courses without losing learner progress; this one is about the system around that database. The reasoning applies to most web products, which are not yet at the scale where independent services pay for themselves.
What is a modular monolith, and what did we build?
A modular monolith is one deployable application whose code is divided into modules with clear boundaries, sharing one database. Kuvuty is a Next.js application with a module for each area of the domain (identity, publishers, courses, media, quizzes, flashcards, learning, entitlements, bundles, catalog, privacy, administration) and a security layer every module goes through. Route handlers and server actions are thin adapters that parse input and call a module's application service.
Our first architecture decision record states the choice: a single Next.js app, PostgreSQL 17, background work through a database-backed outbox, and explicitly no Redis, no message broker, no microservices and no Kubernetes. The first release targeted fewer than 1,000 students, and the record names what we optimized for: correctness and maintainability. One deploy unit means one transaction boundary, so a publish, an audit entry and a queued email commit together or not at all.
At runtime it is five Docker Compose services on one host:
| Service | Role |
|---|---|
db | PostgreSQL 17, persistent volume, no host port |
migrate | One-off job that applies migrations before anything starts |
app | The Next.js server, published on loopback only, behind Caddy and Cloudflare |
worker | The same image running scripts/worker.ts |
backup | Nightly encrypted backup and weekly restore drill, started by host cron |
Why is the worker a separate service and not a microservice?
The worker has its own container, restart policy and logs, but it runs the same image and codebase as the app and shares its database. It exposes no API and owns no data. There is no contract to version and no network boundary to keep stable, so we call it a separate worker service.
One loop in scripts/worker.ts ticks every five seconds. It delivers queued emails (exponential backoff from 15 seconds, capped at an hour, marked dead after 8 attempts), indexes at most one uploaded ZIP, reconciles videos still processing in Cloudflare Stream every 30 seconds to catch missed webhooks, runs retention cleanup daily and records a heartbeat every ten minutes. Each job runs in its own isolation wrapper: a failure is logged, reported to error tracking, recorded for the admin diagnostics screen and retried on the next tick, and the loop does not die because one archive was malformed.
The point is isolation of load. Indexing a large archive costs CPU, disk and time. In the web process it would compete with learners opening lessons; in the worker it competes with nothing a person is waiting on, and a crash there leaves the site untouched.
How does a job queue in PostgreSQL work?
The queue is a table. A row says what must happen, when it is next due, how many attempts it has had and who holds it. A worker claims a row with FOR UPDATE SKIP LOCKED: in PostgreSQL's words, rows that cannot be immediately locked are skipped, which the documentation says avoids lock contention between several consumers of a queue-like table.
-- Simplified from the ZIP indexer's claim
update archive_manifests
set state = 'INDEXING', attempts = attempts + 1,
lease_until = now() + interval '10 minutes'
where asset_id = (
select asset_id from archive_manifests
where (state = 'UPLOADED' and next_attempt_at <= now())
or (state = 'INDEXING' and lease_until < now())
order by next_attempt_at
limit 1
for update skip locked)
returning asset_id, attempts;- Leased. The claim is a single autocommitted statement, so the row lock is released immediately; the lease is what marks the job as taken while it runs. If a worker crashes mid-archive, the ten-minute lease expires and the next pass retries.
- Safe with several workers. Two workers never claim the same row, so a second worker container needs no coordination code.
- Bounded and idempotent. One archive per tick, a five-minute time budget, five attempts with backoff from 30 seconds for storage errors, and a finished manifest that a database trigger makes immutable. The result is written only if the row is still
INDEXING, and the same bytes always produce the same manifest, so a retried job cannot produce a different answer.
The email outbox uses a different claim, on purpose. A producer inserts the email row in the same transaction as the business change, so a rolled-back change never sends a message and a committed one is durably queued. The worker then selects one due row FOR UPDATE SKIP LOCKED and holds that row lock inside a transaction while it calls the email provider, which takes milliseconds rather than minutes, so no lease is needed: if the worker dies, the transaction aborts and the row becomes claimable again. Delivery is therefore at-least-once. Each row carries a unique idempotency key, which stops a retried producer from enqueuing twice and is passed to the provider so a resend after a crash can be deduplicated. Because emails can contain one-time links, queued payloads are stored encrypted with AES-GCM and scrubbed once the email is delivered or marked dead.
The ZIP reader assumes hostile input. It streams the archive into a private, size-capped temporary file that is deleted afterwards and never extracts entries to disk. It checks every limit from the central directory before decompressing anything, then requires each local header to agree with its central-directory entry, which closes the classic trick of showing different content to different ZIP parsers. Each entry is inflated only into a byte counter and CRC check, capped at its declared size, so a ZIP bomb stops at its first false size. It enforces 250 MB per archive, 2,000 entries, 1 GB uncompressed and compression-ratio limits, and rejects ZIP64 archives as well as encrypted, symlinked, overlapping and path-traversing entries.
A Postgres queue has a ceiling: polling every five seconds adds latency, and row locks and dead tuples from frequent updates do not match a dedicated broker at very high throughput. For uploads and transactional email that ceiling is far away, and the queue's advantage is that it commits atomically with the data it describes.
What does the server not do?
Video is uploaded to and played from Cloudflare Stream, and PDF and ZIP uploads go from the browser to a private Cloudflare R2 bucket through short-lived signed URLs. PDF and ZIP downloads do pass through the app, because each one is a fresh access decision. The machine therefore does the work only it can do: serving pages, running modules and indexing archives. In the pre-launch load check in November 2026, 50 concurrent simulated learners with no think time produced a p95 response time of 538 ms with no errors, against a production build running on a development machine rather than the production server. We quote that as a launch-scale check, not a capacity claim.
What does it cost compared with microservices on managed containers?
The table below is an estimate built from public list prices checked on 28 November 2026. It describes a plausible workload, not Kuvuty's invoice, and the VPS column uses a Hetzner plan as a representative price, not Kuvuty's provider. Costs identical in both designs (Cloudflare Stream and R2, error tracking, email, DNS) are left out. Both columns run containers; Kuvuty itself ships as Docker images. What differs is that a managed platform bills each service, the database, the load balancer and the network path separately.
Workload: a web app, a worker, a PostgreSQL database and backups, about 4 vCPU and 8 GB of memory in total.
Managed-container assumptions: the same workload split into five microservices (web, API, worker, ZIP processor, notifications) on AWS Fargate at 0.5 vCPU and 1 GB each, an RDS PostgreSQL db.t4g.medium (2 vCPU, 4 GB), an Application Load Balancer, and tasks in private subnets that reach Cloudflare and the email provider through NAT gateways; 730 hours a month, US East pricing. "Minimal" is one task per service, a single-zone database and one NAT gateway. "Typical" is two tasks per service, a Multi-AZ database and two NAT gateways.
| Monthly line item | One VPS, modular monolith | Managed containers, minimal | Managed containers, typical |
|---|---|---|---|
| Compute | €30.49 (runs app, worker, database, proxy) | $90.10 (5 tasks) | $180.20 (10 tasks) |
| PostgreSQL | included | $47.45 (Single-AZ) | $94.17 (Multi-AZ) |
| Load balancer (1 LCU) | Caddy, same host | $22.27 | $22.27 |
| Public IPv4 on balancer (2) | not itemised | $7.30 | $7.30 |
| NAT gateway (hours only) | none | $32.85 (1) | $65.70 (2) |
| Total | €30.49 | about $200 | about $370 |
Euros and dollars are compared at face value; converting would narrow the gap slightly without changing the conclusion. Storage, backup storage, NAT and load-balancer data processing, data transfer and the NAT gateways' own public IPv4 addresses are counted on neither side, which flatters the managed column.
Sources, all checked on 28 November 2026:
- Hetzner Regular Performance: CPX32, 4 vCPU, 8 GB, 160 GB NVMe, 20 TB traffic, €30.49 a month excluding VAT in Helsinki (€35.99 in Nuremberg). The cheaper Cost-Optimized plans showed as unavailable that day.
- AWS Fargate pricing: $0.040478 per vCPU-hour and $0.004446 per GB-hour, Linux/x86, US East (N. Virginia), derived from the page's per-second rates.
- Amazon RDS for PostgreSQL pricing and the AWS price list:
db.t4g.mediumat $0.065 an hour Single-AZ, $0.129 Multi-AZ. - Elastic Load Balancing pricing: $0.0225 per hour plus $0.008 per LCU-hour.
- Amazon VPC pricing: $0.045 per NAT gateway hour (the page's US East, Ohio example) and $0.005 per public IPv4 address hour.
Kubernetes adds its own fixed line: Amazon EKS pricing lists $0.10 per cluster per hour, about $73 a month before any node. Google Cloud Run bills per vCPU-second and can scale to zero, which suits spiky traffic; we could not confirm its current rates, so it is not in the table.
How does the gap change with scale?
Compare unit prices. The same 4 vCPU and 8 GB on Fargate is $144.16 a month for compute alone, against €30.49 for a server that also includes 160 GB of storage and 20 TB of traffic. The vCPUs are not identical products (the VPS uses shared cores), so read this as an order of magnitude.
- On a VPS, growth is a step up one ladder. The CPX42 (8 vCPU, 16 GB) is €59.49 in Helsinki, €29 more for twice the resources. Fargate's compute line doubles to $288.32.
- With microservices, fixed costs multiply. Each new service brings its own minimum, at least $18 a month for one 0.5 vCPU task and $36 for a redundant pair, plus its own pipeline, logs and alarms. Each availability zone adds a NAT gateway.
- In a monolith, a new module is code and not infrastructure. It uses the host's idle capacity.
Our first scaling steps would be a larger server, a second worker container (the queue already allows it) and the database on its own host. Splitting out another service comes after those, on evidence.
What do you give up?
Three things.
- Automatic failover. One server is one failure domain. If the host dies, recovery is a restore from backup, not a switch to a standby. For a launch-scale platform with a recoverable data set we judged that acceptable; a product with a hard uptime commitment would need a standby or a managed database.
- Autoscaling. Capacity is what the server has, so a sudden spike is absorbed by headroom and not by new instances.
- Operational responsibility. Patching, disk space, certificates and restores are ours. We cover them with restart policies and a container health check on
/api/healthevery 30 seconds; a nightlypg_dump, encrypted with AES-256-GCM and uploaded to a private R2 bucket (14 daily, 8 weekly and 6 monthly copies kept); structured, rotated logs, error tracking and an admin diagnostics screen with worker heartbeat and failed jobs; and a weekly restore drill that restores the newest backup into a scratch database, verifies the GCM tag, the checksum and every table's row count against the backup's manifest, then drops it. The row counts can be compared exactly because the backup reads them in aREPEATABLE READtransaction and hands that transaction's exported snapshot topg_dump, so the dump and the manifest describe the same instant.
A backup nobody has restored is a hope. Ours is exercised every week.
When would we split a service out?
We split when a workload has a different shape from the web app: different resources, a failure mode that must not take the site down, a different scaling curve, a security boundary, or a separate owner. ZIP processing met the first two, so it became a separate worker service. It still shares the code and database, because that cost nothing and kept transactions simple.
At the 27 November 2026 release check the project ran 660 unit and database tests and 45 browser journeys, all passing. With modules behind explicit service boundaries, extracting one later is a refactor and not a rewrite.
When this approach fits
Consider a modular monolith on a VPS when the team is small, traffic is thousands of users and not millions, a short outage is tolerable and budget matters. Consider managed containers when you need multi-region availability, traffic that must scale in minutes, or several teams shipping independently. If you are unsure which side you are on, our software architecture and custom web application development work starts with that question. See the Kuvuty case study, or contact us.
Frequently asked questions
Is a modular monolith cheaper than microservices?
Usually, at small and medium scale. A monolith needs one runtime, one database and one pipeline, while microservices on managed platforms add per-service minimum sizes, load balancing and networking. On list prices our example workload costs several times more as managed containers than on one VPS.
Can PostgreSQL replace Redis or RabbitMQ as a job queue?
For moderate volumes, yes. FOR UPDATE SKIP LOCKED lets several workers claim different rows without blocking each other, and a job can commit in the same transaction as the data it relates to. At very high throughput a dedicated broker is the better tool.
What happens if the VPS fails?
You restore. The database comes back from the newest encrypted off-site backup into a new database, migrations run forward if the backup is older than the code, and the containers start from the same Compose file. The weekly drill checks the backup is usable. Recovery takes time and is not automatic, which is the main trade-off of this design.