STAFFCHAPTER 31

The lending tech stack: origination, decision engine, loan management

A lending business is a handful of systems that each own one kind of fact. Draw the lines between them wrongly and a timeout pays a customer twice, or asks a bureau three times about one person

70 MINLENDING AND CREDITUPDATED 2026-11-14
PREDICT

A decision service asks a credit bureau for a report once per application. It waits 0.5 seconds, and the bureau takes 0.8 seconds to answer, so every call times out. The service is written to try up to three times in all before giving up. The bureau records an enquiry for each request it receives, even when the caller has stopped waiting. 23 applications arrive in a day. How many enquiries does the bureau record, and how many reports does the service receive?

A lending business is software that answers four questions again and again. Should we lend to this person? What did we agree? What is owed today? Where is the money? Each question has an owner, and most of the damage in a young lender comes from two systems both believing they own the answer. This chapter draws the systems, names what each one owns, builds a small version of the middle two, and then asks the commercial question: which of these should a 15-person company write itself?

The chapter’s company is a lending startup in Lagos with 15 people, described without a name. Its lab data is Owoleaf’s loan book, because the lab has one book. Ikenga and Ikechi are the startup’s credit lead and engineer.

The systems, and the one fact each owns

Seven systems appear in almost every lender, whether they are separate programs or tabs in one. The table says what each does and what it must be the final word on.

System What it does The one thing it owns
Origination The app, USSD menu or merchant checkout: collects the application and the customer’s consent, shows the offer, takes the acceptance What the customer was shown and what they agreed to
KYC and identity Checks who the applicant is (the Compliance course owns the detail) That this person is who they say, and the keys that find their bureau file
Bureau and data integrations Fetch bureau reports and other consented data Nothing: they return copies of other people’s records
Decision engine Applies the credit policy to the inputs and returns an offer or a decline Why a decision was made, under which policy version
Loan-management system (LMS) Holds each contract, its schedule, its payments and its status What was agreed, what is owed today and for how long it has been overdue
Servicing and collections Reminders, calls, promises, restructures (collections) The contact history and the promises
Accounting The general ledger and the reports built from it What was booked, in which period

The cash itself lives outside all seven: in a partner bank’s account, a wallet ledger or a switch’s settlement position (settlement and payouts in Payments). A lender’s books say what it believes it holds there, and reconciliation proves it.

Originationowns: what was shownDecision engineowns: whyLoan managementowns: what is owedLedgerowns: what was bookedapplicationoffer, then acceptBureau and KYCcopies of others’ recordsPayout rail, bankowns: the cashCollectionsreads the LMSdashed boxes belong to someone else: the lender can ask them, never overrule them

The rule that falls out of the picture is one owner per fact. The engine records a decision and does not decide that a loan exists. The LMS says a loan exists and does not decide credit. Origination does not hold a balance. When two systems each keep a balance, one of them is wrong by the end of the month, and nobody knows which.

One application, end to end

Follow one salary-advance application through the stack. The lab builds the middle: the decision engine and the LMS. Origination is a script that replays a day of Owoleaf’s real applications.

  1. Origination collects the amount, the product and the customer’s consent, and gives the application a reference, APP-86, before anything is sent. The reference is the application’s identity for the rest of its life.
  2. KYC and identity have already tied the customer to a verified identity. The bureau’s file is found through that key (credit data in Nigeria).
  3. The decision engine asks the bureau for a report with the customer’s consent reference and a stated purpose, reads the lender’s own wallet data, applies the policy and answers: approved with an amount, declined with a reason, or refer to a person.
  4. Origination shows the offer. The customer accepts or walks away; in the book 6% of approved applicants never accept.
  5. On acceptance the LMS books the loan: contract, schedule and ledger entries, in one transaction, under a disbursement reference.
  6. The payout rail sends the net amount (paying out). Its answer, success, failure or in progress, comes back asynchronously and updates the disbursement’s state.
  7. Servicing collects each instalment; collections takes over when one is missed; accounting reads the ledger.

Steps 3 and 5 are the two places where a repeated message costs money. A repeated decision request asks the bureau again. A repeated booking request lends twice. Both are fixed the same way, and it is the most reusable idea in the chapter: the caller makes an identifier once, sends it with every attempt, and the receiver returns what it already did when it sees the identifier again. Payments teaches the mechanism in full (idempotency and moving money exactly once); the lab applies it twice.

The decision engine

A decision engine is a service that takes an application and the facts around it and returns a decision. Four design choices separate one a lender can defend from a pile of if statements.

The policy is data, with a version. The lab’s engine keeps its cut-offs, enquiry ceiling and thin-file cap in one POLICY dictionary with a version. Every stored decision carries the version that made it. When the credit lead changes a cut-off, the version changes, and nobody has to guess which rule declined a customer in March. The cut-offs themselves come from decisions, limits and pricing; writing the full policy document is the credit policy chapter’s subject in this module.

The decision record keeps its inputs. The record holds the bureau report as it was returned, the wallet inflow the engine computed, the policy version and the outcome. A bureau changes its answer tomorrow; the record does not. This is what lets you answer a customer who asks why they were declined, replay yesterday’s applications under a new policy, and give a model validator the data they need. Model risk returns to this.

It fails closed. When the bureau does not answer, the engine has three choices: approve without the report, decline, or send the application to a person. Approving unseen is a credit decision nobody made. Declining punishes customers for the lender’s outage. The lab’s engine answers refer and records why. Whether a human can then clear the queue the same day is an operations question that the stack must make answerable.

It asks the bureau once. Credit data in Nigeria showed that every request writes an enquiry onto the customer’s file. So the engine makes one request per decision, keeps its own count of requests per customer, and subtracts them before it applies the enquiry ceiling: the report includes the enquiry the engine has itself caused, and counting it against the customer would decline people for being looked at by this lender. The bureau’s 503 answers in the mock are sent before the request is processed, so the engine retries those. A timeout leaves the outcome unknown, so the engine does not retry it. With a real bureau you read its documentation for which failures are safe to repeat; do not assume.

The decision engine does not own the customer’s file or the loan. It returns an offer and stores why. That keeps it replaceable: a vendor’s engine or a new model can sit behind the same endpoint, provided it returns the same record.

What the book used that a live engine cannot

Replaying Owoleaf’s recorded applications through the lab’s engine gives the same approve-or-decline answer on 18 of the 23 applications of 16 June 2026, and a different one on five. The engine approved four that the book had declined and declined one that the book had approved, and all five turn on the amount rule (amount_below_product_minimum): the cap on the amount is a multiple of monthly inflow, and the two programs measure inflow differently. The cause is in the generator, loans.py. It takes all the money a customer funded into the wallet, by bank transfer or card, over the whole wallet data (which ends on 29 June 2026), including money that arrived after the application, and divides it by the months from sign-up to the cut-off of 28 October 2026. A live engine can see only the 90 days before the application, so the lab’s engine divides that by 1 to 3 months. Writing a credit policy finds the same cause from the policy side: two definitions of monthly inflow, and 460 of 3,645 approved loans break the policy when it counts the 90 days before the application. Some customers look poorer to the live engine than to the book, some richer.

This is not a bug in the engine. It is the leak that decisions, limits and pricing warns about, seen from the other side: a rule tested on history can use facts that were not available at the time. It is also a reason to keep decision records. A decision that stored the inflow it used can be audited. One that recomputed income from today’s data cannot.

The loan-management system

The LMS is the system of record for the contract. It holds, for each loan, the principal, the fee, the rate, the schedule, every payment and the status. The decision engine says yes. The LMS says what you agreed and what is owed.

Three properties matter more than features.

One transaction. Booking a loan writes the loan row, every instalment of its schedule and the ledger entries together. If the process dies half-way, none of it exists, and a retry starts clean. A system that writes the loan and then, separately, the ledger, will one day have a loan with no entries or entries with no loan, and finding which costs a day of someone’s time.

Idempotent on a reference. The booking carries a disbursement reference (DISB-APP-86) that the caller made. The store looks it up first and returns the existing loan if it finds one. A UNIQUE constraint on the same column is the second line of defence: if two requests race past the lookup, the database refuses the second.

Money in integer kobo. The lab’s schedule is the equal-instalment formula from interest, APR, fees and amortisation, with the last principal taking the rounding. The check in the lab confirms that the LMS’s function reproduces every one of the book’s 372 schedules to the kobo.

The ledger entries for a disbursement are three lines. For a ₦28,000 salary advance with a 1% fee: debit loans receivable ₦28,000 (what the customer owes), credit cash ₦27,720 (what left), credit fee income ₦280 (what the lender kept). Debits ₦28,000 equal credits ₦27,720 + ₦280 = ₦28,000. The lab books the fee as income on day one, which is a simplification: spreading a fee over the life of the loan is the subject of the chapter on tax and accounting for lenders.

Where the money and the data live

Four stores hold four kinds of fact, and the lab has all four: the decision log (the engine’s engine.sqlite), the contracts and the ledger (the LMS’s lms.sqlite), the bureau’s enquiry log (in the bureau’s memory), and the lender’s own wallet data (finance.sqlite, read only). None of them is the cash. Three habits keep them honest:

  • A check across stores, run daily. The lab’s checks.py asks whether the ledger balances, whether loans receivable equals the principal in the contracts, whether each loan has one posting, and whether the bureau recorded one enquiry per decision. A check that only looks inside one system cannot see the disagreement between two.
  • Copies are marked as copies. A bureau report in the decision record is a snapshot. The LMS’s status is derived from its schedule and payments, not typed in.
  • Cross-border storage is a legal question. Hosting customer data abroad, as many cloud arrangements do, brings in the data protection law’s rules on transfers.

Part VIII of the Nigeria Data Protection Act 2023 governs cross-border transfers of personal data: commentary in the search results lists section 41 (the basis for transfer), section 42 (adequacy of protection, judged by the Nigeria Data Protection Commission) and section 43 (other bases where there is no adequacy finding). The results quote law-firm and commissioned commentary, not the Act’s own words for these sections, and one commentator describes transfers as prohibited by default while others do not use that framing, so read the sections themselves before you choose where a stack is hostedas of 2026-11. The Commission’s General Application and Implementation Directive 2025 is described in law-firm commentary as issued on 20 March 2025 and in force from 19 September 2025, with Article 45 and Schedule 5 giving guidance on cross-border transfers; the search results did not return the Directive’s own text for these provisionsas of 2026-11.

The Federal Competition and Consumer Protection Commission’s Digital, Electronic, Online or Non-Traditional Consumer Lending Regulations 2025 are reported, in search results quoting secondary sources, to bar digital lenders from accessing borrowers’ contact lists, call logs and photos, to require compliance with the Data Protection Act and the Commission’s directive, to take effect on 21 July 2025 with registration within 90 days, and to set 5 January 2026 as a later compliance deadline. This chapter could not confirm the exact wording of the contact-list provision in the official text, and reports of the dates differ, so take every one from the Regulations themselvesas of 2026-11. For a stack the practical consequence is on the origination side: what the app asks the phone for is a design decision with a legal edge, and the decision engine should only be given inputs the lender may lawfully collect. Consumer protection and digital lending rules reads the Regulations in full.

Integrations and how they fail

Every line leaving the lender’s boundary in the diagram can fail in four ways: it refuses (a clear error), it is slow, it answers wrongly, or it does something and then fails to tell you. The fourth is the dangerous one, and the lab’s bureau shows it, because a slow bureau still writes its enquiry.

Integration Typical failure What the stack does
Bureau Slow; refuses; thin file; field missing (score is null) One call per decision; fail closed to a person; treat a null score as thin, never as zero
KYC and identity Name mismatch; BVN where a NIN was expected Do not decide until it resolves; keep the key you sent
Payout rail Answer 09 in progress; timeout; reversal later Disbursement is a state, not an event: requery before you retry
Repayment rail Insufficient funds; mandate revoked; card expired Retry rules per rail (collecting)
Collections tools A duplicate SMS; a call at 23:00 The LMS decides who is due; the tool only contacts
Accounting Posts the same event twice; period closed Post from an event reference, once

Two habits cover most of the table. First, make the reference before the first attempt, never inside the retry loop: a client that makes a new app_ref on every try defeats the receiver’s idempotency check and cannot be told apart from a new customer. Second, a timeout means unknown, not failed. The question that follows is: how do I find out what happened? A payout is answered by a status request on its session id; a bureau request, in the mock, by listing the enquiries recorded for the customer.

Build or buy

A lender can write each of these systems, rent it or take it from a partner. The wrong frame is “build everything because we are engineers” or “buy everything because we are small”. The useful frame asks of each system four questions.

Question If yes If no
Does it make our lending different from the next lender’s (our rules, our data, our offer)? Own it, or own its core Buy or rent it
Is it a solved problem many lenders share (a schedule, a ledger, a mandate)? Buy or rent it Build
Can we leave? Can we export every contract, schedule and posting in a format we can load elsewhere? Renting is safe Treat the contract as a long-term commitment
Does it touch money or customer data? Add the cost of controls and audit to either option Compare on cost and speed

For most young lenders the decision engine’s policy and the customer experience in origination are where the difference lives, and the LMS and ledger are where the shared problem lives. That is a pattern, not a rule: a lender whose edge is a servicing model, or one with unusual loan structures, may find the LMS is the product. Nothing here says which provider to use, and the chapter names none. What a founder can decide is what must stay inside the company’s control: the policy, the decision records, the customer data and the ability to export.

A cost model you can change

The lab’s buildbuy.py compares owning an LMS with renting one over 36 months. Every input is illustrative and sits at the top of the file.

  • Rent: ₦800,000 a month plus ₦120 per active loan per month, live in 2 months.
  • Build: 2 engineers for 6 months at ₦1,500,000 a month each, ₦18,000,000 in all; then one engineer to maintain it and ₦150,000 a month of hosting.
  • Delay: each month later than the rented system costs ₦3,000,000 of contribution that was never earned.

The arithmetic a reviewer can redo: renting costs 36 × (₦800,000 + ₦120 × N) = ₦28,800,000 + ₦4,320 × N. Building costs ₦18,000,000 + 36 × (₦1,500,000 + ₦150,000) = ₦18,000,000 + ₦59,400,000 = ₦77,400,000, or ₦89,400,000 once the 6 − 2 = 4 months of delay at ₦3,000,000 are added. Equal cost is where ₦4,320 × N = ₦77,400,000 − ₦28,800,000 = ₦48,600,000, so N = 11,250 active loans, and 14,028 (rounded up from 14,027.8) with the delay.

Three readings of the result. Below about eleven thousand active loans the rented system is cheaper on these inputs, and a 15-person company is far below that. The fixed cost of building does not shrink with the loan count, which is why building looks bad early and good later. And the model leaves out what matters most: the ₦ cost of being unable to leave, the risk of a rented system’s outage in the middle of a collections run, and the engineering time diverted from the part that makes the company different. Change the inputs in step 8 and watch which ones move the crossover most. The per-loan fee and the engineer’s cost do, which tells you what to negotiate and what to measure.

Where it goes wrong

  • Two balances. The app and the LMS each keep one. They disagree on the 28th and the next hours go to finding out which is right.
  • A retry loop that mints identifiers. A fresh app_ref or disbursement reference on each attempt makes every duplicate look new.
  • Retrying a timeout as if it were a refusal. The lab’s break writes 69 enquiries for 23 applications.
  • A decision with no record. The bureau’s answer, the inflow and the policy version were all live variables. Without them you cannot answer a complaint.
  • Failing open. An engine that approves when the bureau is down becomes the cheapest way to get a loan in the week of the outage.
  • Writing the loan and the ledger separately. A crash between the two leaves a loan with no entries.
  • Testing a policy on history without asking what the live system can see. The lab’s five disagreements out of 23 come from one such assumption.
  • Choosing a build-or-buy by the cheapest line. The exit cost and the delay are on no invoice.
LAB Build a decision engine and a loan-management store, and run a day through them ~60 MIN
YOU NEEDPython 3.9 or later (standard library only)curllabs/finance with the default book built: python3 generate.py && python3 loans.py (about 5 seconds)Three terminals open in labs/financeNo Docker, no packages

You build five small programs in a new folder, labs/finance/stack/. Terminal 1 runs the mock bureau, terminal 2 the decision engine, terminal 3 everything else. The engine and the LMS only read ../data/finance.sqlite; they write their own stores in stack/.

1. Start the bureau and pick the day. In terminal 1, start the mock bureau (it needs the loan book: run python3 loans.py after generate.py if data/ has no loan tables). In terminal 3, make the folder and find the busiest day of applications.

# terminal 1, in labs/finance
python3 mock_bureau.py --quiet

# terminal 3, in labs/finance
mkdir -p stack && cd stack
python3 - <<'PY'
import sqlite3
db = sqlite3.connect("../data/finance.sqlite")
print(*db.execute("""SELECT substr(applied_at, 1, 10), COUNT(*) FROM applications
                     GROUP BY 1 ORDER BY 2 DESC LIMIT 1""").fetchone())
PY

Terminal 1 prints mock bureau on http://127.0.0.1:8103 (Bearer bu_test_owoleaf_mock) and then stays quiet. Terminal 3 prints:

2026-06-16 23

23 applications arrived on 16 June 2026. The bureau keeps its enquiries in memory, so restarting it gives a clean count: do that now if you have used it before.

2. Write and start the decision engine. Save this as stack/engine.py. Read POLICY first: the cut-offs are the lab’s, from loans.py. Then read bureau(), which retries a 503 and does not retry a timeout, and decide(), which fails closed.

#!/usr/bin/env python3
"""A small decision-engine service. Standard library only.

    python3 engine.py                       # http://127.0.0.1:8104, bureau at http://127.0.0.1:8103

POST /decisions  {app_ref, customer_ref, consent_ref, product, requested_kobo, instalments, applied_on}
GET  /decisions/<app_ref>                    the stored record: inputs, bureau snapshot, policy version
GET  /policy                                 the rules in force
Every number in POLICY is ILLUSTRATIVE (the same rules as labs/finance/loans.py).
"""
import argparse, datetime as dt, json, socket, sqlite3, threading, time
import urllib.error, urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

NAIRA = 100
POLICY = {
    "version": "2026-11-18.1",
    "score_cutoff": {"SAL": 580, "PL": 620, "BNPL": 560, "SME": 600},
    "max_enquiries_90d": 6,
    "max_delinquent_12m": 1,                  # two or more declines
    "min_monthly_inflow_kobo": 5_000 * NAIRA,  # not for BNPL
    "thin_file_cap_kobo": 50_000 * NAIRA,
}
BUREAU_KEY = "bu_test_owoleaf_mock"
RETRY_ON_TIMEOUT = False       # the one setting the break at the end of the lab changes
LOCK = threading.Lock()


class Engine:
    def __init__(self, a):
        self.a = a
        self.store = sqlite3.connect(a.db, check_same_thread=False)
        self.store.execute("""CREATE TABLE IF NOT EXISTS decisions (
            app_ref TEXT PRIMARY KEY, customer_ref, product, requested_kobo, decision, reason, approved_kobo,
            policy_version, bureau_status, bureau_calls, snapshot, decided_at)""")
        self.own = {}                       # customer_ref -> bureau requests this engine has made
        self.data = sqlite3.connect(f"file:{a.data}/finance.sqlite?mode=ro", uri=True, check_same_thread=False)
        self.products = {r[0]: r for r in self.data.execute(
            "SELECT code, rate_bps_per_period, fee_bps, min_kobo, max_kobo, period_days FROM loan_products")}

    # ---- the bureau call: one request per decision
    def bureau(self, body):
        """Returns (status, report, calls). A 503 is refused before the bureau does anything: retry it.
        A timeout leaves the outcome unknown, and the mock records an enquiry either way: do not retry."""
        calls = 0
        for attempt in range(1 + self.a.bureau_retries):
            req = urllib.request.Request(self.a.bureau + "/reports", data=json.dumps(body).encode(), method="POST",
                headers={"Authorization": f"Bearer {BUREAU_KEY}", "Content-Type": "application/json"})
            calls += 1
            try:
                with urllib.request.urlopen(req, timeout=self.a.bureau_timeout) as r:
                    return "ok", json.load(r), calls
            except urllib.error.HTTPError as e:
                if e.code == 503:
                    time.sleep(0.05)
                    continue
                return f"http_{e.code}", None, calls
            except (socket.timeout, TimeoutError, urllib.error.URLError):
                if RETRY_ON_TIMEOUT:
                    continue
                return "timeout", None, calls
        return "unavailable", None, calls

    def inflow(self, customer_ref, applied_on):
        """Wallet money in over the 90 days before the application, per month (30 to 90 days of history)."""
        cid, signup = self.data.execute("SELECT id, substr(signup_at,1,10) FROM customers WHERE ref=?",
                                        (customer_ref,)).fetchone()
        total = self.data.execute(
            """SELECT COALESCE(SUM(amount_kobo),0) FROM transactions WHERE customer_id=? AND status='succeeded'
               AND kind IN ('funding_transfer','funding_card') AND created_at >= date(?, '-90 days')
               AND created_at < ?""", (cid, applied_on, applied_on)).fetchone()[0]
        tenure = (dt.date.fromisoformat(applied_on) - dt.date.fromisoformat(signup)).days
        return int(total / (max(30, min(90, tenure)) / 30))

    def decide(self, b):
        p = b["product"]
        _, _, _, lo, hi, _ = self.products[p]
        body = {"customer_ref": b["customer_ref"], "consent_ref": b["consent_ref"],
                "purpose": "credit_application", "as_of": b["applied_on"]}
        status, rep, calls = self.bureau(body)
        self.own[b["customer_ref"]] = self.own.get(b["customer_ref"], 0) + calls
        snap = {"bureau_status": status, "report": rep, "inflow_kobo": None}
        if status != "ok":                                   # fail closed: a person looks at it
            return "refer", f"bureau_{status}", 0, snap, calls
        score = rep.get("score")
        thin = score is None
        # The report counts the enquiry this engine has itself caused. Take its own requests out.
        enquiries = rep["enquiries_90d"] - self.own[b["customer_ref"]]
        inflow = self.inflow(b["customer_ref"], b["applied_on"])
        snap.update(inflow_kobo=inflow, enquiries_excluding_us=enquiries)
        if not thin and score < POLICY["score_cutoff"][p]:
            return "declined", "score_below_cutoff", 0, snap, calls
        if enquiries > POLICY["max_enquiries_90d"]:
            return "declined", "too_many_recent_enquiries", 0, snap, calls
        if not thin and rep["delinquent_12m"] > POLICY["max_delinquent_12m"]:
            return "declined", "recent_delinquency", 0, snap, calls
        if inflow < POLICY["min_monthly_inflow_kobo"] and p != "BNPL":
            return "declined", "insufficient_income_evidence", 0, snap, calls
        n = b["instalments"]
        cap = int(inflow * (1.0 if p in ("SAL", "BNPL") else 2.0 * n / 3)) // 100_000 * 100_000
        if thin:
            cap = min(cap, POLICY["thin_file_cap_kobo"])
        approved = max(0, min(b["requested_kobo"], cap, hi))
        if approved < lo:
            return "declined", "amount_below_product_minimum", 0, snap, calls
        return "approved", None, approved, snap, calls

    def handle(self, b):
        with LOCK:
            row = self.store.execute("SELECT * FROM decisions WHERE app_ref=?", (b["app_ref"],)).fetchone()
            if row:
                rec = self.record(row)
                if (rec["customer_ref"], rec["product"], rec["requested_kobo"]) != (
                        b["customer_ref"], b["product"], b["requested_kobo"]):
                    return 409, {"code": "APP_REF_REUSED", "message": "same app_ref, different application"}, False
                return 200, rec, True
            decision, reason, approved, snap, calls = self.decide(b)
            self.store.execute("INSERT INTO decisions VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", (
                b["app_ref"], b["customer_ref"], b["product"], b["requested_kobo"], decision, reason, approved,
                POLICY["version"], snap["bureau_status"], calls, json.dumps(snap),
                dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds")))
            self.store.commit()
            return 200, self.record(self.store.execute("SELECT * FROM decisions WHERE app_ref=?",
                                                       (b["app_ref"],)).fetchone()), False

    def record(self, row):
        keys = ["app_ref", "customer_ref", "product", "requested_kobo", "decision", "reason", "approved_kobo",
                "policy_version", "bureau_status", "bureau_calls", "snapshot", "decided_at"]
        rec = dict(zip(keys, row))
        rec["snapshot"] = json.loads(rec["snapshot"])
        if rec["decision"] == "approved":
            _, rate_bps, fee_bps, lo, hi, pdays = self.products[rec["product"]]
            rec["offer"] = {"principal_kobo": rec["approved_kobo"], "fee_kobo": rec["approved_kobo"] * fee_bps // 10_000,
                            "rate_bps_per_period": rate_bps, "period_days": pdays}
        return rec


class Handler(BaseHTTPRequestHandler):
    engine = None

    def log_message(self, *a):
        pass

    def send(self, status, obj, replayed=False):
        body = json.dumps(obj, indent=2).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        if replayed:
            self.send_header("Idempotent-Replayed", "true")
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/health":
            return self.send(200, {"ok": True})
        if self.path == "/policy":
            return self.send(200, POLICY)
        if self.path.startswith("/decisions/"):
            row = self.engine.store.execute("SELECT * FROM decisions WHERE app_ref=?",
                                            (self.path.split("/")[-1],)).fetchone()
            return self.send(200, self.engine.record(row)) if row else self.send(404, {"code": "NOT_FOUND"})
        self.send(404, {"code": "NOT_FOUND"})

    def do_POST(self):
        if self.path != "/decisions":
            return self.send(404, {"code": "NOT_FOUND"})
        try:
            b = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
            for k in ("app_ref", "customer_ref", "consent_ref", "product", "requested_kobo", "instalments", "applied_on"):
                b[k]
            assert b["product"] in self.engine.products and isinstance(b["requested_kobo"], int)
        except Exception:
            return self.send(400, {"code": "BAD_REQUEST"})
        status, obj, replayed = self.engine.handle(b)
        self.send(status, obj, replayed)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=8104)
    ap.add_argument("--bureau", default="http://127.0.0.1:8103")
    ap.add_argument("--data", default="../data", help="folder with finance.sqlite (read only)")
    ap.add_argument("--db", default="engine.sqlite", help="the engine's own store of decisions")
    ap.add_argument("--bureau-timeout", type=float, default=3.0)
    ap.add_argument("--bureau-retries", type=int, default=2, help="extra tries after a 503")
    a = ap.parse_args()
    Handler.engine = Engine(a)
    print(f"decision engine on http://127.0.0.1:{a.port}, policy {POLICY['version']}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", a.port), Handler).serve_forever()


if __name__ == "__main__":
    main()

In terminal 2:

cd stack
python3 engine.py
decision engine on http://127.0.0.1:8104, policy 2026-11-18.1

3. Send one application, then send it again. From terminal 3, post the application the loan book recorded as APP-86: a ₦28,000 salary advance. Print a summary of the answer, then repeat it, then change the amount under the same reference.

BODY='{"app_ref":"APP-86","customer_ref":"C0000193","consent_ref":"consent-APP-86","product":"SAL","requested_kobo":2800000,"instalments":1,"applied_on":"2026-06-16"}'
curl -s -X POST localhost:8104/decisions -d "$BODY" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d['decision'], d['approved_kobo'], d['offer']['fee_kobo'], d['policy_version'], d['bureau_calls'], d['snapshot']['report']['score'])"
curl -s -D - -o /dev/null -X POST localhost:8104/decisions -d "$BODY" | grep -iE "^HTTP|idempotent"
curl -s -D - -o /dev/null -X POST localhost:8104/decisions -d "${BODY/2800000/3000000}" | grep -iE "^HTTP"
curl -s localhost:8103/enquiries -H "Authorization: Bearer bu_test_owoleaf_mock" | python3 -c "import json,sys; print(len(json.load(sys.stdin)['enquiries']), 'enquiries')"
approved 2800000 28000 2026-11-18.1 1 None
HTTP/1.0 200 OK
Idempotent-Replayed: true
HTTP/1.0 409 Conflict
1 enquiries

The offer is 2,800,000 kobo (₦28,000) with a 28,000 kobo fee (₦280), made under policy 2026-11-18.1 after one bureau call. The score is None: this customer is a thin file at the bureau. Your own record of the loan appears in the bureau’s tradelines, because the book already holds the loan this application led to. That is a replay artefact: a live engine would not see it. The second post is answered from the store with Idempotent-Replayed: true and makes no bureau call. The third reuses the reference for a different application and is refused with 409. The bureau recorded one enquiry for three requests.

4. Write the LMS and the day’s origination script. Save lms.py: the store that books a loan, its schedule and its ledger entries in one transaction, once per disbursement reference.

"""A small loan-management store: the contract, the schedule and the ledger. Standard library only.

book_loan() is the only way money enters the books. It is idempotent on the disbursement reference and
writes the loan, its schedule and its ledger entries in one transaction. Money is integer kobo.
"""
import datetime as dt
import sqlite3

SCHEMA = """
CREATE TABLE IF NOT EXISTS loans (loan_id TEXT PRIMARY KEY, app_ref TEXT, customer_ref TEXT, product TEXT,
    principal_kobo INTEGER, fee_kobo INTEGER, net_kobo INTEGER, instalments INTEGER, disbursed_on TEXT,
    disbursement_ref TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS schedule (loan_id TEXT, instalment INTEGER, due_date TEXT, principal_kobo INTEGER,
    interest_kobo INTEGER, total_kobo INTEGER, PRIMARY KEY (loan_id, instalment));
CREATE TABLE IF NOT EXISTS entries (id INTEGER PRIMARY KEY, posting_ref TEXT, account TEXT, debit_kobo INTEGER,
    credit_kobo INTEGER);
"""


def annuity(principal, rate, n):
    """Equal instalments on a reducing balance (chapter 1.2). The last principal takes the rounding."""
    rows, balance = [], principal
    if rate == 0:
        each = principal // n
        for i in range(1, n + 1):
            p = each if i < n else balance
            rows.append((i, p, 0))
            balance -= p
        return rows
    payment = round(principal * rate / (1 - (1 + rate) ** -n))
    for i in range(1, n + 1):
        interest = round(balance * rate)
        p = payment - interest if i < n else balance
        rows.append((i, p, interest))
        balance -= p
    return rows


class LMS:
    def __init__(self, path):
        self.db = sqlite3.connect(path)
        self.db.executescript(SCHEMA)

    def book_loan(self, disbursement_ref, app_ref, customer_ref, product, principal, fee, rate_bps, period_days,
                  instalments, disbursed_on):
        """Returns (loan_id, created). A repeat of the same disbursement_ref changes nothing."""
        row = self.db.execute("SELECT loan_id FROM loans WHERE disbursement_ref=?", (disbursement_ref,)).fetchone()
        if row:
            return row[0], False
        n = self.db.execute("SELECT COUNT(*) FROM loans").fetchone()[0] + 1
        loan_id = f"S{n:06d}"
        net = principal - fee
        with self.db:                                   # one transaction: all of it or none of it
            self.db.execute("INSERT INTO loans VALUES (?,?,?,?,?,?,?,?,?,?)", (
                loan_id, app_ref, customer_ref, product, principal, fee, net, instalments, disbursed_on,
                disbursement_ref))
            day = dt.date.fromisoformat(disbursed_on)
            for i, p, it in annuity(principal, rate_bps / 10_000, instalments):
                due = day + dt.timedelta(days=period_days * i)
                self.db.execute("INSERT INTO schedule VALUES (?,?,?,?,?,?)",
                                (loan_id, i, due.isoformat(), p, it, p + it))
            for account, dr, cr in (("loans_receivable", principal, 0), ("cash_settlement", 0, net),
                                    ("fee_income", 0, fee)):
                self.db.execute("INSERT INTO entries (posting_ref, account, debit_kobo, credit_kobo) VALUES (?,?,?,?)",
                                (disbursement_ref, account, dr, cr))
        return loan_id, True

    def trial_balance(self):
        return self.db.execute("""SELECT account, SUM(debit_kobo), SUM(credit_kobo) FROM entries
                                  GROUP BY account ORDER BY account""").fetchall()

Save runday.py. It plays origination: for each of the day’s applications it posts to the engine and, when the answer is an approval the customer took up, books the loan. It treats the applications the book records as withdrawn as customers who walk away.

#!/usr/bin/env python3
"""Origination for one day: replay a day's applications from the loan book through the engine and the LMS."""
import argparse, json, sqlite3, urllib.error, urllib.request
from collections import Counter
from lms import LMS

NAIRA = 100


def post(url, body):
    req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
                                 headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return r.status, json.load(r), r.headers.get("Idempotent-Replayed")
    except urllib.error.HTTPError as e:
        return e.code, json.load(e), None


def naira(k):
    return f"₦{k // NAIRA:,}.{k % NAIRA:02d}"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--day", default="2026-06-16")
    ap.add_argument("--engine", default="http://127.0.0.1:8104")
    ap.add_argument("--data", default="../data")
    ap.add_argument("--lms", default="lms.sqlite")
    ap.add_argument("--double-send", action="store_true", help="send every application twice, as a retry would")
    a = ap.parse_args()
    book = sqlite3.connect(f"file:{a.data}/finance.sqlite?mode=ro", uri=True)
    apps = book.execute("""SELECT a.id, c.ref, a.product, a.requested_kobo, a.instalments, substr(a.applied_at,1,10),
                                  a.decision, a.decline_reason, a.approved_kobo
                           FROM applications a JOIN customers c ON c.id = a.customer_id
                           WHERE substr(a.applied_at,1,10) = ? ORDER BY a.id""", (a.day,)).fetchall()
    lms = LMS(a.lms)
    out, agree, replays = Counter(), 0, 0
    for aid, ref, product, requested, n, day, book_decision, book_reason, book_amount in apps:
        body = {"app_ref": f"APP-{aid}", "customer_ref": ref, "consent_ref": f"consent-APP-{aid}",
                "product": product, "requested_kobo": requested, "instalments": n, "applied_on": day}
        status, d, _ = post(a.engine + "/decisions", body)
        if a.double_send:
            _, _, replayed = post(a.engine + "/decisions", body)
            replays += replayed == "true"
        out[d["decision"] if d["decision"] != "declined" else "declined:" + d["reason"]] += 1
        same = (d["decision"] == "approved") == (book_decision in ("approved", "withdrawn"))
        agree += same
        if d["decision"] != "approved" or book_decision == "withdrawn":
            continue                                    # nothing offered, or the customer walked away
        o = d["offer"]
        loan_id, created = lms.book_loan(f"DISB-APP-{aid}", d["app_ref"], ref, product, o["principal_kobo"],
                                         o["fee_kobo"], o["rate_bps_per_period"], o["period_days"], n, day)
        out["loan booked"] += created
    print(f"{len(apps)} applications on {a.day}")
    for k, v in sorted(out.items()):
        print(f"  {k:<36}{v:>4}")
    print(f"engine and book agree on approve or not: {agree} of {len(apps)}")
    if a.double_send:
        print(f"replayed answers: {replays}")
    for acct, dr, cr in lms.trial_balance():
        print(f"  {acct:<18}debit {naira(dr):>16}  credit {naira(cr):>16}")


if __name__ == "__main__":
    main()
python3 runday.py
23 applications on 2026-06-16
  approved                              13
  declined:amount_below_product_minimum   4
  declined:insufficient_income_evidence   3
  declined:recent_delinquency            1
  declined:score_below_cutoff            2
  loan booked                           12
engine and book agree on approve or not: 18 of 23
  cash_settlement   debit            ₦0.00  credit      ₦832,965.00
  fee_income        debit            ₦0.00  credit       ₦10,035.00
  loans_receivable  debit      ₦843,000.00  credit            ₦0.00

The engine approved 13 and the customer behind one of them (the book’s APP-159) walked away, so 12 loans were booked. The ledger: receivable ₦843,000 against ₦832,965 paid out plus ₦10,035 of fees, and ₦832,965 + ₦10,035 = ₦843,000. One of the 12, an SME working-capital loan of ₦505,000, is 60% of the day’s principal: a concentration to notice. The engine and the book agree on 18 of the 23 applications; the other five are the income difference this chapter describes. Re-run the comparison with the book’s reasons if you want the detail: the engine approved four applications the book had declined, and declined one it had approved.

5. Check across the stores. Save checks.py. It reads the LMS, the engine’s decision log, the bureau’s enquiry log and the book.

#!/usr/bin/env python3
"""Checks across the three stores: the LMS, the engine's decision log, the bureau's enquiry log, the book."""
import argparse, json, sqlite3, urllib.error, urllib.request
from lms import annuity

ap = argparse.ArgumentParser()
ap.add_argument("--day", default="2026-06-16")
ap.add_argument("--bureau", default="http://127.0.0.1:8103")
ap.add_argument("--data", default="../data")
ap.add_argument("--lms", default="lms.sqlite")
ap.add_argument("--engine-db", default="engine.sqlite")
a = ap.parse_args()
lms, eng = sqlite3.connect(a.lms), sqlite3.connect(a.engine_db)
book = sqlite3.connect(f"file:{a.data}/finance.sqlite?mode=ro", uri=True)
bad = 0


def check(label, ok, detail=""):
    global bad
    bad += not ok
    print(f"{'ok  ' if ok else 'FAIL'} {label}{(': ' + detail) if detail else ''}")


# 1. The ledger balances, and says what the contracts say.
dr, cr = lms.execute("SELECT SUM(debit_kobo), SUM(credit_kobo) FROM entries").fetchone()
check("ledger debits equal credits", dr == cr, f"{dr} = {cr} kobo")
acct = dict((r[0], (r[1], r[2])) for r in lms.execute(
    "SELECT account, SUM(debit_kobo), SUM(credit_kobo) FROM entries GROUP BY account"))
principal, net, fee, n_loans = lms.execute(
    "SELECT SUM(principal_kobo), SUM(net_kobo), SUM(fee_kobo), COUNT(*) FROM loans").fetchone()
check("loans receivable equals the principal in the contracts", acct.get("loans_receivable", (0, 0))[0] == (principal or 0),
      f"{principal} kobo over {n_loans} loans")
check("cash out equals net disbursed", acct.get("cash_settlement", (0, 0))[1] == (net or 0) and (net or 0) + (fee or 0) == (principal or 0))
posted = lms.execute("SELECT COUNT(DISTINCT posting_ref) FROM entries").fetchone()[0]
check("one posting per loan", posted == n_loans, f"{posted} postings, {n_loans} loans")
# 2. The schedule sums to the principal, instalment by instalment.
off = lms.execute("""SELECT COUNT(*) FROM loans l WHERE principal_kobo !=
                     (SELECT SUM(principal_kobo) FROM schedule s WHERE s.loan_id = l.loan_id)""").fetchone()[0]
check("every schedule repays exactly its principal", off == 0)
# 3. The bureau was asked once per decision.
req = urllib.request.Request(a.bureau + "/enquiries", headers={"Authorization": "Bearer bu_test_owoleaf_mock"})
for _ in range(20):                       # the bureau may be answering 503s: ask again, this call writes nothing
    try:
        asked = len(json.load(urllib.request.urlopen(req, timeout=10))["enquiries"])
        break
    except urllib.error.HTTPError as e:
        if e.code != 503:
            raise
decisions, calls = eng.execute("SELECT COUNT(*), SUM(bureau_calls) FROM decisions").fetchone()
check("one bureau enquiry per decision", asked == decisions == calls,
      f"{decisions} decisions, {calls} calls made, {asked} enquiries the bureau recorded")
# 4. The LMS schedule against the book's own schedule, for loans the book made on the same terms.
same = 0
for lid, app, principal, n in lms.execute("SELECT loan_id, app_ref, principal_kobo, instalments FROM loans"):
    bl = book.execute("SELECT id FROM loans WHERE application_id=? AND principal_kobo=?",
                      (int(app.split("-")[1]), principal)).fetchone()
    if not bl:
        continue
    mine = lms.execute("SELECT instalment, principal_kobo, interest_kobo FROM schedule WHERE loan_id=? ORDER BY 1",
                       (lid,)).fetchall()
    theirs = book.execute("SELECT instalment, principal_kobo, interest_kobo FROM schedule WHERE loan_id=? ORDER BY 1",
                          (bl[0],)).fetchall()
    check(f"{lid} schedule equals the book's {bl[0]}", mine == theirs, f"{len(mine)} instalments")
    same += 1
# 5. The engine's formula against every schedule in the book.
loans = book.execute("SELECT id, principal_kobo, rate_bps_per_period, instalments FROM loans").fetchall()
wrong = [l[0] for l in loans if [(i, p, it) for i, p, it in annuity(l[1], l[2] / 10_000, l[3])] !=
         book.execute("SELECT instalment, principal_kobo, interest_kobo FROM schedule WHERE loan_id=? ORDER BY 1",
                      (l[0],)).fetchall()]
check("annuity() reproduces every schedule in the book", not wrong, f"{len(loans)} loans, {len(wrong)} differ")
print("ALL OK" if not bad else f"{bad} FAILED")
python3 checks.py
ok   ledger debits equal credits: 84300000 = 84300000 kobo
ok   loans receivable equals the principal in the contracts: 84300000 kobo over 12 loans
ok   cash out equals net disbursed
ok   one posting per loan: 12 postings, 12 loans
ok   every schedule repays exactly its principal
ok   one bureau enquiry per decision: 23 decisions, 23 calls made, 23 enquiries the bureau recorded
ok   S000002 schedule equals the book's L000033: 1 instalments
ok   S000004 schedule equals the book's L000083: 1 instalments
ok   S000008 schedule equals the book's L000269: 1 instalments
ok   S000010 schedule equals the book's L000306: 1 instalments
ok   annuity() reproduces every schedule in the book: 372 loans, 0 differ
ALL OK

The four schedule comparisons are the loans where the engine’s amount equals the book’s, so the same terms must give the same schedule. The last check runs the formula against all 372 of the book’s schedules. Note that the bureau’s 23 enquiries include the one from step 3: the engine did not ask again.

6. Send the whole day again, twice over. A retry, a double tap or a restarted job sends the same applications again. Run the day with every application sent twice, on top of the stored decisions.

python3 runday.py --double-send | tail -6
python3 checks.py | grep -E "enquiry|ALL"
  loan booked                            0
engine and book agree on approve or not: 18 of 23
replayed answers: 23
  cash_settlement   debit            ₦0.00  credit      ₦832,965.00
  fee_income        debit            ₦0.00  credit       ₦10,035.00
  loans_receivable  debit      ₦843,000.00  credit            ₦0.00
ok   one bureau enquiry per decision: 23 decisions, 23 calls made, 23 enquiries the bureau recorded
ALL OK

No new loans, the same ledger, and still 23 enquiries after 46 more requests to the engine: the second send of each application is answered from the decision store, and the LMS finds each DISB-APP- reference already booked.

7. Take the bureau down. Stop the bureau and the engine (Ctrl-C in terminals 1 and 2). Start the bureau so that 60% of requests answer 503, and the engine with a fresh store. Then run the day against new stores.

# terminal 1, in labs/finance
python3 mock_bureau.py --quiet --error-rate 0.6
# terminal 2, in labs/finance/stack
python3 engine.py --db outage.sqlite
# terminal 3, in labs/finance/stack
python3 runday.py --lms outage-lms.sqlite
python3 checks.py --lms outage-lms.sqlite --engine-db outage.sqlite | grep -E "enquiry|ALL|FAIL"
python3 -c "
import sqlite3
e = sqlite3.connect('outage.sqlite')
print(e.execute('SELECT bureau_status, COUNT(*), SUM(bureau_calls) FROM decisions GROUP BY 1').fetchall())"
23 applications on 2026-06-16
  approved                               9
  declined:amount_below_product_minimum   3
  declined:insufficient_income_evidence   3
  declined:recent_delinquency            1
  declined:score_below_cutoff            2
  loan booked                            9
  refer                                  5
engine and book agree on approve or not: 14 of 23
  cash_settlement   debit            ₦0.00  credit      ₦748,815.00
  fee_income        debit            ₦0.00  credit        ₦9,185.00
  loans_receivable  debit      ₦758,000.00  credit            ₦0.00
FAIL one bureau enquiry per decision: 23 decisions, 39 calls made, 18 enquiries the bureau recorded
1 FAILED
[('ok', 18, 24), ('unavailable', 5, 15)]

The engine retried each 503 up to twice. 18 applications got a report (18 decisions took 24 calls, so six retries), and 5 failed all three tries (15 calls) and were referred to a person. The check fails on purpose, and the reason is worth reading: the 39 calls made and the 18 enquiries recorded differ because the mock answers a 503 before it processes the request, so those calls leave no enquiry. A real bureau may behave differently; the check is how you would find out. Nothing was approved without a report. The ledger and its checks still pass, because nothing was booked that the engine had not approved.

8. Price build or buy. Save buildbuy.py and run it. Then change BUY_PER_LOAN to 60 * NAIRA and ENGINEER to 2_000_000 * NAIRA in turn, and rerun after each.

"""Build or buy a loan-management system: total cost over a horizon, in kobo. Every input is ILLUSTRATIVE."""
NAIRA = 100
HORIZON = 36                                  # months
BUY_FIXED = 800_000 * NAIRA                   # platform fee a month
BUY_PER_LOAN = 120 * NAIRA                    # a month, per active loan
BUY_LIVE_IN = 2                               # months to go live
BUILD_ENGINEERS, BUILD_MONTHS = 2, 6          # to a first usable version
ENGINEER = 1_500_000 * NAIRA                  # a month, all-in
RUN_ENGINEERS, HOSTING = 1, 150_000 * NAIRA   # after launch: a maintainer and servers
DELAY_COST = 3_000_000 * NAIRA                # contribution lost for each month later than the bought system


def buy(loans):
    return HORIZON * (BUY_FIXED + BUY_PER_LOAN * loans)


def build(loans, delay=True):
    one_off = BUILD_ENGINEERS * BUILD_MONTHS * ENGINEER
    running = HORIZON * (RUN_ENGINEERS * ENGINEER + HOSTING)
    late = (BUILD_MONTHS - BUY_LIVE_IN) * DELAY_COST if delay else 0
    return one_off + running + late


def crossover(delay):
    """Smallest number of active loans at which building costs no more than buying (integer arithmetic)."""
    gap = build(0, delay) - buy(0)
    per = HORIZON * BUY_PER_LOAN
    return -(-gap // per)


print(f"{'active loans':>13}{'buy':>16}{'build':>16}{'build + delay':>16}")
for n in (500, 2_000, 5_000, 10_000, 20_000):
    print(f"{n:>13,}{buy(n) // NAIRA:>16,}{build(n, False) // NAIRA:>16,}{build(n) // NAIRA:>16,}")
print(f"\nbuilding costs no more than buying from {crossover(False):,} active loans ignoring the delay,"
      f" {crossover(True):,} with it")
python3 buildbuy.py
 active loans             buy           build   build + delay
          500      30,960,000      77,400,000      89,400,000
        2,000      37,440,000      77,400,000      89,400,000
        5,000      50,400,000      77,400,000      89,400,000
       10,000      72,000,000      77,400,000      89,400,000
       20,000     115,200,000      77,400,000      89,400,000

building costs no more than buying from 11,250 active loans ignoring the delay, 14,028 with it

The columns are naira over 36 months. Check one row by hand: 500 loans rented is 36 × (800,000 + 120 × 500) = 36 × 860,000 = 30,960,000. Halving the per-loan fee to ₦60 raises the crossover to 22,500 loans, or 28,056 with the delay (₦60,600,000 ÷ ₦2,160, rounded up). Raising the engineer’s cost to ₦2,000,000 a month raises it to 16,806, or 19,584 with the delay, because building gets dearer.

9. Stop what you started. Ctrl-C the bureau and the engine. The .sqlite files in stack/ are yours to delete; nothing outside stack/ was written.

Break the retry rule. First start the bureau slow, python3 mock_bureau.py --quiet --latency-ms 800, and the engine with a short timeout, python3 engine.py --db slow.sqlite --bureau-timeout 0.5, and run python3 runday.py --lms slow-lms.sqlite and python3 checks.py --lms slow-lms.sqlite --engine-db slow.sqlite | grep enquiry. All 23 applications are referred and the bureau still recorded 23 enquiries: the engine gave up, the bureau did not. Now stop both, change RETRY_ON_TIMEOUT = False to True in engine.py, restart the bureau with the same latency and the engine with --db naive.sqlite --bureau-timeout 0.5, and run the day again against naive-lms.sqlite. The check now fails with 23 decisions, 69 calls made, 69 enquiries the bureau recorded. Nobody got a loan and every applicant’s file carries three more enquiries than they asked for. A lender that does this to a real bureau, at real volume, makes its own customers look like credit-hungry borrowers to every other lender, and does so during the very outage that already costs it applications. Put the constant back to False when you finish.

ARTEFACT Write the loan-management system evaluation ~50 MIN
YOU PRODUCEA build-vs-buy evaluation for a loan management system

Template

# LMS evaluation: <company>, <date>
Written by <role>, reviewed by <engineer>. Signed by <role>. Decision needed by <date>.

## 1. Decision requested
<Rent, build or keep what we have, and what you need approved.>

## 2. Requirements and options scored
| Requirement | Weight | <Option A> | <Option B> | <Option C> |
Scores 1-5; weights add to 100; last row is the weighted total out of 5.

## 3. Cost over <months> months at <loans> active loans
| | Option A | Option B | Option C |
Inputs and where each came from. Delay priced at <₦ a month>. Crossover: <loans>.

## 4. Migration risk
What moves (<loans>, schedules, postings), how it is checked, the parallel run, who owns cutover.

## 5. Recommendation and what would reopen it
<Decision, owner, review date, and the loan count or price that changes it.>

## 6. How this could be wrong
<One way, and what would show it.>
WORKED EXAMPLE

At a real lender the head of operations writes this with the engineer, and the chief executive signs. Here Ikenga writes it, Ikechi reviews it, and the chief executive signs. Dated 7 December 2026; decision needed by 18 December.

Decision requested. Rent an LMS, keep the decision engine and its records in-house, and make a full export a condition of signing.

Scores (weight, then rent, build, spreadsheet):

Requirement Weight Rent Build Sheet
Idempotent booking, one transaction 20 4 5 1
Full export of contracts and postings 20 3 5 2
Reproduces our schedules to the kobo 15 4 5 1
Live within 2 months 15 5 2 5
36-month cost at 5,000 loans 20 5 2 4
Fits our product 10 3 5 1
Weighted total out of 5 100 4.05 3.95 2.40

Cost (the chapter’s buildbuy.py, illustrative inputs). At 5,000 loans renting costs ₦50,400,000; building costs ₦77,400,000, or ₦89,400,000 with four extra months at ₦3,000,000. Building is no dearer from 11,250 loans, or 14,028 with the delay. We have about 1,500. The sheet’s cost is staff time, not priced here, so its score of 4 is an assumption.

Migration risk. About 1,500 loans move. The new system must reproduce every schedule to the kobo, as the lab’s check does for the book’s 372, and run two weeks beside the sheet. Ikechi owns cutover; every posting carries a reference.

Could be wrong. The scores are judgements and the gap is 0.10. If the vendor’s sample export will not reload, rent’s export score falls to 2 and the total to 3.85, below build. A test export would show it.

Reopen at 4,000 active loans or on 1 December 2027.

Now you

You work at an unnamed lender to market traders with 30 people and 9,000 active loans, which plans 20,000 in 18 months. It runs on a home-built system that two departed engineers wrote, and one engineer now keeps it alive. The chief executive asks whether to rent a replacement, rebuild or carry on. Facts: a rented system quotes ₦800,000 a month plus ₦120 per active loan, live in 2 months; a rebuild takes 6 months. Run buildbuy.py and use its rows for 10,000 and 20,000 loans, its two crossovers and the lab’s build inputs, then make your own edits (try ₦60 a loan). Score at least three options against six requirements you choose, and say how the 9,000 existing loans would move. You write it as the head of operations; the chief executive signs, and it decides which system the company commits to for the next three years.

Self-check

DECIDE

Ikenga's lending startup has 15 people, about 1,500 active loans and a plan for 5,000 in a year. Ikechi can build a loan-management system in six months with two engineers, or the company can rent one that is live in two. Ikenga's concern is that the credit rules and decision records stay the company's own whatever is chosen. Using this chapter's illustrative model, what should they do?

READING
  1. DOC
    FCCPC: Digital, Electronic, Online or Non-Traditional Consumer Lending Regulations 2025

    The Regulations as the FCCPC hosts them. Read the provisions on registration, data access and disclosure that shape what an app may ask for, and check the dates against this chapter's note. Skip press commentary on fines.

  2. DOC
    FCCPC: DEON Consumer Lending Guidelines 2025

    Guidelines the FCCPC issued to support the Regulations. This chapter did not read the text, so read it alongside the Regulations before you design what a lender's systems must record.

  3. DOC
    Nigeria Data Protection Act 2023

    A copy of the Act. Read Part VIII on cross-border transfers (sections 41 to 43) before you choose where a stack is hosted, and check the section numbers against this chapter's note. Read: Part VIII.

  4. DOC
    NDPC: General Application and Implementation Directive 2025

    The Commission's directive for applying the Act. Read the article and schedule on cross-border transfers; skip the sections on the Commission's own administration.

  5. DOC
    The Idempotency-Key HTTP Header Field (Internet-Draft)

    An IETF working-group draft, not a finished standard: check its status on the page. Read it for how a key, a repeat and a changed payload should be answered, and compare with the 200 and 409 in step 3.

  6. DOC
    Python documentation: http.server

    The standard-library module under the lab's services. Read the warning about its security checks: it is for teaching and local labs, and a production service sits behind a proper server.

  7. DOC
    SQLite documentation: transactions

    What a transaction guarantees, which is why the LMS writes a loan, its schedule and its ledger entries together. Read the sections on commit and rollback; skip the locking detail on a first pass.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Getting customers profitably: acquisition cost, lifetime value, channels and referral fraud →