Exploration
Delivery sketch — Automating budget execution in a public agency
A hypothetical scenario run end to end: from interviews with public servants to the AS-IS diagnosis, the TO-BE design, the architecture, the technology choices and the delivery plan for a system handling invoices, budget commitments and contracts.

- stakeholder profiles interviewed, from budget authority to internal audit
- 7
- times each invoice is typed in: the TO-BE target
- 3 → 1
- of notice before a contract expires, on the first alert
- 120 dias
- from the first interview to a pilot in one unit
- 20 sem.
- Year
- 2026
- Role
- Project management & architecture
- Client
- Cenário hipotético
- Stack
- Discovery
- BPMN
- C4 Model
- ADRs
- Scrum
- Next.js
- FastAPI
- PostgreSQL
- Keycloak
- OpenTelemetry
This isn't a system I've built: it's an exercise in how I would run a software project from scratch, from the first client meeting to the pilot. I picked a public-sector scenario because it combines everything that makes a project hard — legal rules, legacy systems, many stakeholders and little room for error with money.
The hypothetical client is the budget and finance department of a state agency. It pays suppliers on about 180 active contracts, receives around 600 invoices a month and runs everything on email, case files in SEI (the government's electronic records system), spreadsheets and re-keying into the official financial system. The request arrives vague, as it almost always does: “we need to automate invoices and stop missing contract deadlines”.
The scenario's numbers are hypotheses that discovery would confirm or discard. What matters here is the method: understand the people and the process before picking technology, and record every decision along with its reason.
1. Learn the domain before the problem
Before any client meeting, I study the domain so I can ask good questions. In the Brazilian public sector, every expense follows the same path, set by Law 4.320/1964: first a commitment (empenho) reserves the money in the budget; then settlement (liquidação) confirms the service was delivered, with the invoice signed off by the contract's inspector; only then comes payment.
Around that cycle sits the contract, governed by Law 14.133/2021. It has an assigned manager and inspector, a term, a value and a remaining balance; amendments change term and value, and payments must follow chronological order. Knowing this changes the conversation: instead of “what do you want the system to do?”, I can ask “where in this cycle do things get stuck?”.

2. Interviews and discovery
Discovery takes three weeks and starts with the people who live the problem. I map stakeholders and interview each profile separately: the budget authority (the sponsor), the budget team lead, the finance team, contract managers and inspectors, accounting, internal audit and the agency's IT. Each sees a different slice of the same process — and feels different pains.
Interviews are semi-structured: a short script, plenty of room for concrete stories and no questions about solutions. Besides listening, I follow one real payment from start to finish (shadowing), read internal procedures and regulations and pull numbers from the system: how many invoices, how many contracts, how long each step takes.
- Discovery deliverables: a stakeholder map, the AS-IS process in BPMN validated with the people who run it, a prioritized pain list and baseline numbers to measure before and after.
- A typical finding from interviews like these: inspectors sign off invoices without seeing the commitment's balance, and finance only finds the problem at settlement — days later.
## Roteiro — fiscal de contrato (45 min)
1. Me conte como foi a última nota fiscal que você atestou,
do momento em que ela chegou até sair da sua mesa.
2. O que você precisou conferir? Onde buscou cada informação?
3. Qual foi a última vez que algo deu errado nesse caminho?
O que aconteceu depois?
4. Como você sabe quanto ainda resta de saldo no contrato?
5. Como fica sabendo que um contrato está perto de vencer?
6. Se pudesse mudar uma única coisa amanhã, qual seria?
Regra: perguntar sobre o passado concreto, nunca sobre a solução.3. From AS-IS to TO-BE
The AS-IS diagnosis shows an invoice's real path: it arrives by email or on paper, becomes a case file in SEI, someone checks it by hand against a commitments spreadsheet, the inspector signs off by memo and finance re-keys everything into the official system. The same data is typed three times, the balance lives in a spreadsheet and contract terms depend on one person's memory.
The TO-BE doesn't replace the official financial system — it remains the accounting source of truth. The new system orchestrates the path to it: it captures the electronic invoice from its XML or access key, validates it with the state tax authority (SEFAZ), links invoice, commitment and contract, shows the balance instantly, brings the inspector's sign-off into the system with a deadline and reminder, and hands over a pre-filled settlement, in a queue that follows chronological order.

4. Shaping the idea and the MVP
With the TO-BE drawn, I turn the idea into product decisions. First, principles that guide everything else: the official system stays the source of truth; no payment is decided automatically; every action is recorded for auditing; and the interface must be accessible, because public servants have diverse needs.
Then the MVP cut, using MoSCoW. Must have: contracts and commitments imported from the official system, NF-e capture and validation, linking with balance, sign-off workflow and settlement queue. Should have: alerts for contract terms, balances and tax certificates. Later: service invoices (NFS-e), write integration with the financial system and a mobile app for inspectors. A clickable prototype is tested with five servants before any production code is written.
- Success metrics set before any code: average time from invoice to settlement, invoices needing rework, payments out of chronological order and contracts that expired without warning.
- First contract-term alert at 120 days: a realistic lead time to decide between extending and starting a new procurement.
AVISOS_VIGENCIA = (120, 90, 60, 30) # dias antes do fim
SALDO_MINIMO = Decimal("0.20") # 20% do valor atualizado
def alertas_do_contrato(contrato: Contrato, hoje: date) -> list[Alerta]:
alertas = []
dias = (contrato.fim_vigencia - hoje).days
if dias in AVISOS_VIGENCIA:
alertas.append(Alerta.vigencia(contrato, dias))
if contrato.saldo < contrato.valor_atualizado * SALDO_MINIMO:
alertas.append(Alerta.saldo_baixo(contrato))
# Alerta avisa; quem decide prorrogar ou aditivar é o gestor.
return alertas5. Designing the architecture
I design the architecture with the C4 model, starting from the container view. The central choice is a modular monolith, not microservices: the team is small, there is one domain and the agency's IT will maintain the system afterwards. A web app talks to an API; a separate worker handles everything slow or external — SEFAZ lookups, commitment imports, scheduled alerts.
Government systems stay outside, behind isolated adapters that only the worker calls. If the financial system goes down or SEFAZ is slow, users keep working and the integration retries later. Every relevant change becomes an event in an append-only audit trail, designed for internal audit and the court of accounts.
# ADR 0003 — Integração com o sistema financeiro oficial
Status: aceito
## Contexto
O sistema financeiro do estado não tem API de escrita. Há exportação
diária de empenhos e importação de lotes de liquidação por arquivo.
## Decisão
Ler empenhos pela exportação diária e gerar lotes de liquidação para
importação, via adaptador no worker. Nada é gravado direto no sistema.
## Consequências
+ Sem dependência de API que não existe; o sistema oficial segue soberano.
- Saldo pode ter até um dia de atraso: a tela mostra a data da última carga.
6. Technologies and why
Each technology is chosen for the problem and for whoever maintains it afterwards. In the public sector, the question “can the agency's IT sustain this five years from now?” weighs as much as performance.
- Next.js + React: server rendering, a good foundation for accessibility (eMAG and WCAG) and an ecosystem that's easy to hire for.
- Python + FastAPI: Python handles NF-e XML and PDFs well; Pydantic validates every input and OpenAPI documents the API on its own.
- PostgreSQL: transactions for money, JSONB to keep the parsed XML and a simple queue using SELECT … FOR UPDATE SKIP LOCKED, with no extra service to run.
- Keycloak (OIDC): single sign-on tied to the agency's Active Directory or gov.br, with role-based profiles.
- S3-compatible object storage for XMLs and PDFs, and OpenTelemetry for logs, metrics and tracing of integrations.
- Everything in containers, deployable in the agency's datacenter or a government cloud — with data kept in Brazil, as data-protection law (LGPD) expects.
7. Methodology and governance
The team is lean: me as project manager and tech lead, two full-stack developers, a part-time designer and an agency servant as product owner — ideally someone from finance, with authority to prioritize. Quality is the whole team's job, not a step at the end.
After discovery, we work in Scrum with two-week sprints. A fixed cadence helps the agency plan servants' time for reviews, which happen with the people who will use the system, not just management. In parallel, discovery continues on a smaller scale to validate what comes next.
- Definition of done: automated tests, code review, accessibility criteria, no personal data in logs and up-to-date documentation.
- Governance: a weekly red-amber-green status for the sponsor and a monthly committee for scope decisions.
- Scope changes go into the backlog and swap places with another deliverable: deadline and quality stay fixed, scope is what gets negotiated.
- Continuous knowledge transfer to the agency's IT: pairing, ADRs and runbooks — the system can't depend on whoever built it.
8. Risks and how to handle them
Risks are raised during discovery, get an owner and are reviewed every sprint. The main ones in this scenario:
- The financial system has no API → a technical spike in week 1 confirms what's possible; plan B is file-based integration (ADR 0003).
- Resistance to change → servants involved in the design from the first interview, a pilot in one unit and on-the-job training.
- A change of administration or team → documented sponsorship, decisions recorded as ADRs and value delivered every two weeks.
- Digital certificates and SEFAZ access depend on agency paperwork → requested during discovery, owned by IT.
- Outdated contract data → cleaning the records as part of the pilot, with an inconsistency report.
9. Roadmap and success criteria
It's 20 weeks from the first interview to the pilot: three of discovery, three of design, four MVP sprints, two of acceptance testing with servants and four of piloting in one unit. Each milestone has an objective criterion — the AS-IS map validated by the people who run it, the prototype approved in user tests, the MVP accepted.
The pilot ends with a go/no-go decision on expanding, made by comparing the metrics defined during design against discovery's baseline. If invoice-to-settlement time doesn't drop and rework doesn't shrink, the project goes back to the drawing board before it grows.

What this sketch shows
Technology is the easiest part of a project to change; misunderstanding the process is the most expensive. That's why the order here is always the same: people, process, product decisions, architecture and only then tools.
In the public sector this matters even more. The system must comply with the law before it's elegant, coexist with official systems instead of competing with them and keep running after the team that built it has moved on.