Skip to content

[Feature Request] improve perfromance of index creation in dcumentdb-local #529

Open

Description

@xgerman

Purpose of the feature.
Speed up index creation in documentdb local

Describe the solution you'd like
Set the following parameteres on postgres startup:

<style> </style>
Change Current Proposed Impact
indexBuildScheduleInSec 2 1 Halves worst-case wait (~50% faster)
indexBuildWaitSleepTimeInMilliSec 1000 100 Faster poll detection

Describe alternatives you've considered
More advanced solutions like background worker, etc.

Additional context

#!/usr/bin/env python3
"""
DocumentDB createIndex Performance Profiler

Demonstrates the async index creation bottleneck in DocumentDB
compared to MongoDB. Each createIndex takes ~2s due to pg_cron (2s cycle)
+ gateway polling (1s), regardless of collection size.

Usage:
    # Start documentdb-local:
    #   docker run -d -p 10260:10260 ghcr.io/documentdb/documentdb/documentdb-local:latest \
    #     --username benchuser --password benchpass123 --skip-init-data

    # Against documentdb-local (default, TLS required)
    python3 profile_index_creation.py

    # Against Azure DocumentDB vCore (resolve SRV first: dig SRV _mongodb._tcp.<cluster>.mongocluster.cosmos.azure.com)
    python3 profile_index_creation.py "mongodb://user:pass@<host>:10260/bench?tls=true&authMechanism=SCRAM-SHA-256&directConnection=true"

    # Against MongoDB
    python3 profile_index_creation.py mongodb://localhost:27017/bench
"""

import sys
import time
import statistics
from pymongo import MongoClient

ITERATIONS = 10
COLLECTIONS = 20  # simulate NStore creating many collections


def time_op(label, fn, iterations=ITERATIONS):
    times = []
    for i in range(iterations):
        start = time.perf_counter()
        fn(i)
        elapsed = (time.perf_counter() - start) * 1000
        times.append(elapsed)
    avg = statistics.mean(times)
    p50 = statistics.median(times)
    mn, mx = min(times), max(times)
    print(f"  {label:<40s}  avg={avg:7.0f}ms  p50={p50:7.0f}ms  min={mn:7.0f}ms  max={mx:7.0f}ms  (n={iterations})")
    return avg


def main():
    uri = sys.argv[1] if len(sys.argv) > 1 else "mongodb://benchuser:benchpass123@localhost:10260/bench?tls=true&tlsAllowInvalidCertificates=true&directConnection=true&authMechanism=SCRAM-SHA-256"
    client = MongoClient(uri, serverSelectionTimeoutMS=10000)
    db = client.get_default_database()

    # Warm up
    db.command("ping")
    print(f"Connected to: {uri.split('@')[-1] if '@' in uri else uri}")
    print(f"Database: {db.name}")
    print(f"=" * 90)

    # --- Individual operation profiling ---
    print(f"\n1. Per-Operation Profiling ({ITERATIONS} iterations each)\n")

    # Prepare collections for drop test
    for i in range(ITERATIONS):
        db[f"prof_drop_{i}"].insert_one({"x": 1})
    time_op("drop()", lambda i: db.drop_collection(f"prof_drop_{i}"))

    time_op("createCollection()", lambda i: db.create_collection(f"prof_create_{i}"))
    for i in range(ITERATIONS):
        db.drop_collection(f"prof_create_{i}")

    # createIndex — THE BOTTLENECK
    for i in range(ITERATIONS):
        db.create_collection(f"prof_idx_{i}")
    time_op("createIndex(unique compound)",
            lambda i: db[f"prof_idx_{i}"].create_index(
                [("PartitionId", 1), ("Index", 1)], unique=True))
    for i in range(ITERATIONS):
        db.drop_collection(f"prof_idx_{i}")

    # Insert/Find on an indexed collection
    db.drop_collection("prof_crud")
    col = db.create_collection("prof_crud")
    col.create_index([("PartitionId", 1), ("Index", 1)], unique=True)
    time.sleep(3)
    time_op("insertOne()",
            lambda i: col.insert_one({"PartitionId": f"s_{i}", "Index": 1, "data": f"payload_{i}"}))
    time_op("findOne()",
            lambda i: col.find_one({"PartitionId": f"s_{i}", "Index": 1}))
    db.drop_collection("prof_crud")

    # --- NStore-style workload: many collections with indexes ---
    print(f"\n{'=' * 90}")
    print(f"\n2. NStore-Style Workload: {COLLECTIONS} collections, each with a unique compound index\n")

    start = time.perf_counter()
    for i in range(COLLECTIONS):
        name = f"nstore_stream_{i}"
        db.drop_collection(name)
        db.create_collection(name)
        db[name].create_index([("PartitionId", 1), ("Index", 1)],
                              unique=True, name="partition_index")
        db[name].insert_one({"PartitionId": "s1", "Index": 1, "Payload": {"i": i}})
        db[name].find_one({"PartitionId": "s1"})
    total = (time.perf_counter() - start) * 1000

    print(f"  Total time for {COLLECTIONS} collections:  {total:,.0f}ms ({total/1000:.1f}s)")
    print(f"  Avg per collection:                   {total/COLLECTIONS:,.0f}ms")
    print(f"  Projected for 158 collections (NStore): {total/COLLECTIONS*158/1000:.0f}s")

    # Cleanup
    for i in range(COLLECTIONS):
        db.drop_collection(f"nstore_stream_{i}")

    print(f"\n{'=' * 90}")
    print(f"\n  If createIndex takes ~2,000ms → 158 collections × 2s = ~316s overhead")
    print(f"  MongoDB createIndex takes ~5ms → 158 × 5ms = <1s overhead")
    print(f"  Root cause: async index build via pg_cron (2s cycle) + gateway poll (1s)\n")

    client.close()


if __name__ == "__main__":
    main()

Activity

  1. added
    enhancement
    on Mar 18, 2026
  2. added
    documentdb-local
    on Mar 18, 2026
  3. added this to the 0.111-0 milestone on Mar 18, 2026
  4. added 2 commits that reference this issue on Mar 23, 2026
    bb461e0
    d1fd7b5
  5. moved this from Todo to In Progress in Issue triageon Apr 29, 2026
  6. documentdb-triage-tool commented on May 30, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 72 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  7. documentdb-triage-tool commented on Jun 13, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  8. documentdb-triage-tool commented on Jun 28, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  9. documentdb-triage-tool commented on Jul 13, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 15 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  10. documentdb-triage-tool commented on Jul 28, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  11. documentdb-triage-tool commented on Aug 15, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  12. documentdb-triage-tool commented on Aug 29, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  13. documentdb-triage-tool commented on Sep 13, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  14. documentdb-triage-tool commented on Sep 27, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  15. guanzhousongmicrosoft commented on Oct 5, 2026

    @guanzhousongmicrosoft
    Member

    Not started. #539 changed the global defaults and was closed. New plan: set documentdb.indexBuildScheduleInSec=1 only in the config that documentdb-local manages, and a shorter index-build poll interval only in the image's gateway config, so packaged and server defaults stay the same. Moving to Backlog.

  16. documentdb-triage-tool commented on Oct 28, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 23 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  17. documentdb-triage-tool commented on Nov 11, 2026

    @documentdb-triage-tool

    👋 @Ritvik-Jayaswal, @guanzhousongmicrosoft — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

documentdb-localenhancement

Type

No type

Projects

Relationships

None yet

Development

No branches or pull requests

Issue actions