---
title: "Cookbook"
canonical: "https://aifitnessapi.com/cookbook"
type: "cluster-index"
pages: "6"
last_reviewed: "2026-08-12"
publisher: "AIFitnessAPI"
---

# Cookbook

> 6 pages. Each entry below shows the question the page owns, followed by its answer capsule.

## Recipe: Single-Flight Refresh-Token Rotation

- Question: oauth refresh token rotation code example
- HTML: https://aifitnessapi.com/cookbook/refresh-rotation
- Markdown: https://aifitnessapi.com/cookbook/refresh-rotation.md
- Last reviewed: 2026-08-12

Refresh-token rotation breaks integrations in four predictable ways: concurrent refreshes race each other into invalid_grant, the returned refresh token is not persisted, a 401 retry loop hammers the provider, and a dead grant gets retried forever. This recipe is a small JavaScript token client that closes all four — refresh is single-flight per user, both tokens are written in one atomic save that is awaited before the promise resolves, a 401 buys exactly one refresh and one retry, and invalid_grant marks the grant dead instead of retrying. The store, the clock and fetch are all injected, so it runs in tests without a network. Copy it, swap the store for your database, and keep the tests.

## Recipe: A Replay-Safe Health Webhook Receiver

- Question: idempotent webhook receiver code example
- HTML: https://aifitnessapi.com/cookbook/webhook-receiver
- Markdown: https://aifitnessapi.com/cookbook/webhook-receiver.md
- Last reviewed: 2026-08-12

A duplicated health webhook does not throw — it lands in an aggregate and quietly doubles somebody's day. This recipe is one ingest function that makes that impossible by construction: it verifies the HMAC over the raw request bytes before anything parses them, dedupes the delivery on its id, enqueues a thin pointer instead of trusting payload values, gates every effect on a monotonic version so an out-of-order delivery is a no-op, and routes a poisoned delivery to a dead-letter queue while still acknowledging. Every collaborator is injected, so the whole replay suite runs with no network and no tunnel. The behaviour is argued in full on the webhook ingestion page; this is the code.

## Recipe: A Rate-Limit-Aware Fetch Wrapper

- Question: retry after 429 exponential backoff fetch wrapper
- HTML: https://aifitnessapi.com/cookbook/rate-limit-fetcher
- Markdown: https://aifitnessapi.com/cookbook/rate-limit-fetcher.md
- Last reviewed: 2026-08-12

Fitness providers meter reads per consented user, so one runaway backfill starves that user and adding workers makes it worse. This recipe is a fetch wrapper that tracks a per-user budget, honours Retry-After in both the delay-seconds and HTTP-date forms, backs off 5xx with full jitter so a recovering provider does not get a synchronized stampede, opens a circuit that skips and records a gap rather than hammering a dead endpoint, and never replays a non-idempotent call it cannot prove failed. The clock, sleep, jitter source and fetch are injected, so the whole fault-injection suite runs against a fake clock in milliseconds. Nothing throws on an HTTP outcome: every call returns an envelope so the caller parks the window and moves on.

## Day-Boundary Rollup: Grouping Samples by Civil Date

- Question: group health samples by local day code example
- HTML: https://aifitnessapi.com/cookbook/day-boundary-rollup
- Markdown: https://aifitnessapi.com/cookbook/day-boundary-rollup.md
- Last reviewed: 2026-08-12

A copy-and-run implementation of the civil-date daily rollup: a writer that computes each sample's local date from its instant and its UTC offset at ingest, a rollup that groups strictly on that stored date and refuses to re-derive it at read time, and helpers that report how long a given civil day actually was. Plain modern JavaScript, no dependencies, Node 20 and above, with a node:test suite that injects the offset series and the sample store so nothing touches a clock or a network. The fixed-UTC-window version is exported alongside it, marked as the anti-pattern, so the tests can show exactly which samples it invents on a spring-forward day and which it loses in autumn. The pattern itself is argued on the timezones and day boundaries page; this is the code.

## Rep Counter: A State Machine and the Scorer That Guards It

- Question: rep counting state machine code example javascript
- HTML: https://aifitnessapi.com/cookbook/rep-counter
- Markdown: https://aifitnessapi.com/cookbook/rep-counter.md
- Last reviewed: 2026-08-12

A copy-and-run rep counter and the scoring harness that keeps it honest. The counter is a two-phase finite state machine over one smoothed joint angle, with an injectable EMA constant, separate up and down entry thresholds so jitter at one boundary cannot double-fire, a minimum phase duration that rejects a spike rather than delaying it, a confidence gate, and rep events emitted with timestamps. The scorer matches predicted rep timestamps one-to-one and greedily against labelled ground truth inside a tolerance window and reports precision and recall per clip, with no aggregate and no F-score anywhere, because both let a miss and a phantom cancel out. Plain modern JavaScript, no dependencies, Node 20 and above, with a node:test suite that runs on synthetic angle streams rather than a camera.

## Backfill Checkpointer: A Resumable Window Walker

- Question: resumable backfill checkpoint 429 retry code example
- HTML: https://aifitnessapi.com/cookbook/backfill-checkpointer
- Markdown: https://aifitnessapi.com/cookbook/backfill-checkpointer.md
- Last reviewed: 2026-08-12

A copy-and-run implementation of the resumable backfill job: newest-first civil-date windows that widen as they go back, a checkpoint written to an injectable store after each window commits rather than before, 429 and 5xx handled by retrying the same window with jittered exponential backoff and Retry-After as a floor, and an exhausted retry budget recorded as a gap carrying the window and the reason instead of silently advancing. A permission wall is a distinct terminal state that is never retried, and an unrecognised error crashes with the checkpoint intact rather than being laundered into a gap. Plain modern JavaScript, no dependencies, Node 20 and above, with a node:test suite that injects the fetcher, the sleeper, the clock and the store so the whole thing runs with no network and no waiting.
