Explore this guide
A betting exchange API connects applications to exchange markets, prices and trading functions. This guide follows market updates from the provider to the screen, then explains how to validate orders and recover after a failure.
Suppose a team scores in the 83rd minute while an application still displays the earlier odds. The interface can remain responsive even though the information behind a new order is outdated. The worked incident below shows how market-data recovery and order reconciliation address that problem.
What is a betting exchange API?
A betting exchange API lets software communicate with an exchange without relying on its website interface.
Depending on access permissions, it can support:
- Market discovery: Find events, markets and selections.
- Market data: Retrieve back prices, lay prices and liquidity.
- Order management: Submit, cancel or replace orders.
- Order tracking: Monitor unmatched, partially matched and matched positions.
These functions have different responsibilities. A price update does not confirm that an order has been accepted or matched.
Matchbook, for example, provides a REST API for applications connecting to its betting exchange. Source: Matchbook integration guide.
Sportradar and Stats Perform serve different integration roles: odds delivery and live sports data. Their feeds should not be treated as exchange order-placement interfaces.
How to read this guide: provider-specific behavior is linked to official documentation. The architecture, operational checks and worked incident are illustrative design recommendations, not measured performance results.
Backing, laying and liability
Participants back an outcome or lay it by taking the opposite position. The exchange matches compatible offers under its rules.
For a £100 lay bet at decimal odds of 3.00, the layer's liability is £200, excluding commission and settlement adjustments.
Lay liability = stake × (decimal odds − 1)
Betting exchange software must account for that liability when checking funds and exposure.
Polling versus streaming
Polling: asking for the latest information
The application repeatedly requests current market data.
- Straightforward for periodic updates.
- Leaves a gap between requests.
- Requires careful handling of request limits.
A market can change immediately after a response arrives. More frequent polling reduces that gap but increases traffic.
Streaming: subscribing to changes
An exchange streaming API delivers updates through an established connection.
Betfair documents streaming market and order changes without constant polling. Its public market stream and account-specific order stream are separate. Source: streaming overview.
Sportradar UOF delivers odds_change messages when odds are updated. These describe odds and market state rather than an exchange order book. Source: UOF odds changes.
The application still needs to interpret, store and validate each update correctly.
Why live odds become outdated
A live odds API cannot eliminate every delay between a sporting event, a market change and the user's screen.
- Source delay: Observing and reporting an event.
- Publication delay: Preparing an update for delivery.
- Network delay: Transmitting the information.
- Processing delay: Applying updates locally.
- Display delay: Refreshing the interface.
Real-time sports data and exchange data also describe different things. A score feed reports sporting events; an exchange feed reports market conditions.
Combining them requires consistent event mapping and careful timestamp handling.
Stats Perform: the event-data layer
Stats Perform's RunningBall supplies live, venue-sourced data for in-play betting. This helps explain where event information enters the trading workflow. Source: RunningBall.
An integration should map event data to the correct market while continuing to use the exchange's own records for prices, liquidity and order status.
Full technical flow
Market-data path
- 01 Provider feeds
Exchange prices, odds feeds and live event data
- 02 Provider adapters
Authenticate, decode and normalize messages
- 03 RabbitMQ or Kafka
Route work or retain events for replay
- 04 State workers + Redis
Apply updates and store a verified market view
- 05 WebSocket / SSE
Deliver snapshots, updates and health status
- 06 Trading interface
Display odds, liquidity and market availability
Bet-submission path
- 01 Order service
Check funds, limits, feed health and reserve exposure
- 02 Exchange trading API
Submit with supported price and version constraints
- 03 Order store + ledger
Persist requests, responses and financial state
- 04 Reconciliation
Resolve order status and update actual exposure
Recovery runs alongside both paths: detect delay → restrict affected actions → reconnect with backoff → resynchronize → reconcile → resume.
Open the architecture diagramThe architecture below is an illustrative integration design, not a claim that every provider uses the same internal stack. Choose the components needed for your workload and recovery requirements.
1. Connect through a provider adapter
Each adapter authenticates, subscribes to the required events and decodes the provider's format. Preserve source IDs, timestamps, market status and sequence or recovery tokens where supplied.
- Sportradar UOF: XML messages delivered through AMQP, with RabbitMQ supporting the feed connection.
- Betfair: Its documented exchange streaming protocol.
- Matchbook: REST requests under its supported integration model.
These interfaces are provider-specific. Sources: Sportradar concepts, Betfair streaming, Matchbook REST API.
2. Normalize the message format
Convert provider messages into a consistent internal schema while preserving their original meaning.
- Identity: Provider, producer, event, market and selection IDs.
- State: Price, available size where applicable, market status and update type.
- Timing: Source publication time, local receipt time and processing time.
- Continuity: Provider version, sequence or recovery cursor where available.
An exchange order book includes available offers. A sportsbook odds feed does not automatically contain equivalent tradable liquidity.
3. Route events through RabbitMQ or Kafka
RabbitMQ can route events to worker queues. Use publisher confirms, appropriate durable storage and consumer acknowledgements for important internal messages; make consumers safe to rerun after redelivery. Source: RabbitMQ reliability.
Kafka can retain an event log for replay and independent consumer groups. Use a stable provider-and-market key to keep related events in the same partition, with processing that preserves that partition's order. Source: Kafka design.
These are architectural choices. A provider's RabbitMQ connection can feed your adapter, which then publishes to an internal Kafka topic; using both is optional.
A broker acknowledgement is not a bet confirmation. It describes a messaging step, not exchange acceptance or matching.
4. Control ordering, duplicates and backpressure
- Idempotent consumer: Reprocessing an event should not apply its business effect twice.
- Consumer lag: Measure how far processing trails the incoming feed.
- Backpressure: Bound work in flight instead of letting memory and queues grow unchecked.
- Dead-letter handling: Isolate malformed messages and alert; a missing market update may require suspension and resynchronization.
Kafka preserves partition order, not one global order across all feeds. Keep a stable partitioning strategy and serialize state changes per market; a partition-count change needs a controlled migration.
RabbitMQ's prefetch controls outstanding deliveries to consumers. In Kafka, an idempotent producer reduces duplicate log entries from producer retries; it does not make external Redis writes or exchange orders exactly once. Sources: RabbitMQ consumers, Kafka delivery semantics.
5. Store the current odds view in Redis
Use Redis as a fast read model for the latest reconstructed market state. An illustrative key is odds:{provider}:{marketId}.
Store more than the price:
| Field | Purpose |
|---|---|
| Prices and available sizes | Current reported offers, where supplied |
| Market status | Open, suspended, closed or provider-specific state |
| Source and receipt timestamps | Separate publication age from delivery age |
| Version or recovery cursor | Track continuity where supported |
| Feed health and recovery state | Indicate whether this view can be trusted |
Redis SET supports expiry options, which can bound cache lifetime. A key that still exists can contain stale data, so TTL is not a freshness guarantee. Source: Redis SET.
Publish a complete validated snapshot atomically, or use version-aware updates. For read-modify-write operations, Redis WATCH with MULTI/EXEC supports optimistic locking; retry aborted updates against the current state. Source: Redis transactions.
Redis transactions do not automatically include Kafka offsets or exchange operations. Design restart and replay behavior explicitly, with a single writer or guarded updates per market.
Commit the consumer offset after applying the update. A crash between the Redis write and offset commit can replay that update; version guards or deduplication must make reprocessing safe.
If Redis loses its data after offsets advance, rebuild from a supported snapshot or retained log. A successfully committed offset does not prove the cache still exists.
6. Deliver updates to the interface
A WebSocket gateway or Server-Sent Events (SSE) endpoint can distribute the application's market view to browsers. This delivery layer is separate from the provider's protocol.
Send a starting snapshot, then versioned updates. If a browser misses continuity or reconnects, reload the current snapshot and show any delayed or recovering status.
7. Validate and submit the order
The order service checks account permissions, funds, exposure, market status and data health. Reserve exposure consistently so concurrent requests cannot spend the same available balance.
Submit through the exchange's supported trading API with applicable price and version constraints. Treat the exchange response and later order updates as the evidence of acceptance and matching.
8. Reconcile and persist the result
Persist order intent, request references, responses and state transitions in a durable order store, such as PostgreSQL. Keep financial records separate from the replaceable odds cache.
Use reconciliation workers to resolve pending or unknown orders, update matched exposure and process settlement, cancellation or corrections under the provider's rules.
Snapshots and updates
Streaming applications often maintain a local copy of market information, called a cache.
Betfair describes an initial market image followed by updates applied to that cache. Source: market-cache explanation.
A snapshot establishes the starting state
The snapshot provides the relevant information for the subscription. Subsequent updates build on this foundation.
An update changes part of that state
An update may change a price level, remove liquidity or alter market status. Omission, replacement and removal can have different meanings under the provider's protocol.
Sportradar: updates have a different scope
In Sportradar UOF, an odds_change can include only some markets. Omitted markets remain unchanged; each included market contains its current outcomes and odds. Source: UOF message structure.
Implementation lesson: follow each provider's update rules. Reusing exchange price-level logic for a sportsbook odds feed can produce an incorrect local state.
Example: liquidity changes at 2.04
Suppose the available amount changes from £1,800 to £1,000. If the message specifies a replacement, the application must store £1,000.
Adding the amounts would incorrectly display £2,800 of liquidity.
Sequence numbers, cursors and recovery generations
Treat sequence numbers and cursors according to the provider's contract. An opaque cursor is a resume token, not necessarily a counter; timestamps alone cannot establish a total order across independent feeds.
- Continuous sequence supplied: Detect missing or duplicate values within its documented scope.
- Resume cursor supplied: Store and reuse it as documented, without inventing arithmetic comparisons.
- No reliable continuity proof: Recover a new snapshot before trusting further incremental updates.
- New recovery generation: Reject writes from workers still processing the previous generation.
A generation is an application-controlled identifier for the current rebuild. Check it at the write boundary so a delayed worker cannot overwrite recovered state.
Connection health and data freshness
Monitor the producer, message age and local processing as separate signals:
| Signal | What it helps assess |
|---|---|
| Connection status | Whether communication is established |
| Heartbeat arrival | Whether the channel is receiving activity |
| Publication timestamp | When the provider published a message |
| Processing backlog | Whether the application is falling behind |
| Provider health indicators | Whether the provider reports degradation |
What does a heartbeat prove?
Betfair documents server heartbeats sent during periods without other traffic. These messages contain no market data. Source: heartbeat documentation.
A heartbeat helps monitor the connection. It does not independently verify prices.
Sportradar: monitor the producer as well
Sportradar's alive messages carry producer-health information. Its documentation identifies missing messages, delayed timestamps and subscribed=0 as conditions requiring recovery. Source: UOF alive messages.
Monitoring should therefore cover the relevant producer as well as the network connection. One healthy part of the feed does not establish that every producer is ready.
An unchanged price is not automatically stale
A quiet market may legitimately have no price changes. Freshness controls should consider expected activity, timestamps, provider health and local processing together.
When Redis should be considered unsafe to use
Treat the cached market as unavailable for affected trading decisions if its key is missing, required producer health has expired, continuity is unresolved or recovery is incomplete.
Refreshing a Redis TTL on every heartbeat can keep an old price alive indefinitely. Track channel activity separately from when usable market state was last established.
Use synchronized wall clocks to compare source timestamps and local monotonic timers for elapsed waits. After a restart, rebuild freshness evidence rather than reusing a previous process's timer values.
Betfair's documented stream status 503 indicates unreliable data because of downstream latency. This is a streaming-message indicator, distinct from an HTTP response code. Source: Exchange Stream API.
Bet validation before execution
A displayed price describes an earlier view of the market. The authoritative trading system determines what can happen when an order reaches it.
What should be checked?
- Market status: Is trading permitted?
- Selection status: Is the outcome available?
- Order validity: Are the price, stake and order type supported?
- Funds and exposure: Can the account cover the position?
- Market constraints: Has a relevant material change occurred?
Available liquidity affects execution. A valid limit order can remain unmatched when compatible offers are unavailable.
Accepted, matched and settled are different states
| State | What the application can conclude |
|---|---|
| Submission pending or unknown | The outcome is unresolved; retain the relevant exposure allowance |
| Accepted, unmatched | The order exists, but no stake has matched yet |
| Partially matched | A portion has executed; the remainder needs its own status |
| Fully matched | The stake has executed under the exchange's rules |
| Settled | The financial outcome has been recorded under settlement rules |
These are conceptual states; provider field names vary. Read the instruction-level result and matched amount rather than treating HTTP success as proof that the full bet executed. Example: Betfair order execution reports.
Betfair's market-version safeguard
The optional marketVersion constraint in Betfair's placeOrders operation can cause an order to lapse following a material market change.
Betfair distinguishes material changes from other version updates. Ordinary odds movements do not automatically cause rejection. Source: placeOrders documentation.
Sportradar's bet-stop signal
Sportradar UOF uses bet_stop to instruct the receiving system to suspend the affected active markets. Odds can remain displayed while ticket acceptance is stopped. Source: UOF bet-stop documentation.
This is a feed-side suspension instruction. The operator must still enforce account, funds and acceptance checks within its own betting system.
Why an initial check is insufficient
A market can change between preliminary validation and order processing. Final controls must apply at authoritative acceptance or matching.
Recovering from an API failure
Recovery has two separate jobs within a sports exchange integration: rebuild the market view and determine what happened to outstanding orders.
Existing orders require separate attention
Disconnecting an application does not automatically cancel orders resting at the exchange. An unmatched order may remain active and subsequently match.
Local restrictions and exchange-side cancellation are separate actions.
Connection retries: backoff, jitter and circuit breakers
Retry transient connection failures using exponential backoff with jitter: increase the delay between attempts and randomize it so instances do not reconnect simultaneously.
- Illustrative schedule: 1, 2, 4, 8 seconds, then a configured cap, with random variation.
- Timeouts: Bound connection setup, authentication and subscription waits.
- Retry budget: Limit attempts and alert on prolonged degradation.
- Circuit breaker: Temporarily stop repeated calls to a failing dependency, then allow controlled probes.
- Permanent failures: Invalid credentials or permissions require correction rather than endless retries.
The schedule is an example, not a provider requirement. Follow provider limits and client-library recovery behavior, and avoid multiple retry loops acting on the same connection.
RabbitMQ documents that lost connections require reconnecting and reopening channels, with automatic recovery available in many clients. Source: RabbitMQ connection recovery.
Reconnect without trusting an old Redis value
- Mark affected markets as recovering. Gate sensitive actions using current feed-health state.
- Restore authentication and subscriptions. Recreate broker consumers or channels as required.
- Resume or resnapshot. Use the provider's supported recovery mechanism.
- Validate continuity. Reconcile replayed messages and rebuild the market view.
- Publish the verified Redis state. Prevent an older worker from overwriting the recovered version.
- Reconcile orders separately. Restore affected trading only when the required state is verified.
Retrying a connection is different from retrying a bet. Resolve an uncertain order through supported identifiers and reconciliation before resubmitting it.
Sportradar: wait for recovery completion
Sportradar's recovery sequence ends with snapshot_complete. Recovery messages must be processed before the affected producer's active markets are reopened. Sources: recovery procedure, producer recovery guidance.
Its recovery guidance also distinguishes current odds from a complete history of every price change. State recovery and historical replay are different requirements.
Order uncertainty and risk management
A timeout does not prove an order failed. The exchange may have processed it before the response was lost.
Repeating the request immediately can create duplicate exposure unless supported safeguards prevent it.
Handle uncertain submissions deliberately
- Assign supported request and order references.
- Use documented duplicate-submission protection.
- Query authoritative order records.
- Retain an appropriate exposure allowance while status is uncertain.
- Resolve the original submission before attempting a replacement.
Keep exposure consistent across services
Market displays, order management and risk calculations can update at different times. Additional exposure should not be approved using an account state missing a recent match or unresolved submission.
For operators combining exchange positions and sportsbook liabilities, sportsbook risk management also requires consistent event and outcome mapping.
Worked incident: a goal during a feed interruption
The following is a hypothetical test scenario using one illustrative clock. Its timings are not provider benchmarks, recommended timeout settings or a report of a real match.
- 20:42:09.900 — An order leaves the platform. A £100 back order at 2.40 is recorded with its request reference and reserved exposure. Its response is lost.
- 20:42:10.000 — A goal occurs and the market-data connection drops. Redis still contains the earlier 2.40 price; the application has not received the new market state.
- 20:42:10.100 — The transport reports disconnection. The health gate blocks new affected orders and the interface marks prices unavailable. Existing orders remain subject to exchange rules.
- 20:42:10.150 — An older worker finishes an update. Its recovery-generation check fails. It cannot overwrite the new restricted state or restore trading availability.
- 20:42:11.500 — A reconnect attempt succeeds. The adapter restores its subscription, but the application stays in recovering mode while obtaining a valid market image.
- 20:42:12.000 — The recovered market is suspended. Redis stores the validated snapshot and its version. No order is enabled merely because the connection works again.
- 20:42:12.200 — Order reconciliation resolves the timeout. The exchange record shows £40 matched and £60 unmatched. The configured policy cancels the remainder and verifies confirmation; matched exposure remains.
- 20:42:14.000 — A valid open-market update arrives. The platform resumes affected actions only after required feed health, market continuity and account exposure checks pass.
What this test must prove
- No duplicate £100 order is submitted while the original outcome is unknown.
- No old worker restores trading after the disconnect restriction.
- The £40 matched portion stays in exposure after the £60 remainder is canceled.
- Reopening follows verified state, rather than a socket reconnect or Redis key existing.
There is still a detection window between failure and restriction. Final exchange controls remain necessary even when the application's outage response works as designed.
Evaluating API reliability
Compare the provider's role first
These examples illustrate different parts of a betting platform, rather than a ranking of interchangeable services.
| Provider / product | Role illustrated in this guide | Integration checks |
|---|---|---|
| Betfair Exchange API | Exchange market data and account orders | Market state, order constraints and reconciliation |
| Matchbook API | REST access to a betting exchange | Supported operations, request limits and order responses |
| Sportradar UOF | Sportsbook odds, market status and recovery | Producer health, bet stops and recovery completion |
| Stats Perform RunningBall | Live sports event data for in-play trading | Event mapping, data age and downstream processing |
Product roles are described in the Betfair, Matchbook, Sportradar and Stats Perform sources. The checks are integration considerations, not provider performance claims.
Questions to ask every provider
Latency is useful only when its measurement is defined. Ask providers:
- What does latency measure? Detection, publication, delivery or processing?
- How is degradation reported? Health indicators, timestamps or another mechanism?
- How is state recovered? Replay, resubscription or replacement snapshots?
- How are uncertain orders resolved? Which references and queries are available?
- What limits apply? Check subscriptions, requests and commercial data rights.
Use the worked incident as one acceptance test, then vary the failure: an undetected network stall, a duplicate update, lost Redis state or a partially completed cancellation.
Record the observed result and the remaining uncertainty. A clean demonstration is evidence for that test case, not proof that every failure is covered.
Metrics to put on the operations dashboard
- Feed age: Time since the provider published the latest relevant message, allowing for clock accuracy.
- Processing delay: Time between receipt and successful application.
- Queue depth and consumer lag: Work waiting in RabbitMQ or Kafka.
- Cache health: Missing market keys, stale state and Redis update failures.
- Recovery health: Reconnect attempts, recovery duration and unresolved continuity gaps.
- Order uncertainty: Pending submissions, unknown cancellations and unreconciled exposure.
Alert on the affected producer or market where possible. A single green connection indicator cannot represent the health of this entire flow.
Frequently asked questions
Select a question to expand the answer. Opening another question closes the previous one.
Is a live odds API the same as a betting exchange API?
A live odds API primarily supplies pricing. A betting exchange API may also support submission, cancellation and account-specific order tracking.
Does streaming guarantee current odds?
Streaming supports continuous delivery, but delays and processing failures can still occur. Connection health and data freshness need separate controls.
Can stale odds cause an incorrect bet?
Stale odds can mislead users and strategies. Execution still depends on authoritative conditions and order rules; reliable data and validation address different risks.
When should trading resume after an outage?
Resume affected actions after verifying the required market state, order status and exposure. Opening a new connection alone is insufficient.
Do I need both RabbitMQ and Kafka?
Not necessarily. RabbitMQ can route work to queues; Kafka can retain an event log for replay and independent consumers. Choose by ordering, retention and recovery needs. A provider's RabbitMQ feed does not require an internal Kafka layer.
Why store odds in Redis?
Redis can serve a fast, reconstructed market view to interfaces and services. Store prices alongside market status, timestamps, continuity information and feed health. Keep durable order and financial records separately.
Does a Redis TTL guarantee fresh odds?
No. TTL controls key expiry. Use the producer, continuity and recovery checks to decide whether the cached market state is usable.
What happens to unmatched orders when the API disconnects?
They may remain active at the exchange and later match, subject to its rules and configured controls. Restricting your interface does not cancel them. Submit any required cancellation and verify the result.
How can an integration avoid duplicate orders after a timeout?
Record the original request reference and reserve the relevant exposure. Use supported deduplication controls and query authoritative order records before resubmitting. A timeout leaves the result unknown; it does not prove failure.
How should connection retries work?
Use bounded exponential backoff with jitter for transient failures, respecting provider limits and client recovery behavior. Keep retries separate from order resubmission. Invalid credentials or permissions require correction rather than repeated reconnect attempts.
What if the feed is connected but consumers are falling behind?
Monitor processing delay, queue depth and consumer lag. Apply backpressure and investigate the bottleneck. A growing backlog can make Redis and browser prices stale even while the connection remains healthy.
Can I switch automatically between data providers?
Only with validated mappings and a defined handover process. Event IDs, market definitions, settlement rules and update formats can differ. A secondary odds feed cannot establish what happened to orders placed on the original exchange.
Further reading
Primary sources
Official provider and infrastructure documentation supporting this guide.
- Sportradar — AMQP, RabbitMQ and UOF concepts
- RabbitMQ — Reliability and acknowledgements
- RabbitMQ — Consumers and prefetch
- Apache Kafka — Ordering and delivery semantics
- Redis — SET and expiration options
- Redis — Transactions and optimistic locking
- Sportradar — Alive messages and producer health
- Sportradar — Odds change messages
- Sportradar — Bet stop and market suspension
- Sportradar — API recovery procedures
- Matchbook — Exchange API integration
- Stats Perform — RunningBall in-play data
- Betfair — Market & Order Stream API
- Betfair — Heartbeats and conflation
- Betfair — Exchange Stream API
- Betfair — placeOrders and market versions
Examples are illustrative. Provider capabilities vary.