Azure Cosmos DB의 일관성 수준 관리

적용 대상: NoSQL

이 문서에서는 Azure Cosmos DB에서 일관성 수준을 관리하는 방법에 대해 설명합니다. 기본 일관성 수준을 구성하고, 기본 일관성을 재정의하며, 세션 토큰을 수동으로 관리하고, PBS(확률적 제한된 부실) 메트릭을 이해하는 방법을 알아봅니다.

계정 수준 일관성을 변경할 때 애플리케이션을 다시 배포하고 이러한 변경 내용을 적용하는 데 필요한 코드를 수정해야 합니다.

참고 항목

Azure Az PowerShell 모듈을 사용하여 Azure와 상호 작용하는 것이 좋습니다. 시작하려면 Azure PowerShell 설치를 참조하세요. Az PowerShell 모듈로 마이그레이션하는 방법에 대한 자세한 내용은 Azure PowerShell을 AzureRM에서 Azure로 마이그레이션을 참조하세요.

기본 일관성 수준 구성

기본 일관성 수준은 클라이언트에서 기본적으로 사용하는 일관성 수준입니다.

기본 일관성 수준을 보거나 수정하려면 Azure Portal에 로그인합니다. Azure Cosmos DB 계정을 찾아서 기본 일관성 창을 엽니다. 새 기본값으로 사용하려는 일관성 수준을 선택한 다음, 저장을 선택합니다. 또한 Azure Portal은 음악 메모와 함께 다양한 일관성 수준의 시각화를 제공합니다.

Azure Portal의 일관성 메뉴

기본 일관성 수준 재정의

클라이언트는 서비스에서 설정한 기본 일관성 수준을 재정의할 수 있습니다. 일관성 수준은 요청별로 설정할 수 있으며, 이는 계정 수준에서 설정된 기본 일관성 수준을 재정의합니다.

일관성은 SDK 인스턴스 또는 요청 수준에서만 완화될 수 있습니다. 약한 일관성에서 강력한 일관성으로 이동하려면 Azure Cosmos DB 계정에 대한 기본 일관성을 업데이트합니다.

기본 일관성 수준 재정의는 SDK 클라이언트 내의 읽기에만 적용됩니다. 기본적으로 강력한 일관성으로 구성된 계정은 계정의 모든 지역에 동기적으로 데이터를 쓰고 복제합니다. SDK 클라이언트 인스턴스 또는 요청이 이를 Session 또는 약한 일관성으로 재정의하면 단일 복제본을 사용하여 읽기가 수행됩니다. 자세한 내용은 일관성 수준 및 처리량을 참조하세요.

.NET SDK

// Override consistency at the client level
documentClient = new DocumentClient(new Uri(endpoint), authKey, connectionPolicy, ConsistencyLevel.Eventual);

// Override consistency at the request level via request options
RequestOptions requestOptions = new RequestOptions { ConsistencyLevel = ConsistencyLevel.Eventual };

var response = await client.ReadDocumentAsync(collectionUri, document, requestOptions);

Java V4 SDK

Java SDK V4(Maven com.azure::azure-cosmos) Async API


CosmosAsyncClient client =
        new CosmosClientBuilder()
                .endpoint(HOST)
                .key(MASTER_KEY)
                .consistencyLevel(ConsistencyLevel.EVENTUAL)
                .buildAsyncClient();

Java V2 SDK

Async Java V2 SDK(Maven com.microsoft.azure::azure-cosmosdb)

// Override consistency at the client level
ConnectionPolicy policy = new ConnectionPolicy();

AsyncDocumentClient client =
        new AsyncDocumentClient.Builder()
                .withMasterKey(this.accountKey)
                .withServiceEndpoint(this.accountEndpoint)
                .withConsistencyLevel(ConsistencyLevel.Eventual)
                .withConnectionPolicy(policy).build();

Node.js/JavaScript/TypeScript SDK

// Override consistency at the client level
const client = new CosmosClient({
  /* other config... */
  consistencyLevel: ConsistencyLevel.Eventual
});

// Override consistency at the request level via request options
const { body } = await item.read({ consistencyLevel: ConsistencyLevel.Eventual });

Python SDK

# Override consistency at the client level
connection_policy = documents.ConnectionPolicy()
client = cosmos_client.CosmosClient(self.account_endpoint, {
                                    'masterKey': self.account_key}, connection_policy, documents.ConsistencyLevel.Eventual)

세션 토큰 사용

Azure Cosmos DB의 일관성 수준 중 하나는 세션 일관성입니다. 기본적으로 Azure Cosmos DB 계정에 적용되는 기본 수준입니다. 세션 일관성으로 작업할 때 Azure Cosmos DB에 대한 각각의 새 쓰기 요청에는 새 SessionToken이 할당됩니다. CosmosClient는 각 읽기/쿼리 요청과 함께 내부적으로 이 토큰을 사용하여 설정된 일관성 수준이 유지되도록 합니다.

일부 시나리오에서는 이 세션을 직접 관리해야 합니다. 여러 노드가 있는 웹 애플리케이션을 고려하면 각 노드에는 고유한 CosmosClient 인스턴스가 있습니다. 이러한 노드가 웹 계층에서 일관되게 고유의 쓰기를 읽을 수 있도록 동일한 세션에 참여하려고 하는 경우 쿠키 또는 기타 메커니즘을 사용하여 쓰기 작업의 FeedResponse<T>에서 SessionToken을 최종 사용자에게 보내고 해당 토큰이 웹 계층으로, 궁극적으로 후속 읽기를 위해 CosmosClient로 다시 흐르도록 해야 합니다. Azure Load Balancer와 같이 요청 간에 세션 선호도를 유지하지 않는 라운드 로빈 Load Balancer를 사용하는 경우 읽기는 세션이 만들어진 쓰기 요청에 대해 잠재적으로 다른 노드에 도달할 수 있습니다.

위에서 설명한 대로 Azure Cosmos DB SessionToken을 전달하지 않으면 잠시 동안 읽기 결과가 일관되지 않을 수 있습니다.

Azure Cosmos DB의 세션 토큰은 파티션에 바인딩되어 있으므로 하나의 파티션과만 연결됩니다. 쓰기를 읽을 수 있도록 관련 항목에 대해 마지막으로 생성된 세션 토큰을 사용합니다. 세션 토큰을 수동으로 관리하려면 응답에서 세션 토큰을 가져와서 요청별로 설정합니다. 세션 토큰을 수동으로 관리할 필요가 없으면 다음 샘플을 사용할 필요가 없습니다. SDK는 세션 토큰을 자동으로 추적합니다. 세션 토큰을 수동으로 설정하지 않으면 기본적으로 SDK에서 최신 세션 토큰을 사용합니다.

.NET SDK

var response = await client.ReadDocumentAsync(
                UriFactory.CreateDocumentUri(databaseName, collectionName, "SalesOrder1"));
string sessionToken = response.SessionToken;

RequestOptions options = new RequestOptions();
options.SessionToken = sessionToken;
var response = await client.ReadDocumentAsync(
                UriFactory.CreateDocumentUri(databaseName, collectionName, "SalesOrder1"), options);

Java V4 SDK

Java SDK V4(Maven com.azure::azure-cosmos) Async API


// Get session token from response
CosmosItemResponse<JsonNode> response = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();
String sessionToken = response.getSessionToken();

// Resume the session by setting the session token on the RequestOptions
CosmosItemRequestOptions options = new CosmosItemRequestOptions();
options.setSessionToken(sessionToken);
CosmosItemResponse<JsonNode> response2 = container.readItem(itemId, new PartitionKey(partitionKey), JsonNode.class).block();

Java V2 SDK

Async Java V2 SDK(Maven com.microsoft.azure::azure-cosmosdb)

// Get session token from response
RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(document.get("mypk")));
Observable<ResourceResponse<Document>> readObservable = client.readDocument(document.getSelfLink(), options);
readObservable.single()           // we know there will be one response
  .subscribe(
      documentResourceResponse -> {
          System.out.println(documentResourceResponse.getSessionToken());
      },
      error -> {
          System.err.println("an error happened: " + error.getMessage());
      });

// Resume the session by setting the session token on RequestOptions
RequestOptions options = new RequestOptions();
requestOptions.setSessionToken(sessionToken);
Observable<ResourceResponse<Document>> readObservable = client.readDocument(document.getSelfLink(), options);

Node.js/JavaScript/TypeScript SDK

// Get session token from response
const { headers, item } = await container.items.create({ id: "meaningful-id" });
const sessionToken = headers["x-ms-session-token"];

// Immediately or later, you can use that sessionToken from the header to resume that session.
const { body } = await item.read({ sessionToken });

Python SDK

// Get the session token from the last response headers
item = client.ReadItem(item_link)
session_token = client.last_response_headers["x-ms-session-token"]

// Resume the session by setting the session token on the options for the request
options = {
    "sessionToken": session_token
}
item = client.ReadItem(doc_link, options)

PBS(확률적 제한된 부실) 메트릭 모니터링

최종 일관성은 어떻게 최종인가요? 일반적인 경우 버전 기록 및 시간과 관련하여 부실 범위를 제공할 수 있습니다. PBS(확률적 제한된 부실) 메트릭은 부실의 확률을 수량화하여 메트릭으로 표시하려고 시도합니다.

PBS 메트릭을 보려면 Azure Portal에서 Cosmos DB 계정으로 이동합니다. 메트릭(클래식) 창을 열고 일관성 탭을 선택하고 워크로드를 기반으로 하는 일관된 읽기가 발생할 가능성(PBS 참조)이라는 그래프를 살펴봅니다.

Azure Portal의 PBS 그래프

다음 단계

데이터 충돌을 관리하는 방법을 자세히 알아보거나 Azure Cosmos DB의 다음 핵심 개념으로 이동합니다. 다음 문서를 참조하세요.