Skip to content

Architecture

Updated

Over-Engineering My Personal Platform (Because Why Not?)

I could have thrown together a basic template for this portfolio and called it a day. But where is the fun in that?

I wanted a complete personal ecosystem—built on an extensible, solid foundation ready to ingest whatever chaotic backend ideas I dream up in the future. The portfolio website is just one client application within this platform.

This architecture didn't appear overnight; it evolved through constant iteration. I originally started with a monolithic Python backend. I eventually rewrote it into a Go REST API for two reasons: I wanted to learn Go, and I wanted to eliminate the heavy runtime overhead of Python. On the frontend, my administrative dashboards went through two distinct iterations using JavaScript and Bun as I refined the UI patterns.

While those monolithic REST APIs worked fine for a simple website, they presented a structural roadblock: if I wanted to build a completely separate project (like an expense tracker or a custom analytics engine), I would have to recreate authentication, rate-limiting, and core boilerplate all over again. I wanted to genuinely learn how to build distributed systems, and my personal platform was the perfect playground to do it.

So, I abandoned the monolithic REST approach entirely and built a strictly-typed microservice platform from scratch—extracting authentication and routing so any future service can plug into the grid for free. Here is how I wired together Go, gRPC, React, and a slightly paranoid PostgreSQL setup to make it happen.

Let me be honest about the motives, because "distributed systems" sounds a lot nobler than the truth. Reason one: I wanted to learn. Reason two: pure, industrial-grade laziness. I refuse to rebuild authentication for every new idea, and I refuse even harder to patch the same vulnerable package in five repositories at midnight, praying I didn't forget a flag in repo number four. A shared library fixes the copy-paste; it does nothing for the "now update it everywhere" part. I'll happily repeat work when it adds value. This added nothing but anxiety. (Yes, today an AI agent would do those five updates without complaining. When I poured this foundation, agentic coding was still learning to walk.)


The Grand Plan

The architecture relies on strict isolation. The frontends talk exclusively to a central API perimeter, which handles the dirty work before passing clean, binary payloads down to the internal backend services.

Architecture Diagram


The Perimeter: HAProxy & Fiber API Gateway

All external ingress traffic first passes through HAProxy, which sits at the absolute edge of the production infrastructure. It acts as the primary reverse proxy and entry point, handling:

  • TLS Termination & HTTPS Enforcement: Automatically redirects HTTP to HTTPS (*:443 ssl crt) and manages SSL certificates.
  • Domain ACL Routing: Routes traffic based on subdomains (auth.api.adityapunmiya.com, manager.api.adityapunmiya.com, wallet.api.adityapunmiya.com, tools.api.adityapunmiya.com) directly to the backend gateway cluster. Any hostname it doesn't recognize gets a flat 404.
  • Edge Compression & Headers: Applies dynamic gzip compression for JSON/text responses, strips client-supplied forwarding headers and caps each source IP at 200 requests per 10 seconds.
  • Health Checks & Telemetry: Monitors backend availability with an HTTP health check that also confirms the gateway can reach Redis. The stats page is welded to localhost and only reachable through an SSH tunnel, because a dashboard facing the open internet is an invitation.

The API gateway itself is built using Fiber, a ridiculously fast web framework for Go.

The gateway executes no business logic, with one deliberate exception I'll get to later (deleting a user). Its entire job is to keep the noise out. It intercepts incoming traffic, handles rate-limiting via Redis to stop script kiddies from spamming my endpoints, and manages two distinct authentication lanes:

  • The Admin Dashboards: Authenticate via secure, Redis-backed session cookies. The __Secure-session cookie is scoped strictly to api.adityapunmiya.com, so the websites themselves never even see it.
  • The Public Portfolios: Communicate via per-user API keys, stored only as SHA-256 hashes. A key can reach exactly six routes: four that read portfolio content, one that delivers contact messages, and one that asks whether a chatbot visitor has run out of questions. Everything else slams shut. The gateway caches a key's identity so it doesn't have to ask Auth on every page view, but that cached copy is on a strict diet: a user id, "may use Manager", and its allowed origins. No email, no other apps, and never the admin role, even when the key belongs to me.

Password guessing gets its own speed bump: login attempts are capped per account, not just per IP, so rotating through a pool of proxies buys an attacker nothing. And when I disable a user, their API key dies on the very next request instead of lingering until some cache happens to expire.

Yes, portfolios, plural. Anyone I give Manager access to can run their own portfolio on this platform, even from a completely different domain like xyz.com. They register that domain against their key in the Console, and the gateway opens a second, strictly cookie-free CORS lane just for it. An unregistered site gets nothing, and even a registered one can never ride on somebody's logged-in session.

The gateway itself only listens on localhost, so there is no sneaking around HAProxy, and it only believes forwarded client IPs when they come from HAProxy. Spoofing your way past the rate limiter with a fake header doesn't work.

Once a request passes the gauntlet, the gateway wraps the request in a 9.5-second deadline context (giving services a safe margin before HAProxy drops the connection), translates the JSON payload to Protobuf, and fires a lightweight binary gRPC call into the internal backend cluster.


Internal Contracts via gRPC & Buf

When you split a monolith into microservices, keeping internal communication in sync across different codebases can quickly turn into a nightmare of broken endpoints and mismatched JSON. To kill this friction forever, the API gateway and internal backend services communicate strictly over gRPC using Protocol Buffers (.proto).

Why gRPC? Because I wanted to play with it, and I won't pretend otherwise. The textbook contenders for service-to-service calls are gRPC, Cap'n Proto and Thrift. Cap'n Proto had about three tutorials and a mailing list, and Thrift is the kind of project people politely stop recommending for new work. So gRPC won the way the last person standing wins a tournament.

I manage all schemas centrally using Buf, which is what turned gRPC from painful into pleasant. It acts as the ultimate gatekeeper, handling linting and compiling the exact Go structs my services expect. To catch bad data before it even hints at touching my application logic, I use protovalidate to bake validation constraints directly into the raw .proto definitions.

Right now, the cluster runs four isolated microservices, showcasing a true polyglot architecture:

  • Auth Service: The central identity provider (Go). It handles SSO (Single Sign-On) for the entire ecosystem, decides who is allowed into which app (and, for Tools, into which individual tool), and issues/rotates API keys.
  • Manager Service: The headless CMS (Go). It drives the CRUD operations for work experiences, portfolio projects, and incoming contact messages, with every row belonging to its own user. It also remembers which AI model the portfolio chatbot should use.
  • Wallet Service: My personal expense tracker (C# / .NET). Not an accounting system and not double-entry bookkeeping: it records income and expenses in categories, keeps running totals for all time, the month and the week, remembers every edit, and exports to spreadsheets, all through locked-down PostgreSQL stored procedures. Why C# when everything else is Go? Money. C# ships a native decimal type built for exactly this, while Go makes you import a third-party package and hope. Java has BigDecimal, but I had already shipped C# at two jobs, and new-language anxiety is not something I want anywhere near my finances.
  • Tools Service: The newest arrival (Go), and my personal toolbox. It stores Folio markdown notes in virtual folders, with per-user quotas and an exclusive edit lock so the same note can't be edited in two places at once, plus saved Stencil patterns. Notes can be encrypted so that even the server can't read them, and plain notes can be published as public pages (more on both below). It is also the first real test of that "plug into the grid for free" promise: it was added long after everything else, without touching how authentication, sessions or rate limiting work.
  • Future Services: Because the Gateway and Auth layers are completely decoupled, I can drop a new service directly into the grid without touching the existing architecture.

And a private network is not a security strategy, so the gateway still has to prove itself. Every gRPC call carries a shared bearer token, and the services bind only to a private IP. If you aren't the gateway, the grid doesn't want to hear from you.


Escaping the Denormalization Trap (Moving to PostgreSQL)

As the first real-world stress test of this platform, I migrated my public-facing website from a legacy MongoDB cluster to this new architecture.

MongoDB was great for fast document reads, but it introduced a structural flaw: the denormalization trap. To avoid slow joins, MongoDB encourages embedding documents inside other documents. But when a piece of data changes, that update has to be manually propagated across multiple documents.

Yes, modern MongoDB supports multi-document transactions to prevent data fracturing during network hiccups, and they work. But once your updates routinely span multiple documents, you are asking a document database to behave like a relational one, and paying for it in performance and complexity. My take: if you need all of that, use an RDBMS. Maintaining it on MongoDB was a hellhole I had no interest in managing.

Moving to PostgreSQL solved this immediately. Relational normalization means updating a single row propagates the change everywhere, instantly and safely, with native ACID compliance that doesn't tank system performance.

It also allowed me to push the data processing closest to the data itself. Instead of making multiple database calls, dragging raw data across the network, and processing it in the application layer (or writing massive, unmaintainable MongoDB aggregation pipelines), I can execute a single SQL function directly on the server to get exactly what I need.

Three Database Servers: A Self-Inflicted Wound

In the first version of this platform, Auth, Manager, and Wallet each got their very own PostgreSQL server. On a whiteboard, it looked gorgeous: pure isolation, textbook microservices, not a single shared byte.

In production, it was an absolute nightmare.

Three servers meant three rounds of version upgrades, three backup jobs to babysit, three sets of credentials to rotate, and three configurations to tune and then slowly watch drift apart. Worse, every one of them reserved its own slice of memory and CPU just to sit there looking busy. On hardware as modest as mine, that is a crime.

And that was only three. The whole point of this platform is dropping new services into the grid for free, except "free" now came with a brand new database server attached. Every future idea would have meant yet another instance to patch, back up, and lie awake worrying about. The architecture I built to make new services cheap was quietly making them expensive.

So I killed them. There is now one PostgreSQL server and one database, carved into logically separated schemas: account for Auth, portfolio for Manager, and wallet for Wallet. One thing to upgrade. One thing to back up. One pool of memory that actually gets used.

The decision paid for itself the first time I built something new. When the Tools service came along later, it didn't get a server, a backup job or a set of credentials to babysit. It got a tools schema and a role, and that was the whole database story.

Nothing about this is free, and I won't pretend otherwise: if that one server goes down, everything goes down with it. For a personal platform, that is a trade I will happily make to get my weekends back. And the day a service genuinely outgrows this setup, its schema can be lifted out and moved to a server of its own.

Paranoid Database Security

Merging the servers did not mean merging the trust. Every service still gets its own locked room: each role can only enter its own schema, so Manager has no business reading Wallet's transactions, and PostgreSQL makes sure it can't. Then, I took the security model to a slightly paranoid extreme.

The application services connect to PostgreSQL using heavily restricted database roles (auth_service, manager_service, wallet_service, tools_service). I explicitly revoked INSERT, UPDATE, and DELETE permissions from the tables.

The Security Philosophy: If the Go service is compromised, a malicious actor still cannot run arbitrary write queries or drop tables.

Instead, all mutations are forced to route through tightly controlled, pre-compiled PL/pgSQL stored procedures. The application can only call specific execution paths. If it tries to write outside the lines, the database itself violently rejects it. The tables are created by a separate root role too, so the services don't even own the furniture.

None of this is free. Logic now lives in two languages, and a PL/pgSQL function is a lot less fun to test and refactor than Go code. Auth's and Tools' functions already run integration tests against a real PostgreSQL. Manager's and Wallet's are next in line, glaring at me from the backlog.

No ORM

There is no ORM anywhere in the stack. I have nothing against ORMs; they'd just be unemployed here. Every write is a PL/pgSQL function and most reads are a single query, so an ORM would only add a translator that turns my three-line query into thirty lines of SQL nobody asked for. I want to see exactly what hits the database, and keep the data processing sitting right next to the data.

Deleting a User Without Foreign Keys

There are no foreign keys anywhere, not even inside a schema. It's a habit I picked up from engineers who have run Oracle, PostgreSQL and embedded SQLite for decades, and who learned the hard way that foreign keys bring lock contention, hidden per-row work inside every innocent DELETE, and (in SQLite) enforcement that's silently off unless you ask for it. At my traffic, none of that costs anything measurable. What keeps me here is simpler: every delete function lists exactly what it removes, so nothing disappears that I didn't write down. The price is real, though: the database no longer guarantees that every row points at something that exists. That job is on my procedures, with the orphan report below as the safety net.

Between schemas, it's more than habit. The moment Wallet's tables point at Auth's, the two services are welded together, and that schema can never be lifted out to a server of its own.

That leaves one awkward question: when I delete a user, who deletes their data? Nobody is allowed to reach into someone else's schema, so the gateway runs the errand. It disables the account first, so the user is locked out immediately. Then it asks Manager, Wallet and Tools in parallel to purge everything that user owns (for Tools, that includes deleting their published pages from storage), and only when all three report back does Auth delete the account itself. Auth goes last on purpose: if one service fails halfway, the user stays visible (and disabled) in the Console with a retry button, instead of becoming a ghost whose data nobody can find again. Every purge is safe to repeat, so retrying never hurts.

For the ghosts that existed before this was built, the Console has an orphan report: every service lists the user IDs it holds data for, the gateway compares them against Auth, and anything left over can be purged with one click.

The Single-Tenant Constraint (Rest in Peace)

A previous version of this page proudly explained that the Auth schema hardcoded the user ID to 1, physically guaranteeing that nobody else could ever exist in my system. That was by design. I was very smug about it.

Then I realized a portfolio CMS is a lot more useful when other people can use it too, so the constraint is gone. Auth now has real role-based access control: one administrator and any number of tenants, each granted only the apps they are allowed to open. Every Manager, Wallet and Tools row is tied to its owner, so one tenant can't go wandering through another's data. Tools goes one level deeper: access is granted per tool, so someone can have Folio without Stencil.

What did not change is the paranoia about who gets in. Open registration still doesn't exist. Every account is created by hand from the Console, starts with a temporary password that expires in 7 days, and must pick a new one on first login. No sign-up form, no verification overhead, no rogue accounts.


The Presentation Layer

The client infrastructure consists of six distinct React applications. To mirror the backend's separation of concerns, the administrative tools are cleanly split by domain:

  • Console UI: The identity and operations dashboard. It acts as the SSO hub, routing requests through the gateway to the Auth service to manage active login sessions, user accounts, app access, published notes, and API key rotation.
  • Manager UI: The dedicated CMS dashboard. It handles the CRUD operations for the portfolio data once the gateway verifies the SSO session.
  • Wallet UI: The expense-tracking dashboard: income, expenses, categories and totals. Built with zero floating-point precision loss on balance calculations, because money that rounds itself is a horror story.
  • Tools UI: Folio and Stencil. Folio loads the note list once and caches note bodies in the browser by version, so opening a note I've already read never touches the backend. Stencil turns pasted data into SQL, JSON or whatever text I need through a pattern, and it runs entirely in the browser: the data never leaves the tab, only the saved patterns do.
  • Portfolio: The Next.js site you are reading this on. It pulls its content through the gateway with an API key and serves prerendered pages, so visitors aren't left waiting on my backend. It also runs the chatbot below, because of course it does.
  • Folio: A tiny Next.js site that shows published notes at folio.adityapunmiya.com/<id>. It never talks to my servers at all (details below).

All admin interfaces are built for speed: React, Vite, and Bun, with server state cached by TanStack Query.

Did the frontend need splitting? Absolutely not. I had already split the backend, so the frontend got split out of sheer momentum. The real reason: I'm a backend engineer with a genuine CSS phobia, and five dashboards meant five rounds of exposure therapy. Most of them predate useful agentic coding, so every misaligned div was fought by hand.

And when a project isn't ready for the public, it points to a tiny construction page: plain HTML and a few hundred bytes of JavaScript, because not everything deserves a framework. Not even on a platform this over-engineered.

Notes Even I Can't Read

Folio notes can be encrypted, and I mean properly: the encryption happens in the browser, before anything is sent. The server, the database and every backup only ever hold scrambled bytes, so if the whole platform leaked tomorrow, encrypted notes would leak as noise. Not even the administrator (me) can read them.

One vault password per user unlocks everything. It's stretched into a key with PBKDF2 and the notes are sealed with AES-256-GCM, both straight from the browser's built-in Web Crypto API, so there's no crypto library to trust. Each note's ciphertext is bound to that note's id, which means swapping ciphertext between notes fails loudly instead of quietly showing the wrong text. Changing the password is instant, because only the vault key gets re-wrapped, not every note. The vault locks itself after 15 minutes of inactivity, and even crash-recovery drafts are encrypted before they touch the browser's storage.

The catch is the whole point: forget the password and the notes are gone. There's a recovery key shown exactly once at setup, and after that, nobody (least of all me) can help.

Publishing Without Touching My Servers

Plain notes can also be published as public, read-only pages. The obvious design would serve them from my own stack, which would put every random visitor on my smallest machine. So publishing takes a different road:

  • The Tools service snapshots the note and uploads it to a private Cloudflare R2 bucket. Snapshot is the key word: the published page only changes when I click "update", so nobody reads half-finished edits.
  • A separate Next.js site on Vercel reads that bucket with a read-only key and caches each note for as long as it likes. Readers hit Vercel's cache, and my servers never notice.
  • When I update or unpublish, Tools pokes a revalidation endpoint and the cache drops that one note within seconds.
  • Links are random UUIDs (deliberately not time-ordered ones) and survive unpublish and republish. Every page is noindex, and each note is also available as plain Markdown at /<id>.md, because AI agents deserve clean input too.

Encrypted notes can't be published (the server can't read them, which is rather the point), and publishing is a separate permission, so not everyone with Folio gets a megaphone.


The Chatbot (Of Course There Is a Chatbot)

Apparently a portfolio now needs an AI that gushes about its owner, so the /chat page answers questions about me and shuts down everything else. Ask it about binary search and it will politely decline. I am not running a free coding assistant for the entire internet.

The route is refreshingly boring. The browser talks to a route on the Next.js site, and that route calls Vercel AI Gateway directly, streaming the reply back over a plain HTTP response with the AI SDK. No WebSockets to babysit and no event channel to keep alive. Chat traffic never touches my servers, except for one quick question to the gateway: has this visitor had enough?

Swapping the model takes a dropdown in Manager and zero deploys. The site re-reads the choice every minute, so the next question simply lands on the new model. The browser is never trusted to pick one, because the moment it can, somebody picks the most expensive model on the menu.

There are no tools and no MCP server here, because the problem doesn't deserve them. Everything the model needs to know about me is small enough to hand over with every question, straight from the same cached data the site already renders.

Abuse runs into the same Redis limiter as everything else: 30 questions an hour per visitor, 300 an hour overall, and if Redis is down the chat refuses rather than running unmetered. Conversations are never saved on my side. Reload the page and it's gone.


Bare-Metal Deployment

While Kubernetes is the industry standard for container orchestration, running its control plane introduces unnecessary architectural complexity. I wanted absolute simplicity and engineering efficiency. Therefore, the deployment pipeline is built for bare-metal efficiency using GitHub Actions and Podman.

Currently, every service follows a standardized CI/CD workflow. When a deployment is triggered, GitHub Actions builds the image, pushes it to the GitHub Container Registry (GHCR), and SSHs directly into the target virtual machine to orchestrate the rollout. The runner refuses to connect unless the server's host key matches a pinned fingerprint, so it can't be tricked into handing deploy credentials to an impostor. Exposing an SSH port for an external CI runner is a temporary, pragmatic trade-off, but the container execution itself remains heavily locked down.

Noticeably, I do not run the Docker daemon on my servers; I use Podman.

Because Podman is daemonless and integrates natively with Linux systemd, it eliminates background overhead. More importantly, it allows me to enforce strict, unyielding service boundaries. When the deployment script spins up a service, the container is strictly isolated, preventing cross-service interference. Containers get a read-only filesystem, every Linux capability dropped, and a hard memory ceiling. Images are tagged with the exact commit they came from, and if a new container dies on startup, the pipeline rolls back to the previous one on its own. If a machine reboots, systemd brings every container back without me logging in.

Why not Kubernetes, or Docker? Kubernetes for a handful of containers is hiring a 400-person orchestra to play happy birthday. And Docker's daemon runs as root by default, while Podman has no daemon at all and runs every container as an ordinary user. If something ever breaks out of a container, it lands as a nobody, not as root.

Backups: a manual pg_dump before every major update. Have I ever restored one? No. Which makes them Schrödinger's backups: perfectly fine and completely useless at the same time, until the day I open the box. Automated backups with regular restore drills are next on the roadmap, before the universe runs that experiment for me.

Every piece gets a machine of its own. The gateway, each backend service, and PostgreSQL all run on separate hosts and talk over a private network, so a runaway service can't starve its neighbors. Redis lives on the same self-hosted infrastructure, because I apparently enjoy owning things.


Logging & Telemetry

For a long time, observability meant SSH and journalctl. That works right up until the question is "what happened at 3 AM?" and the answer is scattered across machines.

Now a small Grafana Alloy agent runs next to every service and ships everything to Grafana Cloud. Nothing stores metrics or logs on my own hardware, so there is no database to babysit just to watch the other databases.

  • Metrics: The gateway counts every request by route and status, and every gRPC service records its calls, error codes and latency through one shared interceptor. The metrics endpoints listen on localhost only, so nobody on the internet can read them.
  • Logs: Container logs still flow into the system journal; Alloy just picks them up from there, parses the JSON and ships them. Labels stay low-cardinality: never a user ID, an IP or a raw path.
  • Database: PostgreSQL reports per-query timings via pg_stat_statements, with every value replaced by a placeholder. The collector that would ship real query samples stays off, because "send my users' e-mails to a third party" is not an observability strategy.
  • From the outside: Synthetic checks hit the public sites and APIs from Grafana's own probes every few minutes. They catch what internal metrics can't, like DNS breaking or a TLS certificate quietly expiring.

Alerts go to my inbox for the things that actually matter: a service down, errors spiking, a disk filling up, a certificate running out.


Future Roadmap & System Evolution

With the HAProxy/Fiber perimeter, gRPC polyglot microservice grid, and zero-trust storage fully operational, future iterations will focus on infrastructure hardening and resilience:

  • Automated Backups & Restore Drills: Scheduled, off-machine PostgreSQL backups, plus a regular test restore into a throwaway database, because a backup nobody has restored is only a hope.
  • Bastion Host Deployment: Severing direct SSH ingress access to production VMs by routing all GitHub Actions image deployments strictly through an isolated bastion host.
  • Distributed Resilience Patterns: Enhancing the Gateway and service layers with dynamic P95-based timeouts, circuit breaker feedback loops, and retry budgets.

Would I Recommend This Setup?

No. Not unless you have Google- or GitHub-level traffic, or a hard requirement to isolate parts of your system. For almost everyone else, one well-structured application is faster to build, cheaper to run, and won't page you at 3 AM because a service you forgot existed lost its token.

If I outgrew that, I would grow in steps: first a few services talking REST, with separate schemas in one database. Only then gRPC and separate databases, and only where the numbers prove they're needed. This platform sprinted up the staircase on purpose, because the whole point was to find out what's waiting at the top. Spoiler: a lot of YAML.


The Source Code

The architecture is entirely open-source. You can explore the exact implementations, gRPC contracts, and deployment setups across the cluster repositories:

Infrastructure & Contracts

  • common - The centralized Protocol Buffer contracts, generated Go/C# structs, and shared middleware.
  • gateway - The Fiber-based API perimeter, rate limiter, and gRPC translator.

Backend Microservices

  • auth-service - The identity provider, SSO hub, and API key manager (Go).
  • manager-service - The headless CMS backend powering the portfolio data (Go).
  • wallet-service - The personal expense tracker backend (C# / .NET).
  • tools - The Folio and Stencil backend (Go).

Client Applications

  • portfolio-website - The source code for this exact Next.js portfolio website.
  • console-ui - The identity and systems operations dashboard.
  • manager-ui - The dedicated CMS content dashboard.
  • wallet-ui - The expense-tracking dashboard.
  • tools-ui - Folio notes and Stencil, in the browser.
  • folio - The public site for published notes (Next.js).
  • construction-global - The deliberately tiny page for anything still being built.