# Reserve and settle online quota

> Connect a network client to chargingd, reserve prepaid bytes or API calls, settle usage and reconcile mediation copies in the Desk.


A network function asks chargingd how many bytes or API calls it may deliver. Sessions on the same prepaid subscription share the tariff allowance. Accounting reserves the money needed for paid units against both the wallet and its monthly limit. When the network reports usage, the same rating function used for offline billing values it and accounting releases unused cover.

The example API tariff includes 100 calls and charges €0.10 for each additional call. With €3 of monthly headroom, a first session can reserve 120 calls and a second can reserve ten. If they report 112 and ten calls, the wallet pays €2.20 in total, in either reporting order.

## Connect a network client

1. Start the services with `just dev` against a database initialized with the five service roles (`deploy/postgres/init.sql`). `just db-reset` recreates the development database and erases its data. Set the example subscription's effective price book to `example-api@2026-11` and plan to `prepaid-api` for API calls. For mobile data, use a plan with a byte-based data tariff. Enroll and fund the account before its first usage in the service month. [Fund a prepaid wallet](../docs/prepaid/)
2. Configure a named `charging-client` credential for each network gateway in chargingd. Set `TELCO_CHARGING_TOKEN` to a separate service credential accepted by both billd and accountingd with role `charging`. Supply the same pinned price books to billd and chargingd. In production, terminate HTTP/2 TLS and authenticate the network function at the operator gateway. Keep service and operator credentials private.
3. For the local example, `OPERATOR_TOKEN=dev-token-0123456789` and `NETWORK_TOKEN=dev-network-token-0123456789` match the development launcher. On the operator connection, bind the gateway name and rating group to the subscription. The commands below use the local development service. Set `ACCOUNT` and `SUBSCRIPTION` to the enrolled UUIDs.

```sh
CHF=http://127.0.0.1:9405
curl --fail-with-body -X PUT "$CHF/charging-bindings/$SUBSCRIPTION" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H 'Content-Type: application/json' \
  -d "{\"account\":\"$ACCOUNT\",\"consumer\":\"network\",\"subscriber\":\"imsi-262010000000001\",\"rating_group\":7,\"kind\":\"api-call\",\"unit\":\"count\"}"
```

## Reserve, report and release

Send the following JSON by POST to `/nchf-convergedcharging/v3/chargingdata` with the network bearer and `Content-Type: application/json`. Use the current invocation timestamp and a fresh charging ID. The first successful Create returns HTTP 201 and a session URI in `Location`. Read the actual grant before delivering service.

```json
{
  "subscriberIdentifier": "imsi-262010000000001",
  "chargingId": 11,
  "nfConsumerIdentification": {"nodeFunctionality": "NEF"},
  "invocationTimeStamp": "2026-11-04T11:00:00Z",
  "invocationSequenceNumber": 0,
  "multipleUnitUsage": [{"ratingGroup": 7, "requestedUnit": {"serviceSpecificUnits": 120}}]
}
```

Save the Create payload as `create.json` and send it with the named network credential.

```sh
curl --fail-with-body -i "$CHF/nchf-convergedcharging/v3/chargingdata" \
  -H "Authorization: Bearer $NETWORK_TOKEN" -H 'Content-Type: application/json' \
  --data-binary @create.json
```

For each subsequent POST retain the subscriber, charging ID, NF and rating group. Advance the invocation sequence by one and set its timestamp. Send one group per session and one incremental used-unit container per report.

| Operation | Request within the group | Result |
|---|---|---|
| POST to the session URI plus `/update` | `"usedUnitContainer":[{"localSequenceNumber":1,"serviceSpecificUnits":80}],"requestedUnit":{"serviceSpecificUnits":40}` | HTTP 200 returns the next grant. Honor its quantity and validity. |
| POST to the session URI plus `/release` | `"usedUnitContainer":[{"localSequenceNumber":2,"serviceSpecificUnits":32}]` | HTTP 204 closes the session and settles the final increment. |

For bytes use `totalVolume` in both containers. A partial grant can carry a final-unit indication. A refused quota request returns HTTP 403 with cause `QUOTA_LIMIT_REACHED`. Stop delivery when quota or validity runs out. A denied renewal can still settle the usage reported with it. After a timeout, resend the same operation, sequence, quantities and original timestamp. A changed retry conflicts with the retained invocation.

If a tariff correction overlaps already granted or reported use, new sessions return `charging.tariff`. Settle the existing grants on their pinned terms and provision the next clean tariff interval.

A grant lasts at most five minutes and ends by the next Berlin midnight. The network has one further hour to report delivered usage against the hold. Later reports and overruns retain the delivered quantity and its financial evidence. The operator covers unfunded delivery. If reported units exceed authorized consumption, the service suspends new grants against the affected tariff pool. Existing grants can still settle. Inspect the session and mediation records before commissioning further traffic. The implementation covers session-based SMF and NEF charging for one rating group using bytes or counted events. Commission each gateway against this profile. [ETSI TS 132 291 V18.10.0, Annex A.2](https://www.etsi.org/deliver/etsi_ts/132200_132299/132291/18.10.00_60/ts_132291v181000p.pdf)

## Reconcile a service month

Open **Online-Abrechnung** in the Desk. Select a month for separate data and API totals. Inspect a session's validity, reserved amount and invocation history. A paid report links to its journal receipt. Use its report UUID as the `online_report` reference on the corresponding mediation copy. billd retains copies that arrive first and exposes differences for review without charging the wallet twice. [Reconcile online usage](../docs/mobile-usage/#reconcile-online-charging)

Compare the value of delivered units with funded and operator-covered charges. Treat open sessions, discrepancies and pending reports as provisional. Missing secondary copies appear separately so an API with no independent feed can be interpreted correctly. Decision latency and refusal counts are available per channel at `GET /charging-metrics?month=YYYY-MM`. The Desk exposes operator reads. Provision bindings and submit network traffic through the private service.

### Local decision latency

Four concurrent HTTP clients opened 32 sessions on one wallet. Each session reported one call in an Update, requested another call, then released its final usage. The release build used the real contract, tariff, wallet and journal services over loopback with PostgreSQL. The client timed each operation through receipt of its complete response.

| Operation | Samples | p50 | p95 | p99 |
|---|---:|---:|---:|---:|
| Create | 32 | 84 ms | 130 ms | 183 ms |
| Update | 32 | 80 ms | 101 ms | 122 ms |

The 96 requests took 1.96 seconds at concurrency four. A second run took 2.39 seconds, with p95 of 183 ms for Create and 193 ms for Update. With 32 samples the p99 is the slowest observation. Host contention affected the measurements. Establish the production timeout and throughput target with the intended gateway and database.

To reproduce the sample, set `TELCO_TEST_DATABASE_URL` to a development PostgreSQL connection with database-creation privileges and run:

```sh
cargo test --workspace --release --test online_estate four_service_quota_latency -- --ignored --nocapture
```
