CRM projection
The CRM keeps its own copy of what happens in the trading engine: positions, the settings of wallets, the transactions the engine makes on its own, and what a trade sets off in the CRM, such as loyalty coins and volume commission. The projector is the part of the cashier backend that builds this copy from the engine's trading events.
How it reads
The projector reads the stream trading.events.log one event at a time, in the order of the stream. Each event is applied in one database transaction, which also stores the seq and the stream offset of the event in the table gateway_projector_state. After a restart the projector continues with the message after the stored offset.
An event is the Protobuf message Event of the message schema. The projector also reads a message with the content type application/json, which holds the JSON form of the same message and has its seq only in the header.
Only one instance of the backend reads at a time. It holds a Postgres advisory lock for as long as it does. The other instances ask for the lock every few seconds and take over when it is free.
A projector that starts for the first time reads from that moment on. It does not go through what the stream still holds from before.
What an event does
| Event | In the CRM |
|---|---|
PositionOpened, PositionUpdated, PositionClosed | The position is written if the event has a higher version than the stored row. A close for a position the CRM has no row for creates the row. A close awards the loyalty coins and books the volume commission of the introducers. The customer's last trading activity is set to the time of the event |
TransactionCreated | The closing balance and credit are kept per account for the nightly comparison. A negative balance protection or a credit removal that the engine made on its own gets a CRM transaction. A credit removal also expires the credit grants of the wallet and tells the customer |
AccountCreated | An account that was opened without the cashier gets a wallet, under the customer with the holder's email address or under a new customer |
AccountUpdated | Group, leverage and status of the wallet follow the account. A prop account that is disabled moves its funnel on and raises the alerts. For a change the cashier made itself, only the version is stored |
OrderCreated | An entry in the customer's event feed |
OrderUpdated | Nothing |
A transaction the cashier asked for is recognised by its idempotency key, which is the id of a CRM transaction. The CRM has that transaction already, so the event adds nothing.
Events of an account the CRM has no wallet for are skipped, except that its positions are stored.
Applying an event twice
Events can arrive more than once and the stream can be read again. Neither changes anything. Positions and wallets only move to a higher version. Everything else is entered in the table effect_ledger under a key and applied once per key:
| Effect | Key |
|---|---|
| Loyalty coins | Position id |
| Volume commission | Position id and introducer |
| CRM transaction for a transaction of the engine | Engine transaction id |
| Event feed entry | Order id |
| Prop funnel progress and alerts | Account id and account version |
Coins, commission payouts and CRM transactions are written in the transaction of the event. A commission payout is sent to the engine after the commit. If that fails, the credit retry sends it again. Messages to the customer and to the trading clients are also sent after the commit, and are lost if the backend stops at that moment.
Events that fail
A failing event is tried 5 times, with 1, 2, 4 and 8 seconds in between. Then it is stored in the table gateway_parked_event together with the error, Sentry receives the error with the fingerprint gateway-projector-parked, and the projector goes on with the next event.
An event that no retry can help is parked at once. Examples are an account in a group the CRM does not have, and a message that is not an event.
The column body of a parked event holds the event in its JSON form. For a message that could not be read it holds the message as it came, in base64 if the message was Protobuf.
Parked events are not tried again on their own. Fix the cause, then let the projector read again from before the event. Delete the row of an event that is dealt with: the metric cashier_gateway_projector_parked_events counts the rows.
Reconciliation
When a live projector starts reading, and every 24 hours after that, it compares the open positions with the REST API of the engine:
- A position the engine holds open is written if the CRM does not have it or has an older version.
- A position that is open in the CRM and no longer open in the engine is read from the engine and closed.
Coins and commission are paid for a position that closed within the last 7 days. An older close is written without them and logged.
Reconciliation makes up for events the projector never read, for example after the backend was down for longer than the stream keeps events. It does not find a position that was opened and closed within such a gap.
Every night at 00:45 UTC the balance and credit the engine reports for an account are compared with what its last transaction event left. A difference is logged as Gateway projector [BALANCE] ... and counted in one Sentry warning per run. Nothing is corrected.
Open positions
The running result and the margin of an open position change with every quote. The CRM reads them from the engine each time it shows an open position: in the position lists of the admin portal, on the position page, in the positions of a customer and in the XLSX export. Everything else about a position comes from the CRM's own copy. Positions on MT5 are not held by the engine. Lists show the figures the CRM stored for them, and the position page asks the MT5 bridge.
If the engine does not answer, the CRM shows the figures it stored last. The backend stores them about once a second from the status messages of the engine. A list that is sorted by one of the two figures fails instead, because its order would be wrong.
The position lists of the CRM accept these sort columns: id, accountId, symbol, side, size, status, openedAt, closedAt, updatedAt, closedPL, closedPLInAccountCurrency, swap, commission, profitLoss and margin. Any other column is answered with status 400. profitLoss and margin can only sort a list of open positions. Positions without a value come last, and positions with the same value are ordered by id.
The admin portal loads all open positions at once, keeps them current over the websocket and sorts them itself. Rows change place at most once a second.
Listing open positions in the engine
GET /admin/positions/open on the REST API of the engine returns the open positions from memory, without a database query.
| Parameter | Meaning |
|---|---|
accountIds[] | Only positions of these accounts |
groups[] | Only positions of accounts in these groups |
symbols[] | Only positions in these instruments |
side | buy or sell |
sortBy | profitLoss, swap, margin, size or openedAt, which is the default |
sortDir | ASC or DESC, which is the default |
limit | Number of positions to return. Without it, or with 0, all of them |
offset | Number of positions to skip |
The answer holds the positions of the page in positions and the number of positions that match the filters in count. Positions with the same value are ordered by id. A group admin only gets positions of accounts in their own groups. A parameter with a value that is not allowed is answered with status 422.
Modes
The environment variable GATEWAY_PROJECTOR of the backend sets the mode. In the Helm chart it is gateway.projector.
| Mode | Behaviour |
|---|---|
off | The stream is not read. For deployments without a trading engine |
dry-run | The default. The projector reads the stream, writes positions to the table gateway_shadow_position and notes in effect_ledger what each event calls for, without applying it. The queue handlers of the backend stay in charge |
live | The projector is in charge. The queue handlers ignore the messages of the engine and only handle those of the MT5 sync worker |
Comparing a dry run
During a dry run the nightly job at 00:45 UTC also compares the projector with the queue handlers. Each difference is logged as Gateway projector [TYPE] ....
| Type | Meaning |
|---|---|
POSITION | The shadow table has a position that the handlers did not write, or wrote with a different status, size, price, result, commission, stop loss or take profit |
EFFECT_UNAPPLIED | An event called for coins, a commission, a CRM transaction or a feed entry, and the handlers did not apply it |
EFFECT_UNSEEN | The handlers applied one of these and no event called for it |
Events of the last 5 minutes are left out. The swap of a position is not compared, because the handlers take it from status messages.
Every difference should be explained by a message the handlers lost before the deployment is switched to live. Two kinds of difference are expected:
- Events from the seconds before the dry run started. The handlers applied them before the ledger existed.
- Engine transactions, while the engine does not yet send the transaction id in its
TransactionCreatedmessage on thetradingexchange. Update the engine before the cashier.
Switching to live
Set the mode to live and deploy. The new instance reads the stream again from 60 seconds before it started. This applies the events that the handlers of the old instance did not get to. What the handlers did apply is in the effect ledger and is not applied again.
A deployment can be set back to dry-run. The handlers can miss messages in the seconds of that switch. The comparison lists them.
Reading again
To make the projector read the stream again from an earlier time, in UTC:
UPDATE gateway_projector_state
SET "lastSeq" = 0, "lastOffset" = NULL, "resumeFrom" = '2026-03-03 09:00:00';
A running projector notices within seconds and starts over from there. Events it has applied before change nothing.
Do not go back to a time before the projector first ran. Until then the handlers created CRM transactions and feed entries without the ledger, and the projector would create them a second time. Coins and commission are not paid twice in that case.
The stream keeps events for 7 days.
Monitoring
| Metric | Meaning |
|---|---|
cashier_gateway_projector_events_total | Events handled, by type and outcome (applied, skipped, parked) |
cashier_gateway_projector_lag_seconds | Time between the last applied event and the change it describes |
cashier_gateway_projector_connected | 1 on the instance that reads the stream, 0 on the others |
cashier_gateway_projector_parked_events | Rows in gateway_parked_event, counted once a minute |
The lag is only updated when an event arrives. Watch cashier_gateway_projector_connected as well: exactly one instance should report 1. The message bus page lists what to alert on.