โ† Recipes

Batch-compute charts for your existing users

Backfills hit limits that a normal request flow never sees. Both ways of staying inside them are below, run against a Free-plan key (60 requests a minute) with 70 and 65 users.

You build
A backfill job that finishes without wasted calls, whatever your plan's limit
Code
Node.js, Python - no SDK, runnable as shown

Updated

The limits a backfill meets

What stops a batch, and how to tell
LimitResponseWhat to do
Requests per minute, per API key (sliding 60 s)429 + error.code: "RATE_LIMITED" + Retry-AfterWait Retry-After seconds, retry the same request
Requests per month, per account429 + error.code: "QUOTA_EXCEEDED"Stop the job; resume next month or upgrade
Endpoint not in your plan403 PLAN_REQUIREDStop; no retry will help

The two 429s share a status, so switch on error.code, never on the status alone. Every response - successes too - carries x-ratelimit-limit, x-ratelimit-remaining and x-ratelimit-reset (the unix second when the window frees its next slot). Only responses below 400 count toward the monthly quota, so a refused request costs nothing. Limits per plan are on rate limits and quotas; estimate a backfill's duration with the rate-limit planner.

Reactive: a worker pool that honours Retry-After

Four workers drain a queue of users. A RATE_LIMITED response puts that worker to sleep for Retry-After seconds and retries the same user; QUOTA_EXCEEDED aborts the whole job; 5xx gets two short retries; any 400 is a data problem to log, not retry:

backfill-charts.mjs

Node.js
// backfill-charts.mjs - compute a chart for every existing user, within your plan's limits
const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY;
const CONCURRENCY = 4; // parallel requests in flight; the per-minute limit still applies
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const t0 = Date.now();
const log = (msg) => console.log(`[${String(Math.round((Date.now() - t0) / 1000)).padStart(3)}s] ${msg}`);

// Stand-in for your users table: 70 people born on consecutive days of 1990.
const users = Array.from({ length: 70 }, (_, i) => ({
  id: `user_${i + 1}`,
  birth: { date: new Date(Date.UTC(1990, 0, 1 + i)).toISOString().slice(0, 10), time: "08:30:00",
    tz_offset_minutes: 330, lat: 12.9716, lng: 77.5946 },
}));

class QuotaExhausted extends Error {}

const chartFor = async (user) => {
  for (let attempt = 1; ; attempt++) {
    const res = await fetch(`${API}/v1/charts/birth`, {
      method: "POST",
      headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
      body: JSON.stringify(user.birth),
    });
    if (res.ok) return res.json();
    const { error } = await res.json();
    if (res.status === 429 && error.code === "RATE_LIMITED") {
      const wait = Number(res.headers.get("retry-after") ?? "1");
      log(`${user.id}: RATE_LIMITED, remaining=${res.headers.get("x-ratelimit-remaining")}, retry-after=${wait}s`);
      await sleep(wait * 1000); // a refused call is not billed, so retrying costs nothing
      continue;
    }
    // Same 429 status, different meaning: the month is used up. Stop; do not loop.
    if (res.status === 429 && error.code === "QUOTA_EXCEEDED") throw new QuotaExhausted(error.message);
    if (res.status >= 500 && attempt < 3) { await sleep(1000 * attempt); continue; }
    throw new Error(`${user.id}: ${res.status} ${error.code}`); // 400s: fix the stored data
  }
};

const results = new Map();
const queue = [...users];
const worker = async () => {
  for (let u = queue.shift(); u; u = queue.shift()) {
    const { data, meta } = await chartFor(u);
    // Store the version with the chart: it is how you know what to recompute later.
    results.set(u.id, { lagna: data.ascendant.sign, engine_version: meta.engine_version });
  }
};
await Promise.all(Array.from({ length: CONCURRENCY }, worker));
log(`done: ${results.size} charts, engine ${results.get("user_1").engine_version}`);

Output (Free plan, 70 users):

text
[  0s] user_61: RATE_LIMITED, remaining=0, retry-after=60s
[  0s] user_62: RATE_LIMITED, remaining=0, retry-after=60s
[  0s] user_63: RATE_LIMITED, remaining=0, retry-after=60s
[  0s] user_64: RATE_LIMITED, remaining=0, retry-after=60s
[ 60s] done: 70 charts, engine 1.2.1

The first 60 calls succeeded within the first second; calls 61-64 were refused with Retry-After: 60; after the wait the remaining ten went through. The four refusals were not billed.

Proactive: pace on the headers

If you would rather never see a 429, read x-ratelimit-remaining after each call and pause until x-ratelimit-reset when it hits zero:

paced_backfill.py

Python 3.9+
# paced_backfill.py - read the rate-limit headers and pause BEFORE the API says no
import json, os, time, urllib.request

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

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

done = 0
for day in range(1, 66):
    birth = {"date": f"1991-03-{day % 28 + 1:02d}", "time": "21:05", "tz_offset_minutes": 330,
             "lat": 22.5726, "lng": 88.3639}
    body, headers = chart(birth)
    done += 1
    if headers["x-ratelimit-remaining"] == "0":
        # x-ratelimit-reset is the unix second when the window frees its next slot;
        # +1: a margin for clock skew between your server and the API's.
        wait = max(0, int(headers["x-ratelimit-reset"]) + 1 - time.time())
        print(f"[{time.time() - t0:4.0f}s] {done} done, limit {headers['x-ratelimit-limit']}/min reached; "
              f"sleeping {wait:.0f}s")
        time.sleep(wait)
# urlopen raises on any 4xx, so reaching this line means no request was refused
print(f"[{time.time() - t0:4.0f}s] {done} charts, no 429s")

Output (Free plan, 65 users):

text
[   0s] 60 done, limit 60/min reached; sleeping 60s
[  60s] 65 charts, no 429s

The + 1 is a margin, not a correction: x-ratelimit-reset is rounded up to the whole second, so it is never before the slot frees, but your server's clock and the API's can disagree by a fraction of a second. Sleeping one extra second costs little and avoids a refused call.

Choosing the shape of the job

  • Concurrency does not raise the limit. It only gets you to it sooner. On Free, 60 per minute is 3,600 charts an hour whether you use 1 worker or 40.
  • The monthly quota is the real ceiling. The Free plan's 1,000 calls a month cannot backfill 5,000 users; work out calls x users against pricing before you start.
  • Store `meta.engine_version` with every result - it is how you later find the rows to recompute, and with caching by birth-data hash duplicate births cost one call.
  • Make the job resumable. Write each result as it arrives and skip users who already have one, so a crash or a quota stop does not repeat billed calls.
  • Errors are documented on RATE_LIMITED and QUOTA_EXCEEDED.

Questions

What do I end up with?
A backfill job that finishes without wasted calls, whatever your plan's limit. The code is in Node.js and Python.
Which endpoints does this recipe call, and in what order?
1 endpoint, in this order: Birth Chart (Kundli) (POST /v1/charts/birth).

In the API

Endpoints this recipe calls

  1. Birth Chart (Kundli) APIPOST /v1/charts/birth