# Cache chart results by a hash of the birth data

> The engine is deterministic: the same input and engine version give the same `data`, byte for byte. That makes caching safe - provided two spellings of the same birth produce the same key, and a new engine version produces a different one.

Source: https://astronode.dev/recipes/cache-charts-by-birth-hash · Updated: 2026-12-01

**What you build:** A cache keyed by sha256(engine_version, path, normalised body), plus a CI test for determinism (Node.js, Python)

## Three parts of a key

- **The path.** The same birth gives different `data` on `/v1/charts/birth` and `/v1/dasha/vimshottari`.
- **The body, normalised.** `"time": "17:25"` and `"17:25:00"` are both valid and return identical data, and JSON key order is arbitrary. Sort the keys and pad the time, or the cache misses on equivalent requests.
- **`engine_version`.** Bumped whenever a change alters output. Put it in the key and a new version makes every old entry unreachable without a purge.

Leave out what changes on every call: the envelope's `request_id` and `meta.computed_at`. Store `data` and the version, nothing else.

## The cache

chart-cache.mjs

```js
// chart-cache.mjs - cache /v1/* results by a hash of the normalised request
import { createHash } from "node:crypto";

const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY;

const store = new Map(); // stand-in for Redis / Postgres / KV
let engineVersion = null; // learned from responses, persisted with your cache in real use

// Same birth, different spelling -> same key. Sort keys; pad "HH:mm" to "HH:mm:ss".
const normalise = (body) => {
  const b = { ...body };
  if (/^\d{2}:\d{2}$/.test(b.time ?? "")) b.time += ":00";
  return JSON.stringify(Object.fromEntries(Object.entries(b).sort(([x], [y]) => (x < y ? -1 : 1))));
};
const keyFor = (path, body, version) =>
  createHash("sha256").update(`${version}\n${path}\n${normalise(body)}`).digest("hex");

const cached = async (path, body) => {
  if (engineVersion) {
    const hit = store.get(keyFor(path, body, engineVersion));
    if (hit) return { ...hit, cache: "hit" };
  }
  const res = await fetch(API + path, {
    method: "POST",
    headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`${path} ${res.status}`); // never cache errors
  const { data, meta } = await res.json(); // drop request_id + computed_at: they change every call
  engineVersion = meta.engine_version; // a new version makes every old key unreachable
  const entry = { data, engine_version: meta.engine_version };
  store.set(keyFor(path, body, engineVersion), entry);
  return { ...entry, cache: "miss" };
};

const mumbai = { date: "1973-04-24", time: "17:25:00", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };
const show = (label, r) => console.log(label.padEnd(34), r.cache.padEnd(5), r.engine_version, r.data.ascendant.sign);

show("first request", await cached("/v1/charts/birth", mumbai));
show("same birth, time as 17:25", await cached("/v1/charts/birth", { ...mumbai, time: "17:25" }));
show("same birth, keys reordered", await cached("/v1/charts/birth", { lng: 72.8777, lat: 19.076, tz_offset_minutes: 330, time: "17:25:00", date: "1973-04-24" }));
show("ten minutes later", await cached("/v1/charts/birth", { ...mumbai, time: "17:35:00" }));
console.log(`${store.size} entries; key = sha256(engine_version, path, body)`);
```

Output:

```text
first request                      miss  1.2.1 Virgo
same birth, time as 17:25          hit   1.2.1 Virgo
same birth, keys reordered         hit   1.2.1 Virgo
ten minutes later                  miss  1.2.1 Virgo
2 entries; key = sha256(engine_version, path, body)
```

Four requests, two calls. The reordered and the `HH:mm` spellings hit; ten minutes later is a different birth and misses (the lagna is still Virgo, but planet degrees moved). In production the `Map` is Redis or a table, and `engineVersion` is persisted with it.

## When the engine version changes

A cache hit cannot tell you the engine moved on - you learn the current version from a fresh response. In practice misses happen constantly, so the version is refreshed within minutes; if your traffic is almost all hits, make one cheap uncached call on a schedule to read `meta.engine_version`. When it changes, old keys simply stop matching. Do not try to migrate entries: a version bump means output changed, so the old `data` is exactly what you no longer want to serve.

Two things not to normalise: coordinates and offsets. Rounding `lat` to two decimals looks harmless, but it changes the request the engine sees; hash what you send. If you want fewer distinct keys, round **before** sending and store the rounded value as the user's birth place.

## Pin the guarantee in a test

Your cache is correct only while determinism holds for the endpoints you cache. A small test - call twice, compare `data` - keeps that assumption visible in CI:

test_determinism.py

```python
# test_determinism.py - the property your cache relies on, as a test you can keep in CI
import hashlib, json, os, urllib.request

API = os.environ.get("ASTRONODE_API_URL", "https://api.astronode.dev")
KEY = os.environ["ASTRONODE_API_KEY"]

def call(path, body):
    req = urllib.request.Request(API + path, data=json.dumps(body).encode(), method="POST",
                                 headers={"Authorization": "Bearer " + KEY,
                                          "Content-Type": "application/json"})
    with urllib.request.urlopen(req) as r:
        return json.load(r)

birth = {"date": "1973-04-24", "time": "17:25:00", "tz_offset_minutes": 330,
         "lat": 19.076, "lng": 72.8777}
for path in ["/v1/charts/birth", "/v1/dasha/vimshottari", "/v1/panchang"]:
    body = {k: v for k, v in birth.items() if path != "/v1/panchang" or k != "time"}
    a, b = call(path, body), call(path, body)
    digest = lambda r: hashlib.sha256(json.dumps(r["data"], sort_keys=True).encode()).hexdigest()[:12]
    assert a["data"] == b["data"], path
    print(f"{path:<24} data {digest(a)} == {digest(b)}  "
          f"request_id differs: {a['request_id'] != b['request_id']}  "
          f"engine {a['meta']['engine_version']}")
```

Output:

```text
/v1/charts/birth         data 1ee2197eb23e == 1ee2197eb23e  request_id differs: True  engine 1.2.1
/v1/dasha/vimshottari    data ebe413060138 == ebe413060138  request_id differs: True  engine 1.2.1
/v1/panchang             data 6a7eae9e0fa6 == 6a7eae9e0fa6  request_id differs: True  engine 1.2.1
```

Do not cache endpoints that default to "now" (transit charts, Sade Sati's current phase, KP horary) unless you pass the moment explicitly - the [determinism guide](https://astronode.dev/guides/deterministic-astrology-calculations) lists them. Tarot draws are random unless you send a `seed`.

## Questions

**What do I end up with?**

A cache keyed by sha256(engine_version, path, normalised body), plus a CI test for determinism. The code is in Node.js and Python.

**Which endpoints does this recipe call, and in what order?**

3 endpoints, in this order: Birth Chart (Kundli) (`POST /v1/charts/birth`), then Vimshottari Dasha (`POST /v1/dasha/vimshottari`), then Panchang (`POST /v1/panchang`).

## Endpoints, in call order

- [`POST /v1/charts/birth`](https://astronode.dev/capabilities/vedic/charts-birth) - Birth Chart (Kundli) API
- [`POST /v1/dasha/vimshottari`](https://astronode.dev/capabilities/vedic/dasha-vimshottari) - Vimshottari Dasha API
- [`POST /v1/panchang`](https://astronode.dev/capabilities/vedic/panchang) - Panchang API
