Best practices for Azure Cosmos DB Go SDK v1

This guide covers best practices for applications that use the stable v1 releases of the Azure Cosmos DB Go SDK, github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos. Use these recommendations to reduce latency, improve availability, and control request unit (RU) consumption.

Account configuration

Configure your account and application together so the SDK can use nearby, available regions.

  • Run your application in an Azure region that hosts a replica of your account to reduce network latency.
  • For workloads that require regional resilience, configure multiple regions and service-managed failover. A preferred regions list in the client doesn't add account regions or enable write failover.
  • Set ClientOptions.PreferredRegions to your account's regions in preference order. For single-write-region accounts, writes still go to the current write region. Test failover with your account's topology and consistency level.

SDK usage

Reuse clients, configure operation deadlines, and handle failures to keep your application responsive.

  • Use the latest stable v1 release, and review the Go SDK release notes before upgrading. Check the Go version required by that release's go.mod file. Commit go.mod and go.sum so builds use reviewed dependencies.
  • Create one long-lived azcosmos.Client per account and reuse it across requests and goroutines. Reuse DatabaseClient and ContainerClient instances, too. Don't construct a client per operation.
  • Obtain database and container clients from configured names with NewDatabase or NewContainer. These methods construct local clients; they don't verify that resources exist. Keep resource creation and explicit metadata reads out of your item request path.

Apply operation deadlines

Pass the caller's context.Context through your data access layer. Use context.WithTimeout when you need a tighter operation budget, and call the returned cancel function. An operation deadline includes retries and retry delays; an HTTP transport timeout isn't an end-to-end operation deadline.

The following read-only example creates one client, reads an existing item with a deadline, and records diagnostics for failures or slow reads. In a server application, create the client at startup and reuse it in request handlers.

Before you run the example:

  1. Follow the Go quickstart to set up an account, database, container, and sample data.

  2. Give your identity a data plane role that permits reading the item. For local development, sign in with az login.

  3. In a Go module, install the dependencies:

    go get github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos@latest
    go get github.com/Azure/azure-sdk-for-go/sdk/azidentity@latest
    
  4. Set AZURE_COSMOS_ENDPOINT, AZURE_COSMOS_DATABASE, and AZURE_COSMOS_CONTAINER to your resource values. Set AZURE_COSMOS_ITEM_ID to an existing item's id and AZURE_COSMOS_PARTITION_KEY to its string partition key value. The example assumes a single-level string partition key.

  5. Save the following code as main.go, and run go run ..

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos"
)

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}

func run() error {
	for _, name := range []string{
		"AZURE_COSMOS_ENDPOINT", "AZURE_COSMOS_DATABASE",
		"AZURE_COSMOS_CONTAINER", "AZURE_COSMOS_ITEM_ID",
		"AZURE_COSMOS_PARTITION_KEY",
	} {
		if os.Getenv(name) == "" {
			return fmt.Errorf("%s must be set", name)
		}
	}

	credential, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		return fmt.Errorf("create credential: %w", err)
	}
	client, err := azcosmos.NewClient(
		os.Getenv("AZURE_COSMOS_ENDPOINT"), credential, nil)
	if err != nil {
		return fmt.Errorf("create client: %w", err)
	}
	defer client.Close()

	container, err := client.NewContainer(
		os.Getenv("AZURE_COSMOS_DATABASE"),
		os.Getenv("AZURE_COSMOS_CONTAINER"))
	if err != nil {
		return fmt.Errorf("create container client: %w", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	pk := azcosmos.NewPartitionKeyString(os.Getenv("AZURE_COSMOS_PARTITION_KEY"))
	response, err := container.ReadItem(
		ctx, pk, os.Getenv("AZURE_COSMOS_ITEM_ID"), nil)
	if err != nil {
		if diagnostics, ok := azcosmos.DiagnosticsFromError(err); ok {
			log.Printf("read diagnostics: %s", diagnostics.String())
		}
		var responseError *azcore.ResponseError
		if errors.As(err, &responseError) {
			log.Printf("read status: %d", responseError.StatusCode)
		}
		return fmt.Errorf("read item: %w", err)
	}

	log.Printf("read activity=%s charge=%.2f RU elapsed=%s",
		response.ActivityID, response.RequestCharge,
		response.Diagnostics.ClientElapsedTime())
	if response.Diagnostics.ClientElapsedTime() > time.Second {
		log.Printf("slow read diagnostics: %s", response.Diagnostics.String())
	}
	return nil
}

The 10-second deadline and one-second diagnostic threshold are examples, not service recommendations. Choose values based on your latency objectives and measured failover behavior. Close the client only after all application operations finish.

Handle retries and write outcomes

Let the SDK handle supported transient failures before adding application retries.

  • The SDK retries throttled requests (HTTP 429) and honors the service's retry-after delay. Review ClientOptions.Retry, including MaxRetries, RetryDelay, and MaxRetryDelay, against your operation deadline. These settings control the Azure SDK pipeline retry policy, not every internal regional retry.
  • Don't add tight retry loops around SDK calls. If throttling persists, investigate RU usage and hot partitions and reduce request concurrency or adjust throughput.
  • Don't assume every failed write is safe to repeat. A timeout or interrupted connection can leave the outcome unknown even if the service committed the write. Use deterministic item IDs, reconcile the stored state, and design for idempotency before replaying a write. Repeating an increment patch can apply the increment twice.
  • Use errors.As to inspect *azcore.ResponseError, and errors.Is for context cancellation or deadline errors. Handle conflicts and precondition failures according to your application's semantics instead of retrying every error.
  • For read-modify-write updates, pass the response's ETag through ItemOptions.IfMatchEtag to detect concurrent changes. On a precondition failure, read the current item and reevaluate the update.

For general retry and idempotency guidance, see Design resilient applications.

Data design

Design items and partition keys around the operations your application performs.

  • Choose a partition key that distributes storage and RU consumption while supporting common queries. A high number of distinct values alone doesn't prevent a frequently accessed value from becoming a hot partition.
  • Pass the item's actual partition key value, with the correct JSON type, to item operations. Use NewPartitionKeyString, NewPartitionKeyNumber, or the appropriate partition key builder. For hierarchical keys, supply all components in the defined order for point operations.
  • Use ReadItem when you know both the item ID and partition key value instead of running a query to find one item.
  • Keep items small, serialize only the properties you need, and handle JSON serialization errors. Exclude unused paths from the indexing policy to reduce write overhead, while retaining indexes required by your queries.
  • Leave ClientOptions.EnableContentResponseOnWrite disabled when you don't need the written item returned. It's disabled by default. Request charge and other response headers remain available without the item body.

Queries and pagination

Scope queries to a logical partition when possible, and process results one page at a time.

  • Use ContainerClient.NewQueryItemsPager with an explicit partition key for partition-scoped queries. Use QueryOptions.QueryParameters for input values instead of concatenating them into query text.
  • Call NextPage(ctx) while pager.More() is true. An empty page doesn't mean the query is complete. Handle each page's error before processing its items.
  • Tune QueryOptions.PageSizeHint with representative item sizes. It's an upper bound, not a guaranteed result count. Larger pages can reduce round trips but increase memory use and per-page latency.
  • To resume a query later, save QueryItemsResponse.ContinuationToken and pass it through QueryOptions.ContinuationToken with the same query, parameters, and partition scope. Treat tokens as opaque values, and prefer them to deep OFFSET LIMIT pagination.

Important

For cross-partition queries, review the Gateway query limitations.

Diagnostics and monitoring

Measure client-side latency and RU consumption before changing connection or concurrency settings.

  • Record operation type, elapsed time, ActivityID, and RequestCharge. Sum the request charges across query pages to measure the query's total cost.
  • Capture response.Diagnostics.String() for slow operations and use azcosmos.DiagnosticsFromError for failures, as shown in the example. If your installed SDK doesn't expose these APIs, review the Go SDK release notes and upgrade to the latest stable v1 release.
  • Use AZURE_SDK_GO_LOGGING=all or an azcore/log listener to capture Azure SDK logs during troubleshooting. Keep request and response body logging disabled unless necessary, restrict access to diagnostic output, and don't log credentials or item payloads.
  • Inspect QueryItemsResponse.QueryMetrics to investigate query execution. Enable QueryOptions.PopulateIndexMetrics temporarily when you need index utilization details; collecting index metrics adds overhead.
  • Correlate client observations with normalized RU consumption, throttling, and server-side latency. Distinguish client resource pressure and network delays from service execution time.

Host characteristics and connections

Size the application host and bound its work based on load tests.

  • The Go v1 SDK uses Gateway mode over HTTPS.
  • Reuse the SDK's default HTTP transport unless measurements show a reason to customize it. If you supply an http.Client through ClientOptions.Transport, reuse it and its http.Transport across requests. Preserve proxy, TLS verification, connection timeout, and HTTP/2 behavior appropriate to your environment.
  • Distinguish http.Transport.MaxIdleConnsPerHost, which controls retained idle connections, from MaxConnsPerHost, which limits connections per host. Don't treat either as an application request concurrency limit, especially with HTTP/2 multiplexing. Load-test custom settings and check connection wait time, socket usage, and tail latency.
  • Use a bounded worker pool or semaphore for concurrent requests. Don't launch one goroutine per item in an unbounded input. Increase concurrency gradually while observing RU consumption, 429 responses, CPU, memory, garbage collection, and network usage.
  • Enable Accelerated Networking on supported Azure virtual machines when network overhead is a bottleneck. Scale the host or distribute work when client resources limit throughput.