Skip to content

Platform Architecture and Scalability Practical engineering guide

Back and Lay Betting: A Developer's Guide to Exchange Matching

Understand back and lay positions, liability, partial matches and cancellation races, with developer invariants for wallet commitments and exchange recovery.

Explore the flow Worked examples · Failure handling · Primary sources
Explore this guide

Back and lay orders represent opposite positions on an outcome, and exchange software must keep their matched amounts, remaining offers and financial commitments consistent. Understanding the quoted odds is only the first step: developers need a deterministic record of what was submitted, matched, cancelled and settled.

This guide explains illustrative developer invariants, not a profitable trading strategy, a universal exchange matching rule or a tested production engine. The exchange-versus-sportsbook guide remains the broader business-model comparison.

Back, lay and standalone liability

A backer takes a position that benefits if the selected outcome wins. A layer takes the opposite side. At decimal odds of 3.00, a hypothetical matched 100-unit back stake has 200 units profit if the outcome wins and a 100-unit loss if it loses, before fees and adjustments.

For the corresponding lay stake, the layer's standalone liability is stake × (odds − 1): 100 × 2 = 200 units. If the selected outcome loses, the layer's gross gain is the backer's 100-unit stake. Smarkets' liability explanation is a provider reference for this distinction; actual fees and settlement rules remain product-specific.

Matched positionSelected outcome winsSelected outcome loses
Back 100 at 3.00+200−100
Lay 100 at 3.00−200+100

These are gross position examples, not available account balances. Other positions, holds, charges and provider rules can change required funds and the final result.

Technical flow

Back and Lay Betting: A Developer's Guide to Exchange MatchingIllustrative logical boundaries; provider contracts and operating requirements determine the implementation.
  1. 01Record intent

    Bind side, stake, odds, account and stable instruction identity

  2. 02Validate + reserve

    Evaluate available funds, liability and atomic commitments

  3. 03Match or cancel

    Track matched and remaining quantities across cancellation races

  4. 04Reconcile + settle

    Resolve authoritative results before releasing or settling funds

The illustrated order lifecycle starts with authenticated intent, validates and reserves commitments, applies an authoritative ordered decision and records matches/cancels. Recovery and settlement use that durable evidence.

RecordRequired meaning
Order intentAccount, market/selection, side, amount and price constraints
Accepted instructionActual authoritative result and reference
MatchExecuted amount and price with original order linkage
Remaining offerAmount still eligible under the order's rules
CancellationResolved cancellation amount and confirmation
Settlement/correctionRule/result authority and traceable financial effect

A transport acknowledgement does not fill in every record. For external exchange integration, the provider remains authoritative for its order outcomes.

Order-book state and matching rules

An order book represents offers and executed changes within the market's rules. An application can display selected price levels and available amounts, but a displayed size is a received observation, not a reserved execution promise for the next caller.

If building an independent engine, specify priority, acceptable price instructions, rounding, precision and behavior under suspension. Price-time ordering is a possible design choice; do not present it as the universal documented behavior of every exchange without evidence.

For a provider integration, implement the actual contract rather than recreating a plausible matching algorithm locally. Betfair's matching guidance discusses available prices and execution considerations. This does not authorize a local cache to determine provider fills.

Maintain market/selection identity and the versioned terms needed to interpret an instruction. Similar names or visible prices cannot substitute for a correct mapping.

Partial matches change the record, not the original intent

For a hypothetical 100-unit order at 3.00, suppose 40 units match and 60 remain unmatched. Record both amounts explicitly. Do not turn the whole order into “fully matched” because one execution report is successful.

For the lay side at that price, the matched 40 has standalone liability 80. The unmatched 60 corresponds to a possible additional liability of 120 if it later matches under those assumptions. How the account reserves the total must follow the approved rules.

If cancellation of the unmatched 60 is confirmed, that does not remove the matched 40 or its 80-unit standalone liability. Fees, other positions and netting rules can affect actual account funds; this example deliberately excludes them.

Maintain enough precision to ensure matched plus remaining plus any resolved cancellation is explainable without losing fractions. A provider's exact reporting conventions may require separate cumulative and incremental fields.

Model concurrent cancel and match as authoritative decisions

A cancellation request can race execution. The request leaving the client is not proof that the remaining offer was cancelled before another match.

An independent engine needs a defined ordering/atomicity boundary for order, match, cancellation and suspension. A provider adapter must use the actual returned outcome and later authoritative records rather than assume its local send time determines priority.

Store intent and supported references before submission. A duplicate client request should not create another financial effect merely because a network response was lost. Bind operation identity to the meaningful payload and account scope.

resolve_cancel(order_reference):
    persist_cancel_intent_and_supported_reference()
    result = submit_under_documented_contract()
    if result.is_uncertain:
        retain_relevant_commitment()
        query_authoritative_order_state()
    record_actual_matches_and_resolved_remaining_amount()
    release_only_the_commitment_no_longer_required()

This is illustrative pseudocode, not an invented provider operation or a complete engine implementation.

Keep funds, exposure and matching connected

The wallet must not authorize several concurrent requests using the same available funds. Reserve the required commitment consistently with order creation, then update it from reliable execution/cancellation evidence.

If portfolio netting is allowed, define its market scope, outcome assumptions and treatment of pending orders explicitly. A formula that reduces exposure for already matched positions may not justify releasing funds for an unresolved new submission.

Keep financial operation identities and versioned risk decisions explainable. Wallet-ledger architecture provides the underlying consistency and reconciliation model.

Do not confuse gross stake turnover with account profit or available funds. The table above describes isolated positions before costs; it is not a financial statement or guarantee of a realizable hedge.

Suspension and restart are state transitions

Restrict affected acceptance when market status or required health evidence no longer permits action. In an independent engine, ensure the decision cannot be bypassed by another request path. For an external exchange, respect the authoritative operation result and applicable constraints.

After a restart, reconstruct supported order/market state and resolve pending instructions. A restored odds snapshot does not establish what happened to an earlier order.

Use generation/version guards where late work could overwrite recovered state. The in-play architecture guide explains why suspension must reach the acceptance boundary rather than only a display flag.

Record the moment restrictions began, actual unresolved exposure and the evidence used to resume. Reconnecting an adapter alone is insufficient financial recovery evidence.

Test engine or adapter invariants

Build deterministic fixtures for your documented model. Keep provider behavior, local recommendations and actual implementation observations distinguishable.

TestInvariant to inspect
Back/lay examplesCorrect gross outcome amounts before fees
Partial fillExecuted and remaining amounts remain explainable
Cancel/match raceActual authoritative ordering determines resolution
Duplicate submission/resultOne intended operation/match effect
Same reference, changed payloadConflict instead of silent reuse
Suspension during workNo unsupported acceptance path
Restart with unknown commandsReconciliation retains unresolved commitments
CorrectionLinked financial adjustment, not erased history

Test precision boundaries and supported order types rather than assuming integer stakes in every real market. Compare final records and postings, not only status responses.

For sports exchange engineering, the useful brief includes the authoritative matching model, market rules, funds policy and recovery evidence. This guide does not claim that a provider feed supplies an independent matching engine or liquidity.

Frequently asked questions

Is lay stake the maximum amount the layer can lose?

Not generally. In the isolated decimal-odds example, liability is stake multiplied by odds minus one, before applicable adjustments and account rules.

Does an accepted order have to be fully matched?

No. Track matched and unmatched amounts using the actual authoritative evidence.

Does cancelling an order undo an existing match?

Do not assume so. Cancellation of an unmatched remainder and the status of already matched positions are separate matters under the provider's rules.

Should all exchanges use the same priority rule?

No universal rule is established here. Implement and test the defined engine or provider contract consistently.

Is local order-book replay sufficient after a timeout?

Only for a model where the retained evidence is actually authoritative and complete. External orders require the provider's supported reconciliation evidence.

Further reading

Primary sources

  1. Smarkets' liability explanation
  2. Betfair's matching guidance