Why use Fees Engine?
The Fees Engine helps you manage complex fee logic. It applies flat rates, distributes fees proportionally, and estimates transactions before you run them. It offers:
- Flexible fee configuration via fee packages, tailored to account groups or specific ledgers.
- Multiple calculation methods: flat fees, percentual rates, and “max between types” logic.
- Proportional fee distribution for marketplace flows and multi-account operations.
- Support for accounting routes via
transactionRoute,routeFrom, androuteTo. - Estimation tools to preview calculations before executing transactions.
- Fee exemption logic by account and transaction value ranges.
- Priority-based application to control the order of multiple fees.
- Accurate deduction mechanics with
isDeductibleFromsupport. - Volume-based billing via billing packages. Charge based on accumulated transaction counts per period (daily, weekly, or monthly).
- Maintenance billing for recurring per-account charges, targeting accounts by segment, portfolio, or explicit list.
- Free quotas and progressive discounts to model tiered pricing and volume incentives.
- Segment-based exemptions to exempt entire account groups from fee packages without listing individual accounts.
- Fee debt for deferrable fees: a fee that the payer cannot fund becomes a debt that later credits settle.
What are fees?
Fees are monetary values charged in exchange for services, products, or access to resources. Their purpose depends on the industry. Below are a few examples:
Finance
In the financial sector, fees cover operational costs and support legal compliance.- Account maintenance fee: Keeps accounts operational and covers administrative costs.
- Transfer fee: Applies to transactions like TEDs or international transfers.
Logistics and transportation
In the logistics sector, fees cover transportation and storage services.- Handling fee: Applies during storage and physical movement of goods.
- Unloading fee: Covers unloading operations at delivery points.
Pharmaceutical and healthcare
In the pharmaceutical sector, fees ensure the quality and regulation of services.- Medication registration fee: Related to regulatory approvals and market entry.
- Laboratory analysis fee: Covers testing and quality control costs.
Agricultural
In the agricultural sector, fees cover commercialization and regulatory processes.- Sanitary inspection fee: Ensures health compliance for agricultural exports.
- Agricultural export fee: Covers admin and regulatory export costs.
Scope
The unified Midaz service exposes Fees and Billing only on the ledger-scoped v2 surface. The URL is the sole ledger input: a
ledgerId query parameter is not accepted, and a request body that sends ledgerId is rejected as an unknown field. Retrieving, updating, or deleting a package owned by another ledger returns not found.
Fee Packages
A Fee Package defines how the engine applies fees to a transaction. It groups one or more fee rules. You customize it by segment, ledger, and accounting routes. You can create different packages for different products, transaction types, or customer segments. Each package has its own calculation logic, route configuration, and priority rules. A package includes required fields and can add optional matching or exemption fields:
- Ledger scope – The v2 URL identifies the ledger that records the transaction and its fees. Do not send
ledgerIdin the request body. - transactionRoute – The ID of a transaction route. The package matches a transaction that sends the same
routeId. - segmentId – A segment ID. The package matches when every source account, except
@externalaccounts, belongs to this segment. - metadataSelector – Metadata pairs that the transaction must all carry for the package to match. A pair matches only a string metadata value that is equal to it. You set it when you create the package.
- waivedAccounts – Accounts to exempt from fees, when you configure exemptions.
- fees – A map of individual fee rules, each including:
- priority – Defines execution order.
- routeFrom and routeTo – Custom accounting routes for the fee.
- isDeductibleFrom – Whether the engine deducts the fee from what the destination receives, instead of adding it on top.
- referenceAmount – The base amount for calculations.
- deferrable – Whether the part of the fee that the payer cannot fund becomes a fee debt. The default is
false.
Validation rules
Fees Engine enforces the following rules:- Fee priority must be unique within a package.
- Fees with
isDeductibleFrom: truemust usereferenceAmount: originalAmount. - Fees with
priority1 must also usereferenceAmount: originalAmount. - Fees with
deferrable: truemust useisDeductibleFrom: false. - Each fee’s
creditAccountmust be an account alias that exists in the ledger. Midaz checks it when you create or update the package.
Fee application and estimation
Midaz applies fees in-process when it creates a transaction. There is no separate public calculate-fees endpoint. The ledger evaluates the matching package in the transaction flow and applies its rules when one matches.Estimate transaction fees
- Estimates fees for a specific package by its
packageId. - Returns calculated fees only if the amount falls inside the package’s amount range. It does not check
transactionRouteorsegmentId. - Useful for testing, debugging, or a preview of fees, without writing to the ledger.
Fee application happens during transaction creation. Use
estimate when you want to test a specific package without writing to the ledger.Segment-based exemptions
Fee packages support exempting individual accounts by listing their aliases inwaivedAccounts. To exempt a whole group at once, add a segment reference to that same list using the segment:<segment-uuid> form, for example "segment:0198e5f4-7b2a-7c3d-9e1f-2a3b4c5d6e7f".
Use segment-based exemptions when:
- A customer tier (such as premium accounts) is universally exempt from a fee.
- Internal or partner accounts belong to an existing segment in Midaz.
- Maintaining a list of individual account aliases is impractical at scale.
Billing Packages
Billing Packages calculate charges from accumulated transaction volume over a period (daily, weekly, or monthly). Fee packages charge per individual transaction. Billing packages count the qualifying transactions and return payloads for your orchestrator to execute. Two types are available:
- Volume: charges based on the number of transactions matching an event filter in the period.
- Maintenance: charges a fixed fee per account that is active when you run the calculation.
Billing packages are a calculation engine, not a billing platform. The engine calculates the charges and returns the payloads. Your orchestrator (Flowker, a cron job, or any other caller) runs the actual charges against Midaz.
Volume packages
A volume package counts transactions that match a giveneventFilter (transaction route + status) within the billing period. It then applies a charge from the configured pricing model.
Key fields:
- eventFilter: Specifies which transactions to count, using
transactionRouteandstatus. - pricingModel: Either
tiered(unit price varies by quantity range) orfixed(single unit price regardless of volume). - tiers: Quantity ranges (
minQuantity,maxQuantity) andunitPriceper unit within each range. - freeQuota: Number of transactions exempt per period. The engine subtracts this count before it applies pricing.
- discountTiers: Progressive discounts. When total volume meets a threshold, the engine applies the configured discount percentage to the final amount.
- countMode: Accepts
perRouteorperAccount. Volume calculation counts all matching transactions on the route as a single total. - debitAccountAlias / creditAccountAlias: The accounts the charge debits and credits. Both must exist in the ledger.
Maintenance packages
A maintenance package applies a fixed fee per account that is active when you run the calculation, regardless of transaction activity. Key fields:- feeAmount: Fixed charge per active account.
- assetCode: Currency for the charge.
- maintenanceCreditAccount: Account that receives the fee revenue.
- accountTarget: Defines which accounts to charge. Use exactly one per package:
segmentId: All accounts in the segment.portfolioId: All accounts in the portfolio.aliases: Explicit list of account aliases (maximum 100 accounts).
Managing billing packages
The following endpoints manage billing packages:POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages: Create a billing package.GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages: List all billing packages.GET /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{id}: Retrieve a specific billing package.PATCH /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{id}: Update a billing package (label,description,enable).DELETE /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing-packages/{id}: Soft-delete a billing package.POST /v2/organizations/{organization_id}/ledgers/{ledger_id}/billing/calculate: Calculate billing for a period.
Fee Packages vs. Billing Packages
Fee packages and billing packages operate independently.
Routing fees
Every fee can have:
- A
routeFrom, which represents the accounting route for the debit (or source). - A
routeTo, which represents the accounting route for the credit (or destination). - A
transactionRouteon its package, which selects the transactions the package applies to.
Deductible fees
If you flag a fee as deductible (
isDeductibleFrom: true), the following logic applies:
- The source account sends the full value.
- The engine subtracts the fee from the amount the destination account receives.
- The
referenceAmountfor calculations must beoriginalAmount.
Soft delete for safe recordkeeping
When you delete a resource:
- Fees Engine marks it with a
deletedAttimestamp. Active records returndeletedAt: null. - Standard queries exclude it, but the database still stores it for audit and history.
Integrations
Use Fees Engine in a Midaz deployment alongside other components in your stack. You can call its capabilities from Lerian plugins or your own implementation to apply fees from your business logic. Use cases include:
- Exchange engines
- Lending platforms
- Bill payment systems
- Smart contracts
- Pix (Brazil’s instant payment platform)
Security recommendations
Security is foundational when you work with Lerian products and plugins.
Before you deploy any component, review our Security Recommendations. Implement each product and its plugins in line with security best practices, such as:
- Securing network boundaries
- Managing and rotating secrets
- Applying timely patch management
- Enforcing strict role-based access controls (RBAC)
Next steps
Explore the Fees Engine API
Browse endpoints for fee packages, calculations, and estimations.
Using Fees Engine
Learn how to create fee packages and apply them to transactions.

