# Event streams and sync

> Canonical URL: https://docs.mountaya.com/en/apis/map-studio/sync/
> Last updated: 2026-11-27
> Rules for agents: https://docs.mountaya.com/llms.txt#rules-for-agents

Keep a copy of your itineraries, zones and collections up to date: list what changed since your last sync, then follow the organization's event stream.

Keep your own copy of your organization's content up to date in two moves. List what changed since your last sync, then hold the organization's event stream open to hear about each change. A server that holds no connection open receives [webhook events](https://docs.mountaya.com/en/webhooks.md) instead.

## Before you start

The event stream acts as a member, so mint a session token that names one, as in the [quickstart](https://docs.mountaya.com/en/apis/map-studio/quickstart.md):

**cURL**

```bash
export MOUNTAYA_MEMBER_TOKEN=$(curl -s -X POST https://api.mountaya.com/v1/sessions \
  -H "X-API-Key: $MOUNTAYA_SECRET_KEY" \
  -H "Content-Type: application/json" \
  -d "{\"publishable_key\": \"$MOUNTAYA_PUBLISHABLE_KEY\", \"user_id\": \"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1\", \"surface\": \"studio-embedded\"}" \
  | jq -r .data.token)
```

**TypeScript**

```typescript
import { Mountaya } from "@mountaya/client";
import { MountayaAdmin } from "@mountaya/client/admin";

const publishableKey = process.env.MOUNTAYA_PUBLISHABLE_KEY ?? "";
const server = new Mountaya({
  credential: { secretKey: process.env.MOUNTAYA_SECRET_KEY ?? "" },
});
const { data: session } = await new MountayaAdmin(server).sessions.postSession({
  body: {
    publishable_key: publishableKey,
    user_id: "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
    surface: "studio-embedded",
  },
});

const mountaya = new Mountaya({ credential: { publishableKey, sessionToken: session.token } });
```

**Python**

```python
import json
import os
import time

import requests

session = requests.post(
    "https://api.mountaya.com/v1/sessions",
    headers={"X-API-Key": os.environ["MOUNTAYA_SECRET_KEY"]},
    json={
        "publishable_key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "user_id": "7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1",
        "surface": "studio-embedded",
    },
    timeout=10,
).json()["data"]
```

## List what changed

`updated_since` lists only what changed at or after an instant. Sort by `updated_at`, and keep the latest `updated_at` you read for your next sync.

**cURL**

```bash
curl -s "https://api.mountaya.com/v1/itineraries?updated_since=2026-11-09T00:00:00Z&sort=updated_at&limit=50" \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" \
  | jq '{changed: [.data[] | {id, name, updated_at}], pagination: .extensions.metadata.pagination}'
```

**TypeScript**

```typescript
import { paginate } from "@mountaya/client";

for await (const changed of paginate(mountaya.studio.itineraries.getItineraries, {
  query: { updated_since: "2026-11-09T00:00:00Z", sort: "updated_at" },
})) {
  console.log(changed.id, changed.name, changed.updated_at.toISOString());
}
```

**Python**

```python
cursor = None
while True:
    page = requests.get(
        "https://api.mountaya.com/v1/itineraries",
        headers={
            "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
            "X-Session-Token": session["token"],
        },
        params={
            "updated_since": "2026-11-09T00:00:00Z",
            "sort": "updated_at",
            **({"cursor": cursor} if cursor else {}),
        },
        timeout=30,
    ).json()
    for changed in page["data"]:
        print(changed["id"], changed["name"], changed["updated_at"])
    cursor = page["extensions"]["metadata"]["pagination"]["next_cursor"]
    if cursor is None:
        break
```

**Response**

```json
{
  "changed": [
    {
      "id": "0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21",
      "name": "Tour du Mont-Blanc",
      "updated_at": "2026-11-09T10:53:23.316072Z"
    },
    {
      "id": "3e8a5f21-9c47-4d6b-b0e3-6a1f7d2c9b54",
      "name": "Chamonix to Argentière",
      "updated_at": "2026-11-09T11:20:42.525768Z"
    }
  ],
  "pagination": {
    "limit": 50,
    "next_cursor": null
  }
}
```

Zones and collections take `updated_since` the same way, at `/v1/zones` and `/v1/collections`. A listing does not show what was deleted: the event stream does.

- `updated_since` (RFC 3339) keeps items whose `updated_at` is at or after it, on `GET /v1/itineraries`, `GET /v1/zones` and `GET /v1/collections`. With `sort=updated_at` a client picks up what changed since its last read without walking the whole listing. Page with `next_cursor` until it is `null`, keeping the same filters and `sort`: see [pagination](https://docs.mountaya.com/en/apis/conventions/pagination.md).
- An item edited during a walk ordered by `updated_at` moves in that order: past the cursor it is served again, behind it not at all. Keep the walk short, and start the next sync from the latest `updated_at` read, not from the clock.
- What a listing reaches follows the credential. A member's session token lists drafts, private items and unpublished ones, each as its draft. A publishable key alone, or a token minted without `user_id`, lists only public published itineraries and zones, each as last published; there, an itinerary's `updated_at` moves when it is published.
- A listing never reports a deletion or a privacy change that removes an item from what the credential lists. Reconcile those from the stream's `deleted` actions, or by comparing the ids you hold against a full listing.
- `PATCH` of a collection moves its `updated_at`; adding, removing or reordering its items does not. The stream's `collection.changed` reports both.

## Follow the event stream

`GET /v1/organizations/{organization_id}/events` is a server-sent event stream. Each frame names an itinerary, a zone or a collection that was created, updated or deleted. Refetch what it names.

**cURL**

```bash
ORGANIZATION_ID=$(curl -s -X POST https://api.mountaya.com/v1/organizations/lookup \
  -H "Content-Type: application/json" \
  -d "{\"publishable_key\": \"$MOUNTAYA_PUBLISHABLE_KEY\"}" | jq -r .data.id)

# Reads for ten seconds: curl exits 28 when --max-time ends it. Drop it to stay connected.
curl -sN --max-time 10 "https://api.mountaya.com/v1/organizations/$ORGANIZATION_ID/events" \
  -H "X-API-Key: $MOUNTAYA_PUBLISHABLE_KEY" \
  -H "X-Session-Token: $MOUNTAYA_MEMBER_TOKEN" || [ $? -eq 28 ]
```

**TypeScript**

```typescript
import { createCollabTransport } from "@mountaya/client/events";

const { data: organization } = await mountaya.studio.organizations.postOrganizationLookup({
  body: { publishable_key: publishableKey },
});

let lastEventId: string | undefined;
const close = createCollabTransport(mountaya.transport).subscribeList(organization.id, {
  onFrame: ({ event, id }) => {
    lastEventId = id ?? lastEventId;
    if ("action" in event) {
      // Refetch event.id, or drop your copy when the action is "deleted".
      console.log(event.type, event.action, event.id);
    }
  },
  onLastEventId: (position) => {
    lastEventId = position;
  },
  onClose: (reason) => console.log(`closed (${reason}), resume after ${lastEventId}`),
  onError: (error) => console.error(error),
});

// A real copy keeps the stream open. This one stops after ten seconds.
setTimeout(close, 10_000);
```

**Python**

```python
organization = requests.post(
    "https://api.mountaya.com/v1/organizations/lookup",
    json={"publishable_key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"]},
    timeout=10,
).json()["data"]

last_event_id = None
stop_at = time.monotonic() + 10  # A real copy keeps the stream open.
with requests.get(
    f"https://api.mountaya.com/v1/organizations/{organization['id']}/events",
    headers={
        "X-API-Key": os.environ["MOUNTAYA_PUBLISHABLE_KEY"],
        "X-Session-Token": session["token"],
    },
    stream=True,
    timeout=(10, 30),
) as stream:
    for line in stream.iter_lines(decode_unicode=True):
        if line.startswith("id: "):
            last_event_id = line[4:]
        elif line.startswith("data: "):
            frame = json.loads(line[6:])
            # Refetch frame["id"], or drop your copy when the action is "deleted".
            print(frame["type"], frame.get("action"), frame.get("id"))
        if time.monotonic() > stop_at:
            break
```

**Stream**

```text
id: 1794222259487-0
event: collection.changed
data: {"type":"collection.changed","kind":"collection","action":"updated","id":"59cfff6f-29bb-49e9-9090-91e211151802","itinerary_id":"00000000-0000-0000-0000-000000000000","organization_id":"a5eec5f3-3463-4b20-9469-de3eeb870a7a","revision":0,"actor_id":"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1","occurred_at":"2026-11-09T11:04:19.456109Z"}

id: 1794222300297-0
event: itinerary.changed
data: {"type":"itinerary.changed","kind":"itinerary","action":"created","id":"0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21","itinerary_id":"0b6d1a4e-6d3f-4f7a-9c2e-1f0a5b8c3d21","organization_id":"a5eec5f3-3463-4b20-9469-de3eeb870a7a","revision":1,"actor_id":"7a4e1c98-3b52-4f60-9d81-c05e2f7a83b1","occurred_at":"2026-11-09T11:05:00.29693Z"}
```

- The stream carries only durable list events: `itinerary.changed`, `zone.changed` and `collection.changed`, each with `action` `created`, `updated` or `deleted`, the resource `id`, `organization_id`, `revision`, `actor_id` and `occurred_at`. A frame names what changed, never how: refetch on `created` and `updated`, drop your copy on `deleted`. On `collection.changed`, `id` is the collection even when what moved was an itinerary or a zone entering or leaving it; `itinerary_id` is the all-zero UUID and `revision` is `0`.
- `revision` is `0` on a `deleted` frame, and on an `itinerary.changed` or `zone.changed` `updated` frame whose write was made but whose request failed after it, such as a publication made or withdrawn: refetch on it. Never skip a frame because its `revision` is not above your copy's.
- Each frame is `id: <stream id>`, `event: <type>`, `data: <json>`. The server writes a comment line (`: …`) every 15 seconds; ignore it. A `HEAD` answers the stream's headers and opens nothing.
- Without `Last-Event-ID` the server first replays every event it still holds for the organization (about the last thousand, for an hour after the latest), then the live feed; applying a frame twice is harmless. To resume after a drop, reopen with the `Last-Event-ID` header set to the last `id:` you read. After a gap longer than the hour, list with `updated_since` instead. A `Last-Event-ID` that is not two numbers joined by a hyphen is a `400`.
- The stream ends with its credential. When the session token expires, or the key is revoked, loses `studio-embedded` or its organization is canceled, the stream writes `event: reconnect` with `data: {"reason":"credential-expired"}` or `{"reason":"credential-revoked"}` and closes: reopen at once with a fresh token and `Last-Event-ID`. It also writes `reconnect` with `reason` `interrupted` when the server cannot keep delivering; reopen the same way. A `401` on the reopen means the credential is gone. The TypeScript transport reports these closes as `onClose("reconnect")`.
- Membership is checked about every ten seconds; a member removed from the organization has the stream ended, and reopening answers `403` (or `402` without Map Studio).
- It needs the `studio-embedded` scope and a session token minted for `studio-embedded` naming a member, any role. The path must name the key's own organization (`403` otherwise). `EventSource` cannot send the headers: read the stream with `fetch`, `@mountaya/client/events`, or an HTTP client that streams.
- A stream that cannot be opened for a moment, because its events or the member's access cannot be reached, is a `503` with `Retry-After: 1`, answered before any event: reopen with `Last-Event-ID`, and nothing is missed. The TypeScript SDK's collaboration session reopens it itself.
- Limits: 60 opens a minute per user and 1,200 per organization, each open also a session-token read (1,200 a minute per user, 6,000 per organization); at most 20 streams open at once per user, 50 per client IP address and 1,000 per organization. Past any, `429` with `Retry-After`.

## One itinerary or zone at a time

`GET /v1/itineraries/{itinerary_id}/events` and `GET /v1/zones/{zone_id}/events` stream one resource's edits as they happen: its segments and waypoints, and who is editing. They are what Map Studio's collaboration runs on.

- `getItineraryEvents` carries `itinerary.changed`, `segment.changed` and `waypoint.changed` (durable, replayed after `Last-Event-ID`), and the live-only `presence.snapshot`, `presence.join`, `presence.leave`, `lock.snapshot`, `lock.acquired`, `lock.released`, `selection`, `cursor`, `draft.update` and `draft.clear`, plus `reconnect`. `getZoneEvents` carries the zone's equivalents.
- `segment.changed` reports a segment appended to the end of the chain, or updated. A segment deleted, merged, split, converted or inserted before another, and a change to a segment group, is an `itinerary.changed` `updated` frame instead: refetch the itinerary.
- On connect it sends `presence.snapshot` and `lock.snapshot`, then, on a member's first stream, broadcasts `presence.join`, which reaches that stream as well. It re-sends both snapshots every few seconds. A peer that disconnects uncleanly keeps its presence for 45 seconds and its locks for 60.
- A stream that cannot be opened for a moment is a `503` with `Retry-After: 1`, answered before any event and within seconds: open it again from the last event id, and nothing is missed. The TypeScript SDK's collaboration session reopens it itself. The organization stream answers it the same way.
- Any member may watch; sending signals (`postItineraryCollab`, `postZoneCollab`) needs a write role. A personal itinerary has no collaboration session.
- The same reconnect, replay, heartbeat and limit rules as the organization stream apply.

## Next steps

- [Pagination](https://docs.mountaya.com/en/apis/conventions/pagination.md): Cursors, filters and sort orders.
- [Publishing](https://docs.mountaya.com/en/apis/map-studio/publishing.md): What a publish changes, and when.
