home / skills / sickn33 / antigravity-awesome-skills / azure-cosmos-java

azure-cosmos-java skill

/skills/azure-cosmos-java

This skill helps you integrate with Azure Cosmos DB Java SDK for scalable NoSQL data operations using reactive patterns.

npx playbooks add skill sickn33/antigravity-awesome-skills --skill azure-cosmos-java

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
7.3 KB
---
name: azure-cosmos-java
description: |
  Azure Cosmos DB SDK for Java. NoSQL database operations with global distribution, multi-model support, and reactive patterns.
  Triggers: "CosmosClient java", "CosmosAsyncClient", "cosmos database java", "cosmosdb java", "document database java".
package: azure-cosmos
---

# Azure Cosmos DB SDK for Java

Client library for Azure Cosmos DB NoSQL API with global distribution and reactive patterns.

## Installation

```xml
<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-cosmos</artifactId>
    <version>LATEST</version>
</dependency>
```

Or use Azure SDK BOM:

```xml
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>com.azure</groupId>
        <artifactId>azure-cosmos</artifactId>
    </dependency>
</dependencies>
```

## Environment Variables

```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_KEY=<your-primary-key>
```

## Authentication

### Key-based Authentication

```java
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosClientBuilder;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(System.getenv("COSMOS_ENDPOINT"))
    .key(System.getenv("COSMOS_KEY"))
    .buildClient();
```

### Async Client

```java
import com.azure.cosmos.CosmosAsyncClient;

CosmosAsyncClient asyncClient = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .buildAsyncClient();
```

### With Customizations

```java
import com.azure.cosmos.ConsistencyLevel;
import java.util.Arrays;

CosmosClient client = new CosmosClientBuilder()
    .endpoint(serviceEndpoint)
    .key(key)
    .directMode(directConnectionConfig, gatewayConnectionConfig)
    .consistencyLevel(ConsistencyLevel.SESSION)
    .connectionSharingAcrossClientsEnabled(true)
    .contentResponseOnWriteEnabled(true)
    .userAgentSuffix("my-application")
    .preferredRegions(Arrays.asList("West US", "East US"))
    .buildClient();
```

## Client Hierarchy

| Class | Purpose |
|-------|---------|
| `CosmosClient` / `CosmosAsyncClient` | Account-level operations |
| `CosmosDatabase` / `CosmosAsyncDatabase` | Database operations |
| `CosmosContainer` / `CosmosAsyncContainer` | Container/item operations |

## Core Workflow

### Create Database

```java
// Sync
client.createDatabaseIfNotExists("myDatabase")
    .map(response -> client.getDatabase(response.getProperties().getId()));

// Async with chaining
asyncClient.createDatabaseIfNotExists("myDatabase")
    .map(response -> asyncClient.getDatabase(response.getProperties().getId()))
    .subscribe(database -> System.out.println("Created: " + database.getId()));
```

### Create Container

```java
asyncClient.createDatabaseIfNotExists("myDatabase")
    .flatMap(dbResponse -> {
        String databaseId = dbResponse.getProperties().getId();
        return asyncClient.getDatabase(databaseId)
            .createContainerIfNotExists("myContainer", "/partitionKey")
            .map(containerResponse -> asyncClient.getDatabase(databaseId)
                .getContainer(containerResponse.getProperties().getId()));
    })
    .subscribe(container -> System.out.println("Container: " + container.getId()));
```

### CRUD Operations

```java
import com.azure.cosmos.models.PartitionKey;

CosmosAsyncContainer container = asyncClient
    .getDatabase("myDatabase")
    .getContainer("myContainer");

// Create
container.createItem(new User("1", "John Doe", "[email protected]"))
    .flatMap(response -> {
        System.out.println("Created: " + response.getItem());
        // Read
        return container.readItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()),
            User.class);
    })
    .flatMap(response -> {
        System.out.println("Read: " + response.getItem());
        // Update
        User user = response.getItem();
        user.setEmail("[email protected]");
        return container.replaceItem(
            user,
            user.getId(),
            new PartitionKey(user.getId()));
    })
    .flatMap(response -> {
        // Delete
        return container.deleteItem(
            response.getItem().getId(),
            new PartitionKey(response.getItem().getId()));
    })
    .block();
```

### Query Documents

```java
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;

CosmosContainer container = client.getDatabase("myDatabase").getContainer("myContainer");

String query = "SELECT * FROM c WHERE c.status = @status";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();

CosmosPagedIterable<User> results = container.queryItems(
    query,
    options,
    User.class
);

results.forEach(user -> System.out.println("User: " + user.getName()));
```

## Key Concepts

### Partition Keys

Choose a partition key with:
- High cardinality (many distinct values)
- Even distribution of data and requests
- Frequently used in queries

### Consistency Levels

| Level | Guarantee |
|-------|-----------|
| Strong | Linearizability |
| Bounded Staleness | Consistent prefix with bounded lag |
| Session | Consistent prefix within session |
| Consistent Prefix | Reads never see out-of-order writes |
| Eventual | No ordering guarantee |

### Request Units (RUs)

All operations consume RUs. Check response headers:

```java
CosmosItemResponse<User> response = container.createItem(user);
System.out.println("RU charge: " + response.getRequestCharge());
```

## Best Practices

1. **Reuse CosmosClient** — Create once, reuse throughout application
2. **Use async client** for high-throughput scenarios
3. **Choose partition key carefully** — Affects performance and scalability
4. **Enable content response on write** for immediate access to created items
5. **Configure preferred regions** for geo-distributed applications
6. **Handle 429 errors** with retry policies (built-in by default)
7. **Use direct mode** for lowest latency in production

## Error Handling

```java
import com.azure.cosmos.CosmosException;

try {
    container.createItem(item);
} catch (CosmosException e) {
    System.err.println("Status: " + e.getStatusCode());
    System.err.println("Message: " + e.getMessage());
    System.err.println("Request charge: " + e.getRequestCharge());
    
    if (e.getStatusCode() == 409) {
        System.err.println("Item already exists");
    } else if (e.getStatusCode() == 429) {
        System.err.println("Rate limited, retry after: " + e.getRetryAfterDuration());
    }
}
```

## Reference Links

| Resource | URL |
|----------|-----|
| Maven Package | https://central.sonatype.com/artifact/com.azure/azure-cosmos |
| API Documentation | https://azuresdkdocs.z19.web.core.windows.net/java/azure-cosmos/latest/index.html |
| Product Docs | https://learn.microsoft.com/azure/cosmos-db/ |
| Samples | https://github.com/Azure-Samples/azure-cosmos-java-sql-api-samples |
| Performance Guide | https://learn.microsoft.com/azure/cosmos-db/performance-tips-java-sdk-v4-sql |
| Troubleshooting | https://learn.microsoft.com/azure/cosmos-db/troubleshoot-java-sdk-v4-sql |

Overview

This skill provides guidance and examples for using the Azure Cosmos DB SDK for Java to perform NoSQL database operations with global distribution and reactive patterns. It covers synchronous and asynchronous clients, authentication, core workflows (create database/container, CRUD, queries), and operational best practices. The content is focused on practical code patterns, configuration, and performance considerations for production systems.

How this skill works

The SDK exposes account-level clients (CosmosClient / CosmosAsyncClient), database and container abstractions, and reactive APIs for high-throughput scenarios. You configure the client with endpoint and key, optionally tune connection modes, consistency, and preferred regions, then perform CRUD and query operations against containers. The async client returns reactive types for non-blocking chaining; the sync client provides straightforward blocking operations.

When to use it

  • Building Java microservices that need globally distributed, low-latency NoSQL storage
  • High-throughput applications where reactive, non-blocking I/O improves scalability
  • Scenarios requiring multi-region failover and configurable consistency
  • Prototyping or production services that must control RU consumption and latency
  • When you need seamless integration with Azure authentication and region preferences

Best practices

  • Create and reuse a single CosmosClient/CosmosAsyncClient instance per app to avoid connection churn
  • Prefer the async client for high-throughput workloads and non-blocking pipelines
  • Choose a high-cardinality partition key that aligns with query patterns and evenly distributes load
  • Enable direct connection mode in production for lowest latency and tune retry policies for 429 responses
  • Monitor request units (RU) and use contentResponseOnWrite when you need immediate access to written items

Example use cases

  • User profile storage for a globally distributed web application with per-user partitioning
  • Event ingestion pipeline using the async client to write and query telemetry at scale
  • Session store for distributed services requiring session affinity and fast reads
  • Catalog or product database with region-preferred reads and controlled RU budgeting
  • Background jobs that migrate or transform documents using reactive CRUD chaining

FAQ

Should I use the sync or async client?

Use the async client for high-concurrency, low-latency, non-blocking scenarios. Use the sync client for simple or blocking workflows where reactive complexity is unnecessary.

How do I handle rate limiting (429)?

Implement retry logic with exponential backoff. The SDK includes retry policies; tune them and monitor RU usage to reduce throttling.