Menlo Finance EnterpriseFranchise Revenue
Subway Brasil Case

Algorithm Tour

The mathematics behind an intelligent financial operation.

Scroll to start the tour

How AI agents, decision algorithms and financial automation can coordinate collections for approximately 1,500 stores, with policies defined by the network.

Since April 2025, collections for the Subway network in Brazil have been running on the menlo platform. Zamp defines the policy: criteria, control points and how far to go with a franchisee who is late. Menlo executes within those limits, across the whole base, without anyone having to trigger step by step.

~1,500
stores in the network (approximate)
+1,000
invoices per month
+500 h
of manual work avoided per month
4.5/5
network satisfaction with collections

Real data published by Menlo at menlopagamentos.com.br/subway. Also real: 100% of first responses within one minute, 24/7 service, WhatsApp and email, management agent, an increase in total collections and positive ROI in the first year — with no public percentages.

We will follow a financial obligation from its origin to collection, service, receipt and management intelligence. In each chapter, a new mathematical concept appears, and the illustration evolves as you read. Everything that is a model, proposal or simulation is marked.

real operation dataexplanatory modelproposed evolutionsimulated values
Chapter 01

Financial Data Intelligence

From thousands of records to a structured portfolio.

+1,000 invoices per monthMatching and quality: explanatory model

Every month, over a thousand invoices arrive on the platform: one per franchisee, with amount, due date and reference. They come from different systems and spreadsheets, written in different ways — and the same obligation can appear twice.

First, deterministic matching: when two records carry the same identifier, they are the same invoice, with no uncertainty. It is the simplest rule and it resolves a good part of the portfolio.

match(a, b) = [ id(a) = id(b) ]

For what is left, we compare attribute by attribute — store, amount, due date, document — and add up the similarities with weights. A score from 0 to 1 classifies the pair: duplicate, review or distinct.

match_score = Σ(wᵢ × similarityᵢ)

Finally, each invoice gets a quality score: complete fields, plausible values, consistent due date. Bad data does not enter the collection ladder; it becomes a pending item for a person.

Q(t) = Σₖ vₖ · [field k valid]
Adjust the matching weights interactive simulated
duplicates
for review
distinct
match_score = Σ(wᵢ × similarityᵢ) / Σwᵢ  ·  ≥ 0.85 duplicate · 0.55–0.85 review · < 0.55 distinct  ·  synthetic pairs
ERPinvoice recordsSpreadsheetsinvoice recordsEmailinvoice recordsPortfoliostructured1 row per invoice+1,000 invoices per month · real datathree sources, three formats, the same due dateT-0421T-0388T-0415T-0402T-0377T-0421T-0415T-0388T-0402T-0399exact id → direct matchthe rest goes to scoringmatch(a,b) = [id(a) = id(b)]1.000.120.200.900.100.121.000.880.150.300.200.881.000.100.250.900.150.101.000.200.100.300.250.201.00AABBCCDDEEprobable duplicates (≥ 0.85) highlightedInvoice quality scoreT-04210.96T-03880.88T-04150.74T-04020.55T-03770.320.80below the line: becomes a pending item, does not enter the ladder
Chapter 02

Intelligent Segmentation

Not every franchisee needs to receive the same collection approach.

a ladder that treats on-time payers and late payers differentlyProbabilities: demonstration modelGradient boosting: candidate

The network’s collection ladder does not treat on-time payers and late payers the same. For that, the portfolio is separated into operational segments — and each segment receives a different sequence of contacts, within the limits defined by the network.

A classifier, for example gradient boosting, adds up many small decision trees: each one corrects the error of the previous one. The inputs are characteristics of the invoice and the franchisee — punctuality history, amount, days overdue.

F(x) = Σₘ η · fₘ(x)

Instead of only asking “will they pay?”, we ask “when?”. Survival analysis deals with the time until payment: the probability of paying within t days comes from the survival curve.

P(pay within t | X) = 1 − S(t | X)  ·  S(t | X) = exp(−λ(X) · t)

A probability only helps if it is calibrated. Segments come from cutoffs on the calibrated probability and pass through the network’s policy before becoming action.

Everything here is demonstrative: the curves illustrate the method, they do not predict real payments.

Estimate the probability of payment interactive simulated
P(pay within t days)days
P(pay within t)
median time to pay
segment
P(pay within t | X) = 1 − exp(−λ(X)·t)  ·  log λ = −3.5 + 2(punct. − 0.5) − 0.25·ln(V/5000) − 0.6·delay/30  ·  demonstration model, not a real forecast
punctuality →days overdue■ calm■ reminder■ attention■ negotiationsynthetic portfolio: 70 invoices, each dot is an invoicetree 1punctuality < 70%?f₁(x) = +0.80tree 2delay > 15 days?f₂(x) = +0.35tree 3amount > R$ 8k?f₃(x) = +0.20++F(x) = Σ η · fₘ(x) = 1.35each tree corrects the error of the previous oneF(x) becomes a probability through a logistic functionpunctualmediumlateP(pay within t days)daysP(pay within t | X) = 1 − S(t | X)Operational segments (illustrative)negotiationattentionremindercalmcutoffs on the calibrated probability: 0.35 · 0.60 · 0.80each segment gets a different sequence of contactsthe network defines what each sequence can dowhen the model says 70%, it should happen ~70% of the time
Chapter 03

Next Best Action

What is the best permitted next action?

Zamp defines the policies; menlo executes within themExpected values: synthetic scenarioContextual bandits: experimental evolution

For each invoice there are several possible actions: wait, remind by WhatsApp, send an email, propose renegotiation, call a person. The question is not which action is best in general, but which action is best among those permitted now, for this invoice.

Each action has an expected value: the chance of payment it produces times the invoice amount, minus the cost of the action — including the discount, when there is one.

E[U(a|x)] = P(pay | a, x) · V − c(a)

But not everything is permitted. Zamp defines the policy: how much discount, how many contacts per week, when to escalate. Actions that violate a rule leave the set before the choice — it is a constrained optimization.

a* = argmaxₐ∈A(x) E[U(a|x)]   subject to policies(a, x)

When there are many similar actions, a learned ranking (learning to rank) orders the candidates. Contextual bandits, as an experimental evolution, could test variations safely — always within the policy.

Compare the permitted actions interactive simulated
chosen action (a*)
expected value
gain vs. waiting
a* = argmaxₐ E[U(a|x)]  ·  contacts: at most 3 per week (policy)  ·  each contact reduces effectiveness by 15%  ·  synthetic scenario
Invoice · xwaitWhatsAppemailrenegotiatepersonthe set of possible actions for an invoiceExpected value per action (synthetic scenario)waitR$ 1,800WhatsAppR$ 2,208emailR$ 2,004renegotiateR$ 2,576personR$ 2,802E[U(a|x)] = P(pay | a, x) · V − c(a)3 contacts already made this week: policy blocks contactwaitR$ 1,800WhatsAppR$ 2,064blocked by policyemailR$ 1,932blocked by policyrenegotiateR$ 2,576personR$ 2,442blocked by policyonly permitted actions enter the argmaxRanking of permitted actions1 · renegotiateR$ 2,5762 · waitR$ 1,800evolutionexperimentalcontextual bandit:explore with εwithin the policya* = argmaxₐ∈A(x) E[U(a|x)]A(x) = actions that satisfy Zamp’s policies
Chapter 04

Collection State Machine

Collections as a system of states.

a ladder that runs on its own, across the whole baseMarkov chain: analytical modelIllustrative states

Each invoice lives in a state: issued, upcoming, overdue, notified, in negotiation, paid. A finite-state machine says which transitions are possible — a paid invoice never goes back to overdue — and each state change emits an event.

If we assign a probability to each weekly transition, the machine becomes a Markov chain: the next state depends only on the current state. It is an analytical model, not an exact description of what happens.

P(Xₜ₊₁ = j | Xₜ = i) = Pᵢⱼ

Put together, the probabilities form a matrix. Multiplying the portfolio distribution by the matrix, week after week, simulates how the set of invoices spreads across the states.

πₜ₊₁ = πₜ · P  ·  πₜ = π₀ · Pᵗ

With this we can ask “what if?”: what if the notification goes out a day earlier? what if negotiation converts more? The ladder stops being a list of reminders and becomes something that can be studied.

The probabilities are editable in the lab and do not represent network data.

Edit the transitions and simulate the portfolio interactive simulated
paidoverduein collectionweeks
paid
overdue with no contact
in collection
80% paid by
P(Xₜ₊₁ = j | Xₜ = i)  ·  πₜ = π₀ · Pᵗ  ·  demonstration probabilities, editable
IssuedUpcomingOverdueNotifiedNegotiationPaideach invoice is a state; each state change emits an eventIssuedUpcomingOverdueNotifiedNegotiationPaid0.900.300.800.250.550.350.45illustrative weekly probabilities · the rest is staying putTransition matrix P (row → column)0.100.900.150.300.550.150.800.050.400.250.350.550.451.00IssuedIssuUpcomingUpcoOverdueOverNotifiedNotiNegotiationNegoPaidPaideach row sums to 1 · “Paid” is an absorbing stateπₜ₊₁ = πₜ · Pshare of the portfolioweeksPaidsimulation: πₜ = π₀ · Pᵗ, all invoices start in “Issued”
Chapter 05

Communication Intelligence

Conversational AI coordinating thousands of interactions.

WhatsApp and email · 24/7 service desk · 1st response within 1 minClassification, tools and RAG: explanatory model

Collections arrive by WhatsApp and email, and the service desk runs 24 hours a day: in 100% of cases the first response goes out within one minute. Every message from the franchisee — question, proof of payment, request for more time — enters the same flow, through any channel.

A classifier estimates the intent: ask for a second copy, say they paid, negotiate, dispute, talk to a person. The output is not an answer: it is a probability distribution — and that is what makes it possible to know when to doubt.

P(c | x) = exp(z꜀) / Σⱼ exp(zⱼ)

To act, the assistant uses tools — look up the invoice, generate the second copy, record an agreement — and retrieves, from the network’s policies, what it may answer. This is called retrieval-augmented generation (RAG): the answer cites the policy instead of inventing.

answer = LLM(message, tool data, policy excerpts)

Finally, a guard decides the destination: answer on its own, or escalate. A discount request beyond the limit is never granted by the AI; it goes to someone with authority. The AI executes within the policy; it does not rewrite it.

escalate ⇔ confidence < τ ∨ policy(action) = forbidden
Classify and route each request interactive simulated
the AI answers
go to a person
escalate ⇔ p(intent) < τ ∨ request > policy limit ∨ intent = “talk to a person”  ·  synthetic messages
WhatsAppEmailAIassistantPersonwith authority24/7 · first response within 1 minute, in 100% of casesreal operation dataevery message enters the same flow, through any channel“Can you send the second copy of the invoice?”second copy 0.86payment made 0.06negotiate 0.04dispute 0.02talk to a person 0.020.86P(c | x) = softmax(z)꜀ · a distribution, not an answerAIassistantlook_up_invoicegenerate_2nd_copyrecord_agreementNetwork policy (RAG)relevant excerptsretrieved by similaritythe assistant cites the policy instead of improvisingconfidence ≥ τand policy ok?AI answersand records the eventperson with authorityreceives the contextdiscount above the limit? the AI never grants itescalate ⇔ confidence < τ ∨ policy(action) = forbidden
Chapter 06

Revenue Recovery Optimization

The mathematics of effort and recovery.

total network collections increased · positive ROI in year 1Curves and parameters: simulated

Each additional contact recovers less than the previous one: those who were going to answer already did, and insisting wears people out. In mathematical terms, the marginal gain is decreasing — and that is what creates an optimal point of effort.

gain(k) = [P(k) − P(k−1)] · R

The net expected value adds the return and subtracts the cost of acting. It rises while each contact earns more than it costs, and falls afterwards. The maximum of the curve is the intensity that pays off.

ENV(k) = P(pay | k) × Receivable − k × Cost

The optimum depends on the cost: a cheap contact justifies insisting more; an expensive one, less. By varying the cost per contact, a decision surface is drawn — and the best intensity runs along that surface.

In practice, there are constraints: the network’s policy limits the number of contacts per invoice. The optimization becomes constrained: choose the best intensity within what is permitted.

k* = argmax ENV(k)   subject to k ≤ kpolicy

All values in this chapter are simulated.

Find the intensity that pays off interactive simulated
returncostnet expected valuecontacts
net expected value
optimum (k*)
return per R$ spent
total cost
ENV = P(pay | action) × Receivable − Action cost  ·  P(k) = 1 − (1 − p₀) · Πⱼ (1 − q · 0.7ʲ⁻¹), q = response × conversion, p₀ = 35%  ·  policy ceiling: 6 contacts  ·  all simulated
Expected gain of each additional contact (R$)k=1292k=2168k=3103k=466k=543k=629- - - cost of the contact (R$ 30)the marginal gain falls: each contact is worth less than the previous onemaximum: k* = 5 contactsnet expected value per invoiceintensity (contacts)0123456ENV(k) = P(pay | k) · R − k · cGain vs. not collecting · rows: cost per contact · columns: contactsR$ 0R$ 10R$ 20R$ 30R$ 40R$ 50R$ 60R$ 700123456contour = best intensity for each costPolicy ceiling: at most 4 contacts per invoiceno ceilingk* = 5R$ 1,397with a ceiling of 4k = 4R$ 1,384the network’s policy constrains the optimization:the solution is the best within the limit, not outside it
Chapter 07

Payment Reconciliation

Closing the financial cycle.

working capital returns to cashRules and anomalies: explanatory model

The cycle only closes when the money that comes in is matched to the right invoice. Payments arrive by Pix, bank slip or transfer, not always with the full reference, and sometimes they pay part of an invoice or more than one.

The first rule is the simplest: if the payment carries the invoice reference and the amount matches within tolerance, the match is direct. No probability is involved.

reconciled ⇔ ref(p) = ref(t) ∧ |vp − vt| ≤ ε

When it does not match, cascading rules come in — amount, store, date window — and differences are classified: underpayment, duplicate payment, payment without reference. The platform classifies; it does not force a match.

Anomaly detection separates what is strange from what is merely different. A payment far outside the distribution goes to a person, with the evidence on screen; the final decision is human.

z = (x − μ) / σ  ·  |z| > z* → human exception
Reconcile synthetic payments interactive simulated
reconciled
differences
human exception
reconciled ⇔ ref(p) = ref(t) ∧ |vp − vt| / vt ≤ ε  ·  exception ⇔ |z| > z*  ·  synthetic payments
paymentsinvoicesP1T1P2T2P3T3P4T4P5T5money comes in by Pix, bank slip or transfernot always with the full referenceid + amountexact reference and amount within tolerance→ direct reconciliationunderpaymentno reference✕no matchcascade: reference → amount + store + date → exceptiona difference is classified, not forcedz = +2.5z = −2.5exceptionz = (x − μ) / σ · |z| > z* → person, with the evidencestrange ≠ wrong: the person decides
Chapter 08

AI Operations & Human-in-the-Loop

AI executes. Humans govern.

exception handling stays with the finance teamThreshold, evaluation and drift: illustrativeActive learning: proposed evolution

Not every decision should be automatic. A confidence threshold separates what the AI resolves on its own from what goes to a person. The finance team moved out of execution and now handles exceptions: it is the human who governs, the AI that executes.

To know whether the threshold is good, you have to evaluate: of the automatic decisions, how many were right; of those sent to review, how many errors were caught. Raising the threshold reduces automatic error and increases the human load — a trade-off that can be measured.

precision = correct automatic / automatic

Active learning: when there are more cases than people, the most uncertain — those closest to the decision boundary — go first to review, because they are the ones that teach the model the most.

uncertainty(x) = 1 − maxc P(c | x)

And the world changes. Drift detection compares today’s confidence distribution with the reference one: when it moves too far, the stability index (PSI) triggers an alert and the threshold needs to be reevaluated.

PSI = Σᵢ (todayᵢ − refᵢ) · ln(todayᵢ / refᵢ)
Set the confidence threshold interactive simulated
correct decisionswrong decisionsconfidence
goes straight through (automation)
goes to review
error among automatic
PSI
automation = P(conf ≥ τ)  ·  PSI = Σ (today − ref) · ln(today / ref)  ·  < 0.10 stable · 0.10–0.25 attention · > 0.25 drift  ·  illustrative distributions
AI decisionconfidence≥ τ ?yesnoautomaticreviewlabel → trainingthe human governs: decides what the AI did not decideand each decision returns as evaluation dataModel evaluation (1,000 synthetic decisions)automatic · right820automatic · wrong18review · would be right98review · would be wrong64automatic precision = 820 / 838 = 97.9%errors caught by review = 64 / 82 = 78%without evaluating, there is no way to adjust the thresholdAI decisions (each dot is a case)circles: the most uncertain, near the boundary, go first to reviewconfidence distribution:■ reference■ todayPSI = Σ (today − ref) · ln(today / ref) = 0.05above 0.25: drift alert
Chapter 09

Portfolio Intelligence

The whole portfolio turned into management intelligence.

AI agent answers about the portfolio, in real timeSemantic layer and queries: explanatory modelUnit base: synthetic

The platform has an AI agent that answers questions about the operation with the network’s consolidated position, with no spreadsheet or BI. For the answers to be reliable, each metric — overdue amount, collection rate, average delay, exceptions — is defined once, in a semantic layer.

Asking in natural language is just the tip: the model translates the question into a structured query — which metric, grouped by what, with which filter. Whoever does the math is a deterministic query over the data; the AI does not invent numbers.

question → { metric, group_by, filter } → query → answer

That is why every answer can be checked: it shows the metric, the formula and the values that go into the sum. It is the difference between an assistant that chats and one that accounts for itself.

collection rate = Σ paid / Σ issued

And observability closes the loop: time series of collections, bands of expected variation and alerts when something departs from the pattern — before anyone has to ask.

Ask the synthetic portfolio interactive simulated
units (synthetic)
overdue invoices
overdue amount
collection rate
synthetic base generated in the browser · the real agent queries the network’s consolidated position; here, all numbers are fictitious
Semantic layer: each metric is defined onceoverdue_amountΣ amount where status = overduedefined oncecollection_rateΣ paid / Σ issueddefined onceaverage_delayaverage(days after due date)defined onceopen_exceptionscount(unresolved exception)defined oncethe question can change; the definition does notQuestionnatural languageInterpretationthe AI translatesQuerydeterministicAnswerwith the math{ metric: “overdue_amount”, group_by: “region”, filter: { min_delay: 5 } }the model translates the question; it does not do the matha deterministic query does the calculationAuditable calculationcollection rate = Σ paid / Σ issuedregionissuedpaidrateSouthR$ 410kR$ 371k90.5%SoutheastR$ 920kR$ 842k91.5%NortheastR$ 350kR$ 301k86.0%✓ the answer shows the source and the formulafictitious valuesalert: drop in collectionsdaily collections (index, synthetic)daysgreen band: expected variation
Chapter 10

The Learning System

An operation designed to improve continuously.

ladder, WhatsApp, email, management agent, 24/7 service deskMLOps, calibration, drift and experimentation: proposal

An operation that learns is a cycle: data become features; features feed models; models support decisions; decisions are executed; results are measured; evaluation returns to the data. Each turn builds on what the previous one taught.

Data → Features → Models → Decisions → Execution → Results → Evaluation

Before any change, offline evaluation: train on the past and test on the future, in sliding windows, to see how the decision would have performed without risking the operation.

In production, three monitors watch the system: calibration (do the probabilities still hold?), drift (has the data changed?) and human feedback (do people agree?). When one fires, the model or the threshold is reevaluated.

To know whether a change really helps, controlled experimentation: two arms, one with the change and one without. With about a thousand invoices per month, the size of the effect you want to detect determines how many months the test takes.

n = (zα/2 + zβ)² · (p₁q₁ + p₂q₂) / δ²

It is important to separate what exists from what is a proposal. AI-driven collection ladder, WhatsApp and email communication, management agent and 24/7 service desk are on the platform. Predictive models, optimization and MLOps are a proposed evolution, to be validated.

Plan an experiment interactive simulated
invoices per arm
total experiment
estimated duration
n = (zα/2·√(2p̄q̄) + zβ·√(p₁q₁ + p₂q₂))² / δ²  ·  duration = 2n / invoices per month  ·  simulated rates; only the monthly volume has a real reference
DataFeaturesModelsDecisionsExecutionResultsEvaluationcontinuousimprovementeach turn uses the results of the previous oneOffline evaluation: sliding windows in timetraintesttraintesttraintesttime →train on the past, test on the future: no looking aheadno real decision is made at this stagecalibrationdrift (PSI)human feedbackokno?three monitors watch the system in productionwhen one fires, the threshold or the model is reevaluatedcontroltreatment60%66%payment rate (synthetic)effect = difference between arms, with confidence intervalDocumentedAI-driven collection ladderWhatsApp and emailmanagement AI agent24/7 service deskpolicy defined by ZampProposed evolutioncalibrated risk modelsnext best actionMLOps and monitoringcontrolled experimentationlearning from reviewswhat is a proposal is never presented as already proven
Chapter 11

The four teams

To recap the path of an obligation: data is structured and gets a quality score; the portfolio is segmented; the best permitted action is chosen; collection moves through a state machine; the conversation is understood and routed; effort is calibrated against recovery; the payment is reconciled; exceptions go to people; the portfolio becomes management intelligence — and the system learns from the results.

This work is divided into four logical teams, which converge on the Menlo Finance Enterprise platform.

DataIntelligenceDecisionIntelligenceAgenticOperationsFinancialIntelligenceMenlo FinanceEnterprise
  • Data IntelligenceStructures the portfolio and guarantees data quality.
  • Decision IntelligenceApplies rules and models to support prioritization.
  • Agentic OperationsRuns contacts, coordinates workflows and routes exceptions.
  • Financial IntelligenceTracks collections, results and operating performance.

The question that runs through all of this is always the same: between what a machine does well and what a person does better, where is the line — and how do we measure whether it is in the right place? The answer that does not change: the network defines the policy, the AI executes within it, and people govern the exceptions.