MiniBank is a small banking app split into four services, plus a PostgreSQL database and a Redis queue. In the browser you open accounts and move money between them; every transfer is recorded and triggers an SMS-style alert. I wrote the four services and the Docker Compose file that runs them; the Dockerfiles came with the DevOps and container platforms course at Execute Tech Academy, where this was the first phase. (The next phase, pushing the images to Amazon ECR, has its own article.)

The services

  • frontend: the web page, served by Nginx on port 8080.
  • accounts-api (Python, Flask and Gunicorn): creates accounts and moves money.
  • transactions-api (Node.js, Express): records every transfer and queues an alert.
  • notifier (Python): waits on the queue and prints each alert in its logs.
  • db and redis: ready-made PostgreSQL 16 and Redis 7 images.

Moving money safely

The accounts API does the part that must never go wrong. It locks both accounts' rows before reading the balances, always in the same order (by id), so two transfers between the same pair of accounts can't deadlock each other. It checks the balance inside that transaction, and money is a Decimal, never a float:

@app.post("/transfer")
def transfer():
    """Internal endpoint called by transactions-api. Moves money atomically."""
    body = request.get_json(force=True)
    src, dst = int(body["from"]), int(body["to"])
    amount = Decimal(str(body["amount"]))
    if src == dst or amount <= 0:
        return {"error": "invalid transfer"}, 400
    with db() as conn, conn.cursor() as cur:
        # Lock both rows in a fixed order to avoid deadlocks.
        cur.execute("SELECT id, balance FROM accounts WHERE id IN (%s, %s) ORDER BY id FOR UPDATE", (src, dst))
        balances = dict(cur.fetchall())
        if len(balances) != 2:
            return {"error": "account not found"}, 404
        if balances[src] < amount:
            return {"error": "insufficient funds"}, 409
        cur.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, src))
        cur.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst))
    return {"status": "ok"}

A transfer in three steps

The transactions API is what the website talks to. It asks the accounts API to move the money (one container calling another by its service name), records the transaction, and only then queues the alert:

app.post("/transactions", wrap(async (req, res) => {
  const { from, to, amount } = req.body;

  // 1. Ask accounts-api to move the money (container-to-container call by service name).
  const transfer = await fetch(`${ACCOUNTS_URL}/transfer`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ from, to, amount }),
  });
  if (!transfer.ok) {
    return res.status(transfer.status).json(await transfer.json());
  }

  // 2. Record the transaction.
  const { rows } = await pool.query(
    "INSERT INTO transactions (from_account, to_account, amount) VALUES ($1, $2, $3) RETURNING *",
    [from, to, amount]
  );
  const tx = { ...rows[0], amount: Number(rows[0].amount) };

  // 3. Queue a notification for the notifier worker.
  await redis.lPush("notifications", JSON.stringify(tx));

  res.status(201).json(tx);
}));

Alerts that don't slow transfers down

Sending an alert shouldn't hold up the transfer, so the notifier runs on its own. It blocks on the Redis list until a job arrives, and if Redis is unavailable it waits three seconds and tries again instead of crashing:

while True:
    try:
        _, raw = r.blpop("notifications")
        tx = json.loads(raw)
        print(
            f"[{channel}] Debit alert: account {tx['from_account']} sent "
            f"NGN {tx['amount']:,.2f} to account {tx['to_account']} (tx #{tx['id']})",
            flush=True,
        )
    except redis.exceptions.ConnectionError as e:
        print(f"redis unavailable ({e}), retrying in 3s", flush=True)
        time.sleep(3)

Starting in the right order

In the Compose file, the APIs only start once the database and Redis answer their health checks:

  db:
    image: postgres:16-alpine
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      retries: 10
    networks: [backend-net]

  transactions-api:
    depends_on:
      db: { condition: service_healthy }
      redis: { condition: service_healthy }
      accounts-api: { condition: service_started }
    networks: [frontend-net, backend-net]

Two networks

The website is only on frontend-net, the database and Redis only on backend-net, and only the two APIs join both. From the website's container, the name db doesn't even resolve.

Data and secrets

PostgreSQL keeps its data in a named volume, so docker compose down keeps it (only down -v deletes it). The database credentials come from an .env file made from .env.example, and .env is never committed.

The images

The course's Dockerfiles keep the images small and quick to rebuild: each copies its dependency list before the code, so the install step stays cached until the dependencies change, and each switches to a non-root user before it starts. With them and the Compose file, the whole stack starts with one command: docker compose up -d.