โ† Recipes

Async report jobs: start, retry safely, poll, fetch

Some reports are too large for one request: up to 25 years of Varshphal, or up to 500 matchmaking pairs. Those endpoints answer 202 Accepted with a report id, and you poll for the result. This recipe covers the three things that make the pattern safe: idempotent starts, polite polling, and key-scoped results.

You build
A job runner that starts a report once even under retries, waits for it, and returns the result.
Code
Node.js, Python - no SDK, runnable as shown

Updated

The job endpoints

Start withPlanJob
POST /v1/reports/varshphal-multi-yearStarter1-25 consecutive Varshphal years: chart, Muntha, Mudda, Tajika yogas, Harsha and Panchavargeeya bala, month chart
POST /v1/compatibility/batchStarterUp to 500 Ashtakoot pairs, sorted by score
POST /v1/reports/compatibilityStarterOne detailed Gun Milan report
GET /v1/reports/:idStarterPoll: pending, ready (with result) or failed (with error_message)

Each start call returns 202 with data.id (rep_โ€ฆ) and status: "pending". Reports are kept for 30 days. Polling is a normal authenticated request: it counts against the per-minute window, and like every call below 400 it is billable.

Node: idempotent start, polite poll

javascript
// report-job.mjs - Node 18+, server-side. Job routes need the Starter plan.
const API = "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

const startJob = async (path, body, idempotencyKey) => {
  const res = await fetch(API + path, {
    method: "POST",
    headers: {
      authorization: `Bearer ${KEY}`,
      "content-type": "application/json",
      // Derive it from the job, not the attempt: a retry then gets the SAME report id.
      "idempotency-key": idempotencyKey,
    },
    body: JSON.stringify(body),
  });
  const json = await res.json();
  if (res.status !== 202) throw new Error(`${res.status} ${json.error.code}`);
  return { id: json.data.id, replayed: res.headers.get("idempotent-replayed") === "true" };
};

const waitForReport = async (id, { tries = 30, delayMs = 1000 } = {}) => {
  for (let i = 0; i < tries; i += 1) {
    const res = await fetch(`${API}/v1/reports/${id}`, { headers: { authorization: `Bearer ${KEY}` } });
    if (res.status === 429) {
      await sleep(Number(res.headers.get("retry-after") ?? 1) * 1000); // polling is rate-limited too
      continue;
    }
    const { data } = await res.json();
    if (data.status === "ready") return data.result;
    if (data.status === "failed") throw new Error(data.error_message);
    await sleep(delayMs);
  }
  throw new Error(`report ${id} still pending`);
};

const birth = { date: "1973-04-24", time: "17:25:00", tz_offset_minutes: 330, lat: 19.076, lng: 72.8777 };
const job = { birth, start_age: 53, count: 3 };

const first = await startJob("/v1/reports/varshphal-multi-year", job, "user-42:varshphal:53-55");
const retry = await startJob("/v1/reports/varshphal-multi-year", job, "user-42:varshphal:53-55");
console.log(first, retry, "same id:", first.id === retry.id);

const result = await waitForReport(first.id);
for (const y of result.years) {
  console.log(y.age, y.year_chart.solar_return.return_utc.slice(0, 10), Object.keys(y).join(","));
}
text
$ node report-job.mjs
{ id: 'rep_01M8S697D78YH9GX2NMKWFFTE3', replayed: false } { id: 'rep_01M8S697D78YH9GX2NMKWFFTE3', replayed: true } same id: true
53 2026-04-25 age,year_chart,muntha,mudda,tajika,harsha,pancha,month
54 2027-04-25 age,year_chart,muntha,mudda,tajika,harsha,pancha,month
55 2028-04-24 age,year_chart,muntha,mudda,tajika,harsha,pancha,month
  • The retry returned the same report id with idempotent-replayed: true, and no second job was queued. Without the header, a network timeout followed by a retry starts two jobs and bills two. The key is remembered for 24 hours per API key; reusing it with a different body is a 409 IDEMPOTENCY_KEY_REUSED.
  • Back off on 429. A tight polling loop on a Free-sized window runs into RATE_LIMITED; the 429 carries Retry-After and x-ratelimit-*. A one-second interval is plenty for these jobs.
  • Treat `failed` as final. error_message either describes an input problem you can fix or is a generic failure line; fix the input (or retry later) and start a new job with a new idempotency key.

The output above comes from the API running in memory without Redis, where jobs run inside the start request - so the first poll was already ready. In production jobs go through a queue and you will see pending first; write the loop for that.

Python: batch scoring, and who can read the result

Python 3.9+
# batch_job.py - Python 3.9+, standard library only. Starter plan.
import json, os, time, urllib.error, urllib.request

API = "https://api.astronode.dev"
KEY = os.environ["ASTRONODE_API_KEY"]
OTHER_KEY = os.environ["ASTRONODE_OTHER_KEY"]  # a second key on the same account

def call(method, path, key, body=None):
    req = urllib.request.Request(
        API + path, method=method,
        data=json.dumps(body).encode() if body is not None else None,
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(req) as res:
            return res.status, json.load(res)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)

seeker = {"date": "1973-04-24", "time": "17:25:00", "tz_offset_minutes": 330, "lat": 19.076, "lng": 72.8777}
pairs = [
    {"id": "match-1", "person_a": seeker,
     "person_b": {"date": "1976-09-12", "time": "06:40:00", "tz_offset_minutes": 330, "lat": 28.6139, "lng": 77.209}},
    {"id": "match-2", "person_a": seeker,
     "person_b": {"date": "1975-01-30", "time": "21:10:00", "tz_offset_minutes": 330, "lat": 12.9716, "lng": 77.5946}},
]
status, started = call("POST", "/v1/compatibility/batch", KEY, {"pairs": pairs})
report_id = started["data"]["id"]
print(status, report_id, started["data"]["status"], started["data"]["count"])

while True:
    status, polled = call("GET", "/v1/reports/" + report_id, KEY)
    if polled["data"]["status"] != "pending":
        break
    time.sleep(1)
print(polled["data"]["status"], json.dumps(polled["data"]["result"])[:160])

# Reports belong to the KEY that created them, not to the account:
status, other = call("GET", "/v1/reports/" + report_id, OTHER_KEY)
print(status, other["error"]["code"])
text
$ python3 batch_job.py
202 rep_01M8S697NV9TPX14D54MAH7GQP pending 2
ready {"count": 2, "results": [{"id": "match-1", "score": 29, "max": 36, "bucket": "Excellent", "match_percentage": 81, "manglik_match": {"boy_present": false, "girl_
404 NOT_FOUND

The last line is the scoping rule: a report is visible only to the API key that created it - not to other keys on the same account. The second key gets 404 NOT_FOUND, indistinguishable from an id that never existed. If a worker on one key starts jobs and a web service on another key reads them, either share the key between them or pass the result along yourself.

Billing and limits

  • A Hobby key gets 403 PLAN_REQUIRED from every job route and from GET /v1/reports/:id; refusals are not billed.
  • Batch limits are validated up front: count above 25 or more than 500 pairs is a 400 VALIDATION_ERROR, also not billed.
  • A replayed 202 is a successful response and is billed like the original; idempotency saves you a duplicate job, not the call.

Questions

What do I end up with?
A job runner that starts a report once even under retries, waits for it, and returns the result. The code is in Node.js and Python.
Which endpoints does this recipe call, and in what order?
4 endpoints, in this order: Multi-year Varshphal Report (Async) (POST /v1/reports/varshphal-multi-year), then Report Status and Download (GET /v1/reports/:id), then Bulk Kundli Matching (POST /v1/compatibility/batch), then Compatibility Report (Async) (POST /v1/reports/compatibility).