← Journal
Business Transformation14 min · 2026-07-13· 5-phase teardown

Digitizing 40 retail outlets in 2 months: a distributed-monolith field report

150+ staff, zero digitalization, patchy Kalimantan connectivity, a two-month clock. How I shipped five interconnected production systems — and what running them since taught me about integrity boundaries, AI-assisted OCR, and monitoring you actually read.

01

Issue

The problem, framed precisely.

40 outlets, one source of truth, everything on paper

OCB Group runs a retail network of 40 outlets (OC1–OC40) across Kalimantan, employing more than 150 people. When I took over the digitalization mandate in early 2026, every operational process ran on paper: attendance in notebooks a supervisor physically drove out to verify, KPIs scored by gut feel, deposits reported over WhatsApp with no reconciliation against actual sales, and payroll hand-computed in Excel over three days at month-end with a 5–8% error rate.

40retail outlets
150+daily users
5–8%payroll error rate
2 moto production

The engineering problem was never a single app — it was scale and integrity under bad networks. Forty outlets with divergent workflows, five interdependent domains (attendance, KPI, deposits, payroll, assets), and a hard constraint: employee identity had to stay consistent everywhere, or payroll would pay the wrong person and KPI would score the wrong branch. The failure mode I most feared wasn't downtime — it was silent data drift between systems.

02

Hypothesis

What I believed was true, and why.

One writer, many readers — enforced structurally, not by convention

My hypothesis: the whole system stays correct if — and only if — employee data has exactly one writer, and every other system reads from it without ever writing back. Integrity problems in multi-system estates almost always trace to two services both believing they own the same record. Remove that ambiguity at the architecture level and the class of bug disappears; leave it to discipline and it reappears the first busy month-end.

“Cross-database reads, never cross-database writes. The moment two apps can both mutate the same entity, integrity becomes a runtime hope instead of a structural guarantee.”

The corollary hypothesis: I did not need microservices. I needed clear ownership boundaries. Five apps, each owning its own database, linked by read-only references, would give me the integrity of separation without the operational tax of a service mesh I'd be debugging alone at 11pm.

03

Strategy

The approach and the trade-offs weighed.

A distributed monolith, on purpose

I chose a distributed monolith: five separate apps, each with its own database, joined only by read-only cross-database references and a single server-to-server sync. Each app also uses the stack that fits its problem rather than a forced-uniform runtime — the right tool per job, accepting heterogeneity as a deliberate cost.

  • Attendance — Node.js + Express, MySQL. The single source of truth for employee identity.
  • KPI — Bun + TypeScript, MySQL. AI scoring against 34 weighted SOP tracks.
  • Deposits — Bun + TypeScript, MySQL. AI receipt OCR + IPOS reconciliation.
  • Payroll — Bun + TypeScript, three MySQL pools (two strictly read-only).
  • Assets — Express + PWA, PostgreSQL. Installable as an .apk for field staff.

The sync between them is server-to-server, so it needs no user auth — just a shared migration key. Downstream apps pull the roster on a schedule rather than duplicating write paths. The trade-off I accepted: eventual consistency on the roster (minutes of staleness) in exchange for zero write contention. For retail attendance, minutes of staleness is invisible; a double-write bug is not.

04

Implementation

How it was actually built.

The seams that mattered: sync, OCR, and read-only pools

The roster sync is one endpoint on the source of truth. Every downstream app calls it with the migration key and mirrors a read-only projection:

// absen_management — the ONLY writer of employee identity.
app.get('/api/migration/employees',
  validateMigrationKey, // X-Migration-Key, server-to-server
  async (req, res) => {
    const employees = await User.findAll({
      where: { is_deleted: false },
      attributes: ['user_id', 'name', 'username',
        'retail_id', 'category_user', 'upline'],
    });
    res.json({ data: employees, synced_at: new Date() });
  });

The highest-ROI AI feature was deposit OCR. A cashier photographs a paper slip; a vision model extracts the numbers; the form fills itself. Bun + a Svelte 5 frontend keeps the bundle tiny because Kalimantan connectivity is unreliable — every kilobyte is a second of someone's day.

// ai.ts — deposit-slip OCR. Output is validated before it touches the DB.
export async function scanDepositSlip(imageBuffer: Buffer) {
  const base64 = imageBuffer.toString('base64');
  const res = await fetch(AI_ENDPOINT, {
    method: 'POST',
    headers: { Authorization: `Bearer ${AI_KEY}` },
    body: JSON.stringify({
      model: 'claude-sonnet',
      messages: [{ role: 'user', content: [
        { type: 'image_url',
          image_url: { url: `data:image/jpeg;base64,${base64}` } },
        { type: 'text',
          text: 'Extract total_amount, date, items. Return JSON only.' },
      ] }],
    }),
  });
  return res.json(); // reconciled against IPOS before persisting
}

Payroll was the most complex domain — really a data pipeline wearing a payroll app's clothes, pulling from five-plus sources. The structural safeguard was a three-pool setup with two pools read-only by contract, so payroll can physically never corrupt the data other apps depend on:

// db.ts — two of three pools are read-only by contract, not by convention.
export const pools = {
  kpi:     createPool({ database: 'kpi_ocb',          connectionLimit: 10 }), // read-only
  absen:   createPool({ database: 'absen_management', connectionLimit: 10 }), // read-only
  payroll: createPool({ database: 'ocb_payroll',      connectionLimit: 10 }), // read/write
};

Operationally I chose boring on purpose: all five apps on a single Hyper-V VM reached over Tailscale, fronted by a Cloudflare Tunnel, managed with PM2. No Kubernetes. And monitoring that lands where I already am — a Grafana board nobody opens is worse than a Telegram alert on the phone in my pocket:

// One error-handling pattern, every app. Alerts arrive in ~5 seconds.
process.on('uncaughtException', (err) => {
  telegramAlert(`\uD83D\uDD34 UNCAUGHT: ${err.message}\n${err.stack}`);
  process.exit(1);
});
app.use((err, req, res, next) => {
  logger.error(err);
  if (err.status >= 500) telegramAlert(`\uD83D\uDD34 ${req.method} ${req.path}: ${err.message}`);
  res.status(err.status || 500).json({ error: err.message });
});
05

Summary

Outcome, evidence, and what I'd change.

What held up, what broke, what I'd change

In production the numbers moved: deposit entry dropped from 10 minutes to 2 per cashier (~320 minutes/day across the network), and payroll fell from three days at 5–8% error to about one hour at 0.3%. The read-only-pool decision paid for itself — in months of operation, not one cross-system corruption originated in payroll.

“I used to spend three days on payroll. Now it's one hour. Sometimes attendance and IPOS still don't match, so I review those by hand — but three days became one hour.”

HR / Payroll lead

The bugs that hurt were exactly where my hypothesis predicted — cross-system sync. Moving an employee between outlets updated attendance instantly but left assets pointing at the old branch until the next pull; the fix was an event that fans an assignment change out to every affected app. Timezones were the other trap: everything is Asia/Makassar (UTC+8), but some external APIs return UTC, and an unconverted 23:00 shift silently lands on the wrong payroll day.

  • A single-writer identity store was the highest-leverage decision in the entire estate.
  • Read-only-by-contract beats read-only-by-discipline; encode integrity in the pool, not the code review.
  • AI accelerates OCR and scoring but is fallible — validate its output at a boundary and let humans decide.
  • Monitoring you'll actually read (Telegram) beats sophisticated dashboards no one opens.
  • Every honest user complaint was the next feature: crumpled-receipt misreads → blur detection; indoor GPS drift → WiFi-based fallback.

What I'd change: I under-invested early in idempotent sync jobs, so a retried pull occasionally double-counted before I made writes idempotent. If I rebuilt it, idempotency keys would be day-one, not a month-two patch.

Written by Ridha Fahmi Junaidi · AI Implementation Lead · AI Integration Engineer

Next
One /v1 to rule them: designing a provider-agnostic AI gateway→