Change Tracking

Objects in acre Access Control have no “last modified” field. Instead, every time an object is created, updated or deleted, the system writes an Object Modified event. That event includes a copy of the object as it looks after the change.

This page shows how to use those events to keep your own copy of the data up to date. The main path is live, over MQTT. There is also a small set of queries for catching up after you have been offline.

In the examples, {base} is the regional API address and {folder} is the key of the instance root folder. All dates are UTC.

The idea

Every create, update and delete writes an Object Modified event. (Changes to Metadata also write one, but only if events are turned on for that form or write; see Good to know.)

Each event has an EventData part with three important fields:

  • Action: POST (created), PUT (updated) or DELETE (deleted).
  • Key: which object changed.
  • AfterData: the whole object, as it is after the change.

There are two ways to get these events. Most integrations use both.

Live (recommended). Subscribe to Object Modified events over MQTT. When an event arrives, update your copy of the object from AfterData (for POST and PUT), or remove it (for DELETE). You do not need to poll, and you do not need to call GET or search to fetch the new state. It is already in the event. See Using the event payload below.

Catch-up. Use this only when the live feed was not available: when your integration starts, or after it lost its MQTT connection. Do not run it on a timer. Polling the Events collection is not a replacement for the subscription.

To catch up, remember the OccurredOn time of the last event you applied. Call it lastSync. When you reconnect:

  1. Count the Person changes since lastSync (query 3). If the count is zero, you are done.
  2. List the people that changed (query 2), or read the events themselves and use their AfterData.
  3. If there are people you still need to fetch, read them in one search stream. Treat any key that does not come back as deleted.
  4. Move lastSync forward to the newest occurredOn you handled.

To be safe, start a little earlier than lastSync (say 60 seconds) and make sure applying the same change twice does no harm.

Finding the event type key

The key of the Object Modified event type is different in every deployment, so look it up at start-up. It takes two calls:

GET {base}/api/f/{folder}/apps?apiKey=KeepApi                → take Key as {appKey}
GET {base}/api/f/{folder}/apps/{appKey}/eventtypes?namespace=KeepApiEvents&nickname=ObjectMod

The second call returns the event type. Its Key is what the examples call {objectModTypeId}. The examples also use {instanceId}, which is the Key returned by GET {base}/api.

What an event looks like

The fields you will use most:

  • OccurredOn.Date — when the change happened (UTC).
  • EventTypeId — {objectModTypeId} for object changes.
  • ObjectLinks[] — the objects involved. The one that changed is the link whose Relation is its type name (Person, Reader, and so on). That link has the object’s LinkedObjectId (its key) and CommonName. The link with Relation: "User" is the user who made the change.

Running a query

POST {base}/api/f/{folder}/aggregate/Events?queryTimeout=120&jsonStrict=true

The body is an array, and each pipeline stage is a JSON string. The pipelines below are shown as plain objects so they are easier to read. Turn each stage into a string before you send it:

[
  "{\"$match\":{\"ObjectLinks.Relation\":\"Person\"}}",
  "{\"$count\":\"total\"}"
]

The response is an array of strings, one per result document. jsonStrict=true makes the server return standard extended JSON that any JSON parser can read.

Every example below ends with the same two stages. They pick the Person link out of ObjectLinks and give it a simple shape:

{
  "$addFields": {
    "person": {
      "$arrayElemAt": [
        {
          "$filter": {
            "input": "$ObjectLinks",
            "as": "l",
            "cond": { "$eq": ["$$l.Relation", "Person"] }
          }
        },
        0
      ]
    }
  }
},
{
  "$project": {
    "_id": 0,
    "occurredOn": "$OccurredOn.Date",
    "personKey": "$person.LinkedObjectId",
    "personName": "$person.CommonName"
  }
}

To keep the examples short, these two stages are written as …person stages….

1. When was any Person last changed?

[
  {
    "$match": {
      "InstanceScopeId": { "$oid": "{instanceId}" },
      "ObjectLinks.Relation": "Person",
      "EventTypeId": { "$oid": "{objectModTypeId}" }
    }
  },
  {
    "$sort": { "OccurredOn.Date": -1 }
  },
  {
    "$limit": 1
  },
  …person stages…
]
[
  {
    "occurredOn": "2026-11-15T17:42:08.113Z",
    "personKey": "68a1…",
    "personName": "Jane Example"
  }
]

2. Which people changed since lastSync, and how?

[
  {
    "$match": {
      "InstanceScopeId": { "$oid": "{instanceId}" },
      "ObjectLinks.Relation": "Person",
      "EventTypeId": { "$oid": "{objectModTypeId}" },
      "OccurredOn.Date": { "$gt": { "$date": "{lastSync}" } }
    }
  },
  {
    "$sort": { "OccurredOn.Date": -1 }
  },
  …person stages…,
  {
    "$group": {
      "_id": "$personKey",
      "personName": { "$first": "$personName" },
      "lastChange": { "$first": "$occurredOn" },
      "changeCount": { "$sum": 1 }
    }
  },
  {
    "$sort": { "lastChange": -1 }
  }
]
[
  {
    "_id": "68a1…",
    "personName": "Jane Example",
    "lastChange": "2026-11-15T17:42:08Z",
    "changeCount": 3
  },
  {
    "_id": "6899…",
    "personName": "Sam Example",
    "lastChange": "2026-11-15T09:10:51Z",
    "changeCount": 2
  }
]

The result is the list of people you need to refresh. The next section shows how to fetch them. This query gets slower as the number of events in the window grows, so reconnect as soon as you can after a disconnect.

3. How many Person changes since lastSync?

Same $match as query 2, then:

{
  "$count": "total"
}
[
  { "total": 221 }
]

This query is cheap, so run it first when you catch up:

  • If the total is zero, nothing changed while you were away. Stop here.
  • If the total is small, run query 2 and refresh those people.
  • If the total is very large, or query 2 times out, there are too many changes to replay one by one. Do a full resync instead (stream all people, see below). It is simpler and usually faster.

4. When was a specific Person last changed?

[
  {
    "$match": {
      "ObjectLinks": {
        "$elemMatch": {
          "LinkedObjectId": { "$oid": "{personKey}" },
          "Relation": "Person"
        }
      },
      "EventTypeId": { "$oid": "{objectModTypeId}" }
    }
  },
  {
    "$sort": { "OccurredOn.Date": -1 }
  },
  {
    "$limit": 1
  },
  …person stages…
]

Use this for one person, not for a list. This query answers a question about a single Person, for example when a user looks someone up. Do not use it to find all changes. Running it once per person for 700,000 people means 700,000 queries. Instead, keep one lastSync time for your whole integration and use queries 2 and 3 to find every change in one pass.

The events stream

If you would rather have a plain list of events than an aggregation, use the events stream. It returns matching events one per line, newest first, with no paging:

GET {base}/api/f/{folder}/eventsstream

Each line is one full event (OccurredOn, ObjectLinks, EventData, and so on). Read it line by line as it arrives. In the wrapper, use EventsStream.Create(client, folder, …) and a ReadAsync loop.

Option Meaning
startingOn, endingOn UTC bounds on OccurredOn.Date. startingOn is inclusive, endingOn is exclusive.
forKeys Event type keys. Repeat the parameter once per key. Events of any listed type are returned.
forAllKeys Object keys. Only events whose ObjectLinks contain all of these objects. For a single Person, pass its key here.
query A MongoDB filter, as a URL-encoded JSON string, added to the server’s own filter.
includeSubFolders Include events from folders below {folder}.
sinceKey An event key. Returns only events older than that one. Useful to carry on after a stream was cut off.
priorityThreshold Minimum event priority. Not needed for change tracking.

Example 1 — Person changes since lastSync. The query value is the filter {"ObjectLinks.Relation":"Person"}, URL-encoded:

GET {base}/api/f/{folder}/eventsstream
      ?startingOn=2026-11-16T00:00:00Z
      &forKeys={objectModTypeId}
      &includeSubFolders=true
      &query=%7B%22ObjectLinks.Relation%22%3A%22Person%22%7D

This is shown on several lines to make it readable. Send it as one URL. With curl, you can let the tool do the encoding:

curl -G "{base}/api/f/{folder}/eventsstream" \
  -H "Authorization: Bearer $TOKEN" \
  --data-urlencode "startingOn=2026-11-16T00:00:00Z" \
  --data-urlencode "forKeys={objectModTypeId}" \
  --data-urlencode "includeSubFolders=true" \
  --data-urlencode 'query={"ObjectLinks.Relation":"Person"}'

Example 2 — several event types at once. To get both Object Modified and Access Granted events for one Person, repeat forKeys once per event type and put the Person’s key in forAllKeys. Note that Access Granted is two event types, one from each access control service. You need both to see every grant:

curl -G "{base}/api/f/{folder}/eventsstream" \
  -H "Authorization: Bearer $TOKEN" \
  --data-urlencode "startingOn=2026-11-16T00:00:00Z" \
  --data-urlencode "forKeys={objectModTypeId}" \
  --data-urlencode "forKeys={mercuryGrantedTypeId}" \
  --data-urlencode "forKeys={acGrantedTypeId}" \
  --data-urlencode "forAllKeys={personKey}" \
  --data-urlencode "includeSubFolders=true"

Each Access Granted type belongs to its own service app. Look them up the same way as Object Modified:

Mercury service
GET {base}/api/f/{folder}/apps?apiKey=MercuryService                      → take Key as {mercuryAppKey}
GET {base}/api/f/{folder}/apps/{mercuryAppKey}/eventtypes?namespace=MercuryServiceEvents&nickname=mercury:granted

Access control service
GET {base}/api/f/{folder}/apps?apiKey=com.feenics.ac                      → take Key as {acAppKey}
GET {base}/api/f/{folder}/apps/{acAppKey}/eventtypes?namespace=com.feenics.ac&nickname=granted

On some deployments the access control service uses the shorter namespace ac. If the second lookup returns nothing, try again with namespace=ac.

The stream gives you the same data as queries 1, 2 and 4, but without the grouping. It is a good fit when you want every single event, for example to log them. If the question is “which people changed”, query 2 is easier to use, because it returns one row per person instead of one row per event.

Fetching the current state

Query 2 gives you the keys of the people that changed. To fetch them, use one search stream with the keys in an $in filter:

POST {base}/api/f/{folder}/searchstream2?includeChildFolders=true

Always add includeChildFolders=true here. It matches the includeSubFolders=true on the event queries. Without it, a Person in a child folder would be missing from the response, and you would wrongly think they had been deleted.

The body is a MongoDB filter, sent as a JSON string:

"{ \"_t\": \"Person\", \"_id\": { \"$in\": [ { \"$oid\": \"68a1…\" }, { \"$oid\": \"6899…\" } ] } }"

The response is one Person per line, sent as each one is read. In the wrapper, use SearchStream.Create(client, folder, query, includeChildFolders: true) and a ReadAsync loop.

If a key from query 2 did not come back from the stream, that person was either deleted or is no longer visible to you. You can check with a single search on that key:

POST {base}/api/f/{folder}/search?includeChildFolders=true
"{ \"_id\": { \"$oid\": \"6899…\" } }"

An empty result means the Person is gone or your user can no longer see them. The API cannot tell you which, because it silently leaves out anything you are not allowed to see. Either way, remove the person from your copy. If you really need to know whether it was a true deletion, look for the DELETE event in the Events collection (see Good to know). In the wrapper, SearchOneAsync<PersonInfo>(folder, query, includeChildFolders: true) returns null when nothing matches.

For a full resync, skip the event queries and stream every Person with the filter { "_t": "Person" } and includeChildFolders=true.

Good to know

  • The event type key is different in each deployment. Look it up at start-up; do not hard-code it.
  • An update that changes nothing does not write an event.
  • Metadata changes are not published by default. A Custom Form edit only creates an Object Modified event if the form’s Generic has ShouldPublishUpdateEvents: true (the UI copies this onto the Metadata entry). API writes through meta2 must pass publishUpdateEvents=true. See Custom Forms.
  • After an object is deleted, the only trace of it is its DELETE event, which keeps the last CommonName.
  • queryTimeout is in seconds, with a maximum of 600. If an event query times out, that is a sign a full resync is the better choice.

Using the event payload

So far, the examples used events only to learn which object changed, and then fetched that object again. But the event also tells you what the object looks like now. The EventData of an Object Modified event is an ObjectModEventData with these fields:

Field Meaning
Action POST (created), PUT (updated) or DELETE (deleted).
Types The object’s type names, from general to specific (for example ["BaseInfo", "Person"]).
Key, Href, CommonName Which object this is. Always present, even on DELETE.
User The user who made the change.
BeforeData The object before the change. Usually null on POST.
AfterData The object after the change, in the same shape as a GET would return. Usually null on DELETE.

AfterData is the up-to-date object. If you keep a copy of people, readers or access levels, you can write AfterData straight into it and skip the “Fetching the current state” step above. This is why the MQTT path needs no polling: every change arrives with the new object already attached.

Where the payload is, per channel

Channel Where ObjectModEventData is Notes
MQTT, GET …/events, GET …/eventsstream EventDataBsonBase64 on the event BSON, encoded as Base64. Decode the Base64, then read the BSON as ObjectModEventData.
POST …/aggregate/Events EventData subdocument A plain document. You can match and project EventData.Action, EventData.AfterData.… directly.

From the events stream

Here is one line from GET {base}/api/f/{folder}/eventsstream?forKeys={objectModTypeId}&…, shortened:

{
  "$type": "Feenics.Keep.WebApi.Model.EventMessageData, Feenics.Keep.WebApi.Model",
  "Key": "6919a2c4…",
  "EventTypeKey": "{objectModTypeId}",
  "OccurredOn": "2026-11-16T14:02:51.417Z",
  "MessageShort": "Object Modified",
  "ObjectLinks": [
    { "Relation": "Person", "LinkedObjectKey": "68a1…", "CommonName": "Jane Example" },
    { "Relation": "User",   "LinkedObjectKey": "5f0c…", "CommonName": "hr.sync" }
  ],
  "EventDataBsonBase64": "QgEAAAJBY3Rpb24ABAAAAFBVVAAEVHlwZXMA…"
}

To read it, decode EventDataBsonBase64 from Base64 into bytes, then read those bytes as a BSON document. You get the fields from the table above, with AfterData as a nested object. In the wrapper, EventsStream.Create(client, folder, …) with a ReadAsync loop gives you EventMessageData objects. The C# example below shows the decode step.

From an aggregate

aggregate/Events returns the stored document, so there is nothing to decode. Reuse the $match from query 2 and project the parts you want:

[
  {
    "$match": {
      "InstanceScopeId": { "$oid": "{instanceId}" },
      "ObjectLinks.Relation": "Person",
      "EventTypeId": { "$oid": "{objectModTypeId}" },
      "OccurredOn.Date": { "$gt": { "$date": "{lastSync}" } }
    }
  },
  { "$sort": { "OccurredOn.Date": 1 } },
  {
    "$project": {
      "_id": 0,
      "occurredOn": "$OccurredOn.Date",
      "action": "$EventData.Action",
      "key": "$EventData.Key",
      "after": "$EventData.AfterData"
    }
  }
]
[
  { "occurredOn": "2026-11-16T09:10:51Z", "action": "PUT",    "key": "6899…", "after": { "$type": "…PersonInfo…", "CommonName": "Sam Example", "Surname": "Example", "Metadata": [ … ], … } },
  { "occurredOn": "2026-11-16T14:02:51Z", "action": "DELETE", "key": "68a1…", "after": null }
]

Go through the results oldest first. For each POST or PUT, set your copy to after. For each DELETE, remove the key. The only keys that still need a search stream are the ones whose newest POST or PUT has after: null. Remember to send each stage as a JSON string, as explained in Running a query.

From MQTT

Subscribe to the instance’s Object Modified events and keep a dictionary of people up to date. Subscribing to Events covers how to connect and log in. This section covers the message handler.

Two facts shape the handler.

Events can arrive out of order, or twice. They are published by several services across the platform. Now and then a change reaches you twice, or an older change arrives after a newer one. Never assume events arrive in order, on MQTT or anywhere else.

Every object has a version number. It is called ConcurrencyVersion (a long? on BaseInfo), and the server adds one to it on every write. The server sets it on every object it returns. AfterData.ConcurrencyVersion therefore tells you where that copy sits in the object’s history, no matter when or how the event reached you. The handler compares versions to decide whether an event is new information or old news. That one rule handles duplicates, late arrivals, and mixing the live feed with a catch-up stream. If a version is ever missing, the example asks for a refresh rather than guessing.

using Feenics.Keep.WebApi.Model;
using MongoDB.Bson.Serialization;

// Current snapshot per key. A deleted person stays in the map as a tombstone
// (Person == null) so a late or duplicate PUT cannot recreate it.
private sealed record Entry(PersonInfo Person, long Version, bool Deleted);

private readonly Dictionary<string, Entry> _people = new();
private readonly object _gate = new();          // one lock around compare + write
private string _objectModTypeId;                // resolved at start-up, see "Finding the event type key"

private Task OnMessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
    var message = BsonSerializer.Deserialize<EventMessageData>(e.ApplicationMessage.PayloadSegment.ToArray());
    if (message.EventTypeKey != _objectModTypeId || string.IsNullOrEmpty(message.EventDataBsonBase64))
        return Task.CompletedTask;

    // EventDataBsonBase64 is Base64 BSON; decode it before reading the payload
    var bytes = Convert.FromBase64String(message.EventDataBsonBase64);
    var change = BsonSerializer.Deserialize<ObjectModEventData>(bytes);

    if (change.Types.Contains("Person"))
        Apply(change);
    return Task.CompletedTask;
}

private void Apply(ObjectModEventData change)
{
    lock (_gate)
    {
        _people.TryGetValue(change.Key, out var current);

        switch (change.Action)
        {
            case "POST":
            case "PUT":
                if (change.AfterData is not PersonInfo person || person.ConcurrencyVersion is not long version)
                {
                    _refreshQueue.Add(change.Key);              // rare: no snapshot or no version, resolve with a search
                    break;
                }
                if (current is { Deleted: true })
                    break;                                       // a snapshot from before the delete, or a duplicate
                if (current is not null && version <= current.Version)
                    break;                                       // older than, or the same as, what we hold
                _people[change.Key] = new Entry(person, version, Deleted: false);
                break;

            case "DELETE":
                // Keep the last known version with the tombstone; anything at or below it is pre-delete
                _people[change.Key] = new Entry(null, current?.Version ?? long.MaxValue, Deleted: true);
                break;
        }
    }
}

What each rule does for you:

  • Duplicates and late arrivals are dropped by the <= version check, no matter what order they come in.
  • A PUT that arrives after a DELETE hits the tombstone and is ignored. This holds even if the PUT has the same version the object had just before it was deleted. If a catch-up reader sees the DELETE first, it still records the tombstone and then rejects the older copies that follow.
  • More than one reader can feed the cache safely, because the compare and the write happen inside one lock. Dictionary<,> is not thread-safe, so the lock is a must as soon as you have two readers.

Because order does not matter to it, you can feed the same Apply method from the live MQTT subscription and from a catch-up source at the same time. For catch-up, replay the aggregate output above (sorted OccurredOn: 1) or read an EventsStream (newest first). Either way, Apply ends up with the latest version of every object. You can clear out tombstones after a while, once you are sure no event older than that is still on its way.

When you still need to fetch

  • AfterData is null on a POST or PUT. This is rare. Queue the key and look it up with a search.
  • You missed events, because MQTT was disconnected or there were too many to replay. Use query 3, then query 2, then the search stream. Or do a full resync.
  • You only track a few fields and do not want the whole object on every change. In that case ignore AfterData and stick to the key-based queries.