Back to Blog
2 min read

Azure Cosmos DB Change Feed Patterns

Cosmos DB Change Feed turns your database into an event stream. Every insert or update becomes an event you can process.

Common Patterns

1. Real-Time Materialized Views

[FunctionName("UpdateMaterializedView")]
public static async Task Run(
    [CosmosDBTrigger(
        databaseName: "orders",
        collectionName: "order-items",
        ConnectionStringSetting = "CosmosConnection",
        LeaseCollectionName = "leases")] IReadOnlyList<Document> documents,
    [CosmosDB(
        databaseName: "orders",
        collectionName: "order-summaries",
        ConnectionStringSetting = "CosmosConnection")] IAsyncCollector<OrderSummary> summaries)
{
    foreach (var doc in documents)
    {
        var item = JsonConvert.DeserializeObject<OrderItem>(doc.ToString());
        var summary = await CalculateSummary(item.OrderId);
        await summaries.AddAsync(summary);
    }
}

2. Cross-Region Replication Logic

// Replicate to secondary region with transformation
[FunctionName("ReplicateToSecondary")]
public static async Task ReplicateToSecondary(
    [CosmosDBTrigger(...)] IReadOnlyList<Document> documents,
    [CosmosDB(
        databaseName: "orders-secondary",
        collectionName: "orders",
        ConnectionStringSetting = "CosmosSecondary")] IAsyncCollector<Order> output)
{
    foreach (var doc in documents)
    {
        var order = JsonConvert.DeserializeObject<Order>(doc.ToString());
        order.Region = "secondary";  // Mark as replicated
        await output.AddAsync(order);
    }
}

3. Event Sourcing Integration

Push changes to Event Hubs for downstream processing:

[FunctionName("PublishToEventHub")]
public static async Task PublishToEventHub(
    [CosmosDBTrigger(...)] IReadOnlyList<Document> documents,
    [EventHub("order-events", Connection = "EventHubConnection")] IAsyncCollector<string> eventHub)
{
    foreach (var doc in documents)
    {
        await eventHub.AddAsync(doc.ToString());
    }
}

Key Considerations

  • Change Feed doesn’t capture deletes (use soft deletes or TTL)
  • Ordering is guaranteed within a partition, not globally
  • Use lease collection to track progress and enable scaling

Change Feed transforms Cosmos DB from a database into a real-time event platform.

Michael John Peña

Michael John Peña

Senior Data Engineer based in Sydney. Writing about data, cloud, and technology.