# Notify users when their dasha period changes

> A dasha change is personal - it depends on one birth - but it is also known years in advance. So the API is called when the user signs up and again only when a period actually changes; the daily job is a database query.

Source: https://astronode.dev/recipes/dasha-change-notifications · Updated: 2026-12-05

**What you build:** A push on the user's own calendar day whenever their mahadasha, antardasha or pratyantar changes (Node.js, Python)

## Precompute or chain: pick per level

[Transit alerts](https://astronode.dev/recipes/transit-alerts) are the same sky for every user, so one scan serves everyone. Dasha periods are the opposite: each user has their own boundaries, fixed at birth. That makes them cheap in a different way - nothing about them changes after signup, so there is nothing to poll.

*How often each level changes, and how to schedule it*

| Level | Typical length | Schedule it by |
| --- | --- | --- |
| Mahadasha | 6-20 years | Precomputing from the tree at signup |
| Antardasha | Months to about 3 years | Precomputing from the tree at signup |
| Pratyantar | Days to months | Chaining [`/v1/dasha/lookup`](https://astronode.dev/capabilities/vedic/dasha-lookup): one call per change |
| Sookshma, pran | Days, hours | Not a push - show it in the app if at all |

The tree from [`/v1/dasha/vimshottari`](https://astronode.dev/capabilities/vedic/dasha-vimshottari) at `levels: 2` gives every mahadasha and antardasha boundary for 120 years in one call. Going to level 3 for pratyantars multiplies the payload by about nine, most of it decades away, which is why the deeper level is chained instead.

## At signup: turn the tree into a schedule

Keep only boundaries after signup, and collapse the ones that coincide: a new mahadasha always starts with its own antardasha, at the same instant, and the user should get one message, not two. The fire date is the user's local calendar day in the zone they live in now - not UTC, and not the birth zone:

dasha-boundaries.mjs

```js
// dasha-boundaries.mjs - run once per user at signup (and again if the birth data changes)
const API = process.env.ASTRONODE_API_URL ?? "https://api.astronode.dev";
const KEY = process.env.ASTRONODE_API_KEY;

const user = {
  id: "u_481",
  zone: "Asia/Kolkata", // the user's CURRENT zone, for the notification - not the birth zone
  birth: { date: "1990-08-15", time: "06:10:00", tz_offset_minutes: 330, lat: 28.6139, lng: 77.209 },
};
const signupAt = Date.parse("2026-12-05T00:00:00Z"); // "now", passed in so the job is testable

const res = await fetch(`${API}/v1/dasha/vimshottari`, {
  method: "POST",
  headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" },
  body: JSON.stringify({ ...user.birth, levels: 2 }),
});
const { data, meta } = await res.json();

// Flatten the tree into "a new period starts at this instant" rows, future only.
// A mahadasha change is also an antardasha change at the same instant: keep one row.
const rows = new Map();
for (const maha of data.mahadasha) {
  if (Date.parse(maha.start) > signupAt) {
    rows.set(maha.start, { at: maha.start, level: "mahadasha", text: `${maha.lord} mahadasha begins (${maha.years} years)` });
  }
  for (const antar of maha.antardasha) {
    if (Date.parse(antar.start) > signupAt && !rows.has(antar.start)) {
      rows.set(antar.start, { at: antar.start, level: "antardasha", text: `${maha.lord}-${antar.lord} period begins` });
    }
  }
}
const schedule = [...rows.values()].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));

// Fire on the user's local calendar day, not the UTC one.
const localDay = (iso) => new Intl.DateTimeFormat("en-CA", { timeZone: user.zone }).format(Date.parse(iso));

console.log(`${schedule.length} future changes for ${user.id}, engine ${meta.engine_version}; next five:`);
for (const r of schedule.slice(0, 5)) console.log(`  fire ${localDay(r.at)}  (${r.at})  ${r.level.padEnd(10)} ${r.text}`);
const mahas = schedule.filter((r) => r.level === "mahadasha");
console.log(`${mahas.length} of them start a mahadasha; the first: ${localDay(mahas[0].at)} ${mahas[0].text}`);
```

Output (a 1990 Delhi birth, signing up on 5 Dec 2026):

```text
60 future changes for u_481, engine 1.2.1; next five:
  fire 2027-10-15  (2027-10-15T09:22:59.821Z)  antardasha Jupiter-Ketu period begins
  fire 2028-09-20  (2028-09-20T06:58:59.821Z)  antardasha Jupiter-Venus period begins
  fire 2031-05-22  (2031-05-22T06:58:59.821Z)  antardasha Jupiter-Sun period begins
  fire 2032-03-09  (2032-03-09T11:46:59.821Z)  antardasha Jupiter-Moon period begins
  fire 2033-07-09  (2033-07-09T11:46:59.821Z)  antardasha Jupiter-Mars period begins
6 of them start a mahadasha; the first: 2036-11-08 Saturn mahadasha begins (19 years)
```

The Saturn mahadasha begins at `2036-11-07T23:46:59Z`, which is already 8 November in India - a job that compared UTC dates would push it a day early. Sixty rows covers the rest of the 120-year cycle; store them all (they are tiny) or keep a horizon of a few decades and top it up.

## The daily job, with lookups chained for pratyantars

For the deeper level, store only the user's current chain and the instant of the next boundary at any watched level. When that day arrives, call the lookup **at the boundary instant**: a period counts as active from its `start`, so the answer is the period that begins there. Compare the lords, send one message, store the new next boundary:

dasha_job.py

```python
# dasha_job.py - the daily job. One lookup per user at signup, then one per change.
import json, os, sqlite3, urllib.request
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo

API = os.environ.get("ASTRONODE_API_URL", "https://api.astronode.dev")
KEY = os.environ["ASTRONODE_API_KEY"]
LEVELS = ["mahadasha", "antardasha", "pratyantar"]  # deepest level you notify on
calls = 0

def lookup(birth, at):
    global calls
    calls += 1
    body = {"birth_input": birth, "date": at, "system": "vimshottari"}
    req = urllib.request.Request(API + "/v1/dasha/lookup", 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)["data"]

db = sqlite3.connect(":memory:")  # your real database
db.execute("""CREATE TABLE dasha_watch (user_id TEXT PRIMARY KEY, birth TEXT, zone TEXT,
              lords TEXT, next_at TEXT)""")

def schedule(user_id, birth, zone, at):
    d = lookup(birth, at)
    lords = {lvl: d[lvl]["lord"] for lvl in LEVELS}
    next_at = min(d[lvl]["end"] for lvl in LEVELS)  # the soonest boundary at any watched level
    db.execute("INSERT OR REPLACE INTO dasha_watch VALUES (?, ?, ?, ?, ?)",
               (user_id, json.dumps(birth), zone, json.dumps(lords), next_at))
    return lords

def daily_job(now):
    """Run once a day, in the morning. Sends for every change that falls on the user's
    local today - including later today - and catches up on any day the job missed."""
    horizon = (now + timedelta(days=1)).isoformat().replace("+00:00", "Z")
    rows = db.execute("SELECT user_id, birth, zone, lords, next_at FROM dasha_watch WHERE next_at <= ?",
                      (horizon,)).fetchall()
    for user_id, birth, zone, old, next_at in rows:
        tz = ZoneInfo(zone)
        at = datetime.fromisoformat(next_at.replace("Z", "+00:00")).astimezone(tz)
        if at.date() > now.astimezone(tz).date():
            continue  # tomorrow in the user's zone: tomorrow's run sends it
        old = json.loads(old)
        new = schedule(user_id, json.loads(birth), zone, next_at)  # the period starting AT the boundary
        changed = [f"{lvl} {old[lvl]} -> {new[lvl]}" for lvl in LEVELS if old[lvl] != new[lvl]]
        print(f"sent {now.astimezone(tz):%Y-%m-%d %H:%M} to {user_id}, change at {at:%H:%M}: " + "; ".join(changed))

birth = {"date": "1990-08-15", "time": "06:10:00", "tz_offset_minutes": 330, "lat": 28.6139, "lng": 77.209}
print("at signup:", schedule("u_481", birth, "Asia/Kolkata", "2026-12-05T00:00:00Z"))

# Simulate the job at 03:30 UTC (09:00 in India) every day for eleven months.
day = datetime(2026, 12, 5, 3, 30, tzinfo=timezone.utc)
while day < datetime(2027, 11, 1, tzinfo=timezone.utc):
    daily_job(day)
    day += timedelta(days=1)
print(f"{calls} lookup calls in eleven months")
```

Output:

```text
at signup: {'mahadasha': 'Jupiter', 'antardasha': 'Mercury', 'pratyantar': 'Rahu'}
sent 2027-02-16 09:00 to u_481, change at 03:34: pratyantar Rahu -> Jupiter
sent 2027-06-06 09:00 to u_481, change at 12:51: pratyantar Jupiter -> Saturn
sent 2027-10-15 09:00 to u_481, change at 14:52: antardasha Mercury -> Ketu; pratyantar Saturn -> Ketu
4 lookup calls in eleven months
```

Four calls in eleven months for this user: one at signup and one per change. The job runs at 09:00 local and also sends changes that happen later that day - the antardasha moves from Mercury to Ketu at 14:52 on 15 October, and the morning message says so - because waiting for the instant itself would push it to the next morning. If the job is down for a few days, the `next_at <= horizon` query sends the missed change on the next run instead of skipping it.

## What moves a schedule

- **The user edits their birth details.** Delete their rows and recompute. A ten-minute change in birth time can move boundaries by weeks, which is the same sensitivity the [dasha timeline](https://astronode.dev/recipes/dasha-timeline) shows on screen.
- **The engine version changes.** Store `meta.engine_version` with the rows and recompute them when it moves; [caching by birth hash](https://astronode.dev/recipes/cache-charts-by-birth-hash) covers how to notice.
- **The user moves.** The fire day follows the zone they live in, so keep it separate from the birth `tz_offset_minutes` and let them change it.
- **Dates differ from another app by a day.** The engine uses a 365.25-day year; see [dasha dates shifted](https://astronode.dev/docs/errors/dasha-dates-shifted) before treating it as a bug.
- `/v1/dasha/vimshottari` is on the Free plan; `/v1/dasha/lookup` needs Hobby. Without Hobby, notify on mahadasha and antardasha only.

## Questions

**What do I end up with?**

A push on the user's own calendar day whenever their mahadasha, antardasha or pratyantar changes. The code is in Node.js and Python.

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

2 endpoints, in this order: Vimshottari Dasha (`POST /v1/dasha/vimshottari`), then Current Dasha Lookup (`POST /v1/dasha/lookup`).

## Endpoints, in call order

- [`POST /v1/dasha/vimshottari`](https://astronode.dev/capabilities/vedic/dasha-vimshottari) - Vimshottari Dasha API
- [`POST /v1/dasha/lookup`](https://astronode.dev/capabilities/vedic/dasha-lookup) - Current Dasha Lookup API
