โ† Integrations

Serverless ยท JavaScript

A Rahu kaal endpoint on AWS Lambda

This Lambda takes a date and a place and returns the day's three inauspicious windows - Rahu kaal, Yamaganda and Gulika - in UTC and in local time. The interesting parts are not the call itself but where the key comes from, when it is fetched, and how long the function is allowed to wait.

Updated

How this page was checked: index.mjs was executed on Node 24 against the in-memory API with API Gateway payload-v2 events (plain and base64 bodies). @aws-sdk/client-secrets-manager is not installed on the build machine, so a two-class stand-in with the same send(new GetSecretValueCommand(...)) shape supplied the secret; the timeout path was run against a local server that never answered in time. Not run: Lambda itself, IAM, the AWS CLI commands.

Where the key comes from

Two options, and the handler below supports both. A plain environment variable (ASTRONODE_API_KEY) is encrypted at rest but readable by anyone who can view the function's configuration in the console. Secrets Manager keeps the value out of the function configuration entirely; the function holds only the secret's name and an IAM permission to read it.

bash
aws secretsmanager create-secret --name astronode/api-key --secret-string "aie_live_..."

aws lambda update-function-configuration --function-name rahu-kaal \
  --timeout 15 \
  --environment "Variables={ASTRONODE_SECRET_ID=astronode/api-key}"

The execution role needs secretsmanager:GetSecretValue on that secret's ARN. The Node.js 20 and later managed runtimes include the AWS SDK for JavaScript v3, so the import below needs no bundling.

The handler

index.mjs (ES module, so top-level await works):

js
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const BASE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";

// Top-level await runs once, during the cold start. Warm invocations reuse API_KEY.
async function loadKey() {
  if (process.env.ASTRONODE_API_KEY) return process.env.ASTRONODE_API_KEY;
  const sm = new SecretsManagerClient({});
  const out = await sm.send(new GetSecretValueCommand({ SecretId: process.env.ASTRONODE_SECRET_ID }));
  return out.SecretString;
}
const API_KEY = await loadKey();

const reply = (statusCode, body) => ({
  statusCode,
  headers: { "content-type": "application/json" },
  body: JSON.stringify(body),
});

export const handler = async (event) => {
  const raw = event.isBase64Encoded ? Buffer.from(event.body ?? "", "base64").toString() : event.body;
  let input;
  try {
    input = JSON.parse(raw ?? "{}");
  } catch {
    return reply(400, { error: "body is not JSON" });
  }
  const { date, tz_offset_minutes, lat, lng } = input;

  let res;
  try {
    res = await fetch(`${BASE}/v1/muhurta/inauspicious`, {
      method: "POST",
      headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify({ date, tz_offset_minutes, lat, lng }),
      signal: AbortSignal.timeout(8000), // below the function timeout
    });
  } catch {
    return reply(504, { error: "AstroNode did not answer in 8 s" });
  }
  const json = await res.json();
  if (!res.ok) return reply(res.status === 400 ? 400 : 502, { error: json.error.code, details: json.error.details });

  const hhmm = (iso) => new Date(Date.parse(iso) + tz_offset_minutes * 60_000).toISOString().slice(11, 16);
  const { rahu_kaal, yamaganda_kaal, gulika_kaal } = json.data;
  return reply(200, {
    date,
    windows: [rahu_kaal, yamaganda_kaal, gulika_kaal].map((w) => ({
      name: w.name,
      start: w.start,
      end: w.end,
      local: `${hhmm(w.start)}-${hhmm(w.end)}`,
    })),
  });
};

The handler reads only event.body and event.isBase64Encoded, which a function URL, an HTTP API and a REST API all provide, so the same code works behind any of them. Function URLs and HTTP APIs may deliver the body base64-encoded; skipping that check gives you a JSON.parse error on some requests and not others. Picking the four fields out of the body drops anything else the caller sent - a city label, say - which the API would otherwise reject.

What it returned

Request body:

json
{ "date": "2026-12-07", "tz_offset_minutes": 330, "lat": 12.9716, "lng": 77.5946 }
Bengaluru, Monday 7 December 2026
WindowUTC (from the API)Local (IST)
Rahu Kaal02:24:36 - 03:50:0307:54 - 09:20
Yamaganda Kaal05:15:30 - 06:40:5610:45 - 12:10
Gulika Kaal08:06:23 - 09:31:4913:36 - 15:01

Each window is one eighth of the local sunrise-to-sunset day, which is why the same Monday in London (tz_offset_minutes: 0) gives Rahu kaal 08:51-09:51: a shorter winter day, so one-hour slices. /v1/muhurta/inauspicious needs the Hobby plan or above. Sending tz_offset_minutes as the string "330" - easy when the value comes from a query string - returns 400 with "Invalid input: expected number, received string", which the handler passes back with its details.

Timeouts, set on purpose

  • The default Lambda timeout is 3 seconds. A cold start that also fetches a secret can use a good part of that before the handler runs. Set it explicitly - 15 s above - and keep the fetch deadline below it (AbortSignal.timeout(8000)), so a slow upstream becomes your clean 504 instead of Lambda's "Task timed out". In the run against a server that never replied in time, the handler returned the 504 after 8.06 s.
  • API Gateway has its own limit (29 seconds by default for REST APIs, 30 seconds for HTTP APIs), whatever the function's timeout. A function URL waits for the full function timeout.
  • The secret fetch belongs to the init phase, which on-demand functions get up to 10 seconds for. If it throws, the function fails to initialise and every invocation errors until the cause is fixed - check the role's permission first.

The mistake that bites first: a key/value secret

The Secrets Manager console's default secret type stores key/value pairs, so SecretString comes back as {"ASTRONODE_API_KEY":"aie_live_..."}, not the key. The handler then sends that JSON as the bearer token; in the run, AstroNode answered 401 UNAUTHORIZED and the function returned 502. Either store the secret as plaintext (--secret-string as above) or parse it: JSON.parse(out.SecretString).ASTRONODE_API_KEY.

A function URL created with --auth-type NONE is public: anyone who finds it spends your quota. Use AWS_IAM for service-to-service calls, or put API Gateway with a usage plan in front.

Questions

Which AstroNode endpoints does the AWS Lambda example call?
1 endpoint: Rahu Kaal, Yamaganda and Gulika (POST /v1/muhurta/inauspicious).
Was the AWS Lambda code on this page actually run?
index.mjs was executed on Node 24 against the in-memory API with API Gateway payload-v2 events (plain and base64 bodies). @aws-sdk/client-secrets-manager is not installed on the build machine, so a two-class stand-in with the same send(new GetSecretValueCommand(...)) shape supplied the secret; the timeout path was run against a local server that never answered in time. Not run: Lambda itself, IAM, the AWS CLI commands.