Spanner 큐는 메시지를 최소 한 번 전송하며 여러 수신자 간에 병렬 처리를 수행하도록 설계되었습니다. 동일한 항목(예: 고객 계정, 주문, 기기)에 대한 여러 메시지가 큐로 전송되면 여러 작업자가 동시에 이를 가져와 처리할 수 있습니다. 한 메시지가 먼저 전송되더라도 네트워크 지연 또는 재시도로 인해 첫 번째 작업자가 느려질 수 있으며, 두 번째 작업자는 이후 메시지를 완료합니다.
전체 큐의 모든 메시지가 엄격한 전역 순서로 처리되면 느린 작업자 하나가 전체 큐를 중단시킬 수 있습니다(head-of-line blocking 현상). 하지만 대부분의 애플리케이션은 전체 데이터베이스의 모든 메시지가 단일 전역 줄에서 대기할 필요가 없습니다. 대신 동일한 항목의 태스크만 순서대로 실행하면 되고 다른 항목의 태스크는 동시에 실행됩니다. 다음 패턴을 사용하여 워크로드에 따라 항목별로 메시지를 순서대로 처리할 수 있습니다.
순차적 워크플로를 위한 메시지 연결
항목의 백그라운드 작업이 종속된 순차적 단계(예: step-1 다음에 step-2 및 step-3)로 구성되고 외부 요청이 해당 워크플로에 경쟁 태스크를 동시에 추가하지 않는 경우 이전 단계가 완료된 후에만 각 단계를 시작해야 합니다.
단계별 순서를 적용하려면 처음에는 첫 번째 단계만 큐에 추가합니다. 작업자가 현재 단계 처리를 완료하면 현재 메시지(DELETE ...
ASSERT_ROWS_MODIFIED
1)를 확인하고 동일한 읽기-쓰기 트랜잭션에서 다음 단계의 메시지를 삽입합니다.
현재 단계가 완료되고 동일한 트랜잭션에서 확인될 때까지 다음 단계의 메시지가 생성되지 않으므로 동일한 워크플로의 두 단계가 동시에 큐에 존재하지 않으며 동시 작업자가 순서에 맞지 않게 처리할 수 없습니다.
예를 들어 작업자가 온보딩 워크플로의 step-1를 완료하고 step-2를 예약하는 경우입니다.
GoogleSQL
-- Inside the worker transaction after finishing step-1:
-- 1. Acknowledge the current step
DELETE FROM OnboardingQueue
WHERE CustomerId = 456 AND StepName = 'step-1'
ASSERT_ROWS_MODIFIED 1;
-- 2. Enqueue the next step in the sequence
INSERT INTO OnboardingQueue (CustomerId, StepName, DeliverTime, Payload)
VALUES (456, 'step-2', CURRENT_TIMESTAMP(), b'{"stage": "provision_resources"}');
PostgreSQL
-- Inside the worker transaction after finishing step-1:
-- 1. Acknowledge the current step
DELETE FROM onboardingqueue
WHERE customerid = 456 AND stepname = 'step-1'
ASSERT_ROWS_MODIFIED 1;
-- 2. Enqueue the next step in the sequence
INSERT INTO onboardingqueue (customerid, stepname, deliver_time, payload)
VALUES (456, 'step-2', CURRENT_TIMESTAMP, CAST('{"stage": "provision_resources"}' AS bytea));
정렬된 작업 테이블 및 대기열 사용
하지만 특정 항목의 모든 태스크를 커밋 순서대로 실행해야 하는 경우, 외부 요청, 웹훅 또는 사용자 작업이 새 태스크를 추가하는 동안 이전 태스크가 아직 처리 중이더라도 이 패턴은 단일 분할의 쓰기 용량에 맞는 워크로드를 지원합니다.
동시 태스크를 항목별로 순서대로 처리하려면 인터리브 처리된 테이블에 순서가 지정된 태스크를 저장하고 가벼운 절전 모드 해제 알림에만 큐를 사용하여 더티 플래그 패턴을 확장합니다.
먼저 활성 클레임을 추적하는 상위 항목 테이블에서 정렬된 작업 테이블(커밋 타임스탬프 사용)과 대기열을 인터리브 처리합니다. 분할 간에 핫스팟이 발생하지 않도록 하려면 항목을 균등하게 분산하는 기본 키(예: UUID 또는 비트 반전 시퀀스)를 선택합니다.
GoogleSQL
CREATE SEQUENCE CustomerIdSeq OPTIONS (sequence_kind = 'bit_reversed_positive');
CREATE TABLE Customers (
CustomerId INT64 NOT NULL DEFAULT (GET_NEXT_SEQUENCE_VALUE(SEQUENCE CustomerIdSeq)),
CustomerName STRING(1024),
IsProcessing BOOL NOT NULL DEFAULT (FALSE),
ActiveClaimId STRING(36),
ProcessingExpiresAt TIMESTAMP,
) PRIMARY KEY (CustomerId);
CREATE TABLE CustomerWorkItems (
CustomerId INT64 NOT NULL,
CreatedAt TIMESTAMP NOT NULL DEFAULT (PENDING_COMMIT_TIMESTAMP())
OPTIONS (allow_commit_timestamp = true),
BatchIndex INT64 NOT NULL DEFAULT (0),
WorkType STRING(128) NOT NULL,
WorkPayload JSON NOT NULL,
) PRIMARY KEY (CustomerId, CreatedAt, BatchIndex),
INTERLEAVE IN PARENT Customers ON DELETE CASCADE;
CREATE QUEUE CustomerDirtyQueue (
CustomerId INT64 NOT NULL,
MessageId STRING(36) NOT NULL,
Payload BYTES(MAX) NOT NULL,
) PRIMARY KEY (CustomerId, MessageId),
INTERLEAVE IN PARENT Customers ON DELETE CASCADE;
PostgreSQL
CREATE SEQUENCE customeridseq BIT_REVERSED_POSITIVE;
CREATE TABLE customers (
customerid bigint NOT NULL DEFAULT nextval('customeridseq'),
customername varchar(1024),
isprocessing boolean NOT NULL DEFAULT false,
activeclaimid varchar(36),
processingexpiresat timestamptz,
PRIMARY KEY (customerid)
);
CREATE TABLE customerworkitems (
customerid bigint NOT NULL,
createdat spanner.commit_timestamp NOT NULL DEFAULT spanner.pending_commit_timestamp(),
batchindex bigint NOT NULL DEFAULT 0,
worktype varchar(128) NOT NULL,
workpayload jsonb NOT NULL,
PRIMARY KEY (customerid, createdat, batchindex)
) INTERLEAVE IN PARENT customers ON DELETE CASCADE;
CREATE QUEUE customerdirtyqueue (
customerid bigint NOT NULL,
messageid varchar(36) NOT NULL,
payload bytea NOT NULL,
PRIMARY KEY (customerid, messageid)
) INTERLEAVE IN PARENT customers ON DELETE CASCADE;
이 스키마를 사용하면 발신자와 작업자가 다음 워크플로를 사용하여 조정합니다.
- 순서가 지정된 작업 및 절전 모드 해제 메시지 삽입: 발신자 트랜잭션에서 작업을
CustomerWorkItems에 삽입하고(PENDING_COMMIT_TIMESTAMP()및 0 기반BatchIndex를 사용하여 동일한 트랜잭션 내에서 여러 작업의 순서 지정) 빈 페이로드(b'')가 있는 단일 절전 모드 해제 메시지를CustomerDirtyQueue에 삽입합니다. - 다음 세 단계에 따라 항목을 소유권 주장, 처리, 취소합니다.
- 1단계(트랜잭션 1에서 항목 소유권 주장): 작업자가
RECEIVE_CustomerDirtyQueue에서 절전 모드 해제 메시지를 수신하면 짧은 읽기-쓰기 트랜잭션을 실행합니다.Customers를 확인하고 수신되는 wake-up 메시지(DELETE ... ASSERT_ROWS_MODIFIED 1)를 확인합니다. 다른 작업자가 이미 활성 클레임(IsProcessing = TRUE및ProcessingExpiresAt > CURRENT_TIMESTAMP())을 보유하고 있으면 트랜잭션 1을 커밋하고 종료합니다. 활성 작업자는 소유권을 해제하기 전에 남은 태스크를 확인합니다.- 그렇지 않으면
CreatedAt ASC, BatchIndex ASC로 정렬된CustomerWorkItems에서 가장 오래된 태스크 배치(예:LIMIT 25)를 읽고 만료된 나머지 대체 메시지(MessageId가 이전ActiveClaimId임)를 삭제합니다. - 태스크가 반환되면
Customers에서IsProcessing = TRUE,ActiveClaimId,ProcessingExpiresAt(예: 10초 후)를 설정하고ProcessingExpiresAt로 예약된CustomerDirtyQueue에 대체 메시지(MessageId = ActiveClaimId)를 삽입합니다. 남은 작업이 없으면IsProcessing = FALSE,ActiveClaimId = NULL,ProcessingExpiresAt = NULL를 재설정합니다.
- 2단계(트랜잭션 외부에서 태스크 처리): 트랜잭션 1이 커밋된 후 작업자는 애플리케이션 코드에서 태스크를 순차적으로 실행합니다. 태스크가 실패하면 작업자가 배치를 조기에 중지하고 3단계를 계속 실행하여 실패한 태스크를 다시 시도하기 전에 완료된 태스크를 삭제합니다.
- 3단계(완료된 태스크 삭제 및 트랜잭션 2에서 항목 해제): 작업자가 두 번째 짧은 읽기-쓰기 트랜잭션을 열고,
ASSERT_ROWS_MODIFIED 1를 사용하여CustomerDirtyQueue에서 대체 메시지(ActiveClaimId)를 삭제하고,CustomerWorkItems에서 완료된 태스크를 삭제하고,CustomerWorkItems에 태스크가 더 남아 있으면 새 절전 모드 해제 메시지를 삽입하고,Customers에서IsProcessing = FALSE,ActiveClaimId = NULL,ProcessingExpiresAt = NULL를 재설정합니다.
- 1단계(트랜잭션 1에서 항목 소유권 주장): 작업자가
이 패턴은 다음과 같은 이유로 엄격한 항목별 순서와 높은 처리량을 유지합니다.
- 커밋 타임스탬프 순서 지정:
(CustomerId, CreatedAt, BatchIndex)로 키가 지정된CustomerWorkItems에 태스크를 저장하면 여러 발신자가 동시에 쓰더라도 모든 태스크가 트랜잭션 커밋 타임스탬프에 따라 정렬됩니다. - 단일 분할 지역성:
Customers에서CustomerWorkItems및CustomerDirtyQueue를 인터리브하면 항목의 클레임 상태, 태스크, wakeup 메시지가 동일한 분할에 유지됩니다.CustomerDirtyQueue.Payload를 비워두면(b'') 큐 스토리지 및 인메모리 전송 오버헤드도 최소화됩니다. - 단기 데이터베이스 잠금: 2단계에서 읽기-쓰기 트랜잭션을 열어두면
Customers행이 잠기고 동시 발신자가 차단됩니다. 클레임(트랜잭션 1)과 완료(트랜잭션 2)를 두 개의 짧은 트랜잭션으로 분할하면 애플리케이션 코드가 실행되는 동안 데이터베이스 잠금을 유지하지 않고 한 번에 하나의 작업자만 항목을 처리할 수 있습니다. - 비정상 종료 복구 및 펜싱: 트랜잭션 1에서 초기 wake-up 메시지를 즉시 확인하고
ProcessingExpiresAt에 대체 메시지(ActiveClaimId)를 예약하면 고정된 10초RECEIVE메시지 임대가 구성 가능한 항목 클레임으로 대체됩니다. 2단계 중에 작업자가 비정상 종료되면 대체 메시지가 성숙하고 다른 작업자를 깨웁니다. 느린 작업자가 클레임이 만료된 후 완료되고 다른 작업자가 이미 인계한 경우 트랜잭션 2에서ASSERT_ROWS_MODIFIED 1로ActiveClaimId를 삭제하면OUT_OF_RANGE로 실패합니다. 이 오류를 전파하거나 명시적으로 롤백하면 쓰기가 커밋되기 전에 트랜잭션 2가 중단됩니다.
다음 문은 단일 발신자 트랜잭션에 순서가 지정된 작업 2개와 절전 모드 해제 메시지를 삽입합니다.
GoogleSQL
-- 1. Insert ordered tasks for the entity using a 0-based BatchIndex
INSERT INTO CustomerWorkItems (CustomerId, CreatedAt, BatchIndex, WorkType, WorkPayload)
VALUES
(456, PENDING_COMMIT_TIMESTAMP(), 0, 'ORDER_CREATED', JSON '{"order_id": 1001}'),
(456, PENDING_COMMIT_TIMESTAMP(), 1, 'PAYMENT_CAPTURED', JSON '{"order_id": 1001}');
-- 2. Send a single lightweight wake-up message to the interleaved queue
INSERT INTO CustomerDirtyQueue (CustomerId, MessageId, DeliverTime, Payload)
VALUES (456, 'msg-uuid-1', CURRENT_TIMESTAMP(), b'');
PostgreSQL
-- 1. Insert ordered tasks for the entity using a 0-based batchindex
INSERT INTO customerworkitems (customerid, createdat, batchindex, worktype, workpayload)
VALUES
(456, spanner.pending_commit_timestamp(), 0, 'ORDER_CREATED', '{"order_id": 1001}'::jsonb),
(456, spanner.pending_commit_timestamp(), 1, 'PAYMENT_CAPTURED', '{"order_id": 1001}'::jsonb);
-- 2. Send a single lightweight wake-up message to the interleaved queue
INSERT INTO customerdirtyqueue (customerid, messageid, deliver_time, payload)
VALUES (456, 'msg-uuid-1', CURRENT_TIMESTAMP, CAST('' AS bytea));
다음 SQL 문은 작업자가 절전 모드 해제 메시지를 수신하고 트랜잭션 1에서 항목을 요청하고 트랜잭션 2에서 항목을 해제하는 방법을 보여줍니다.
GoogleSQL
-- Stream wake-up messages from the queue:
SELECT CustomerId, MessageId, Payload, DeliverTime, SpannerLeaseToken
FROM RECEIVE_CustomerDirtyQueue(max_duration=>'20m', max_batch_size=>10);
-- Transaction 1 (claim the entity):
-- 1. Check whether another worker holds an active claim on the entity
SELECT
IsProcessing,
ActiveClaimId,
IFNULL(ProcessingExpiresAt > CURRENT_TIMESTAMP(), FALSE) AS HasActiveClaim
FROM Customers
WHERE CustomerId = 456;
-- Always acknowledge the incoming wake-up message in Transaction 1.
-- Let OUT_OF_RANGE propagate to roll back the transaction so duplicate workers exit.
-- If IsProcessing = TRUE and HasActiveClaim = TRUE, commit after this DELETE and exit.
DELETE FROM CustomerDirtyQueue
WHERE CustomerId = 456 AND MessageId = 'msg-uuid-1'
ASSERT_ROWS_MODIFIED 1;
-- 2. Only if no active claim exists, read the next ordered batch of work items
SELECT CreatedAt, BatchIndex, WorkType, WorkPayload
FROM CustomerWorkItems
WHERE CustomerId = 456
ORDER BY CreatedAt ASC, BatchIndex ASC
LIMIT 25;
-- 3. Always clean up any remaining expired fallback message
-- (when ActiveClaimId IS NOT NULL AND ActiveClaimId != 'msg-uuid-1'):
DELETE FROM CustomerDirtyQueue
WHERE CustomerId = 456 AND MessageId = 'expired-claim-uuid';
-- 4. If step 2 returns work items, schedule a 10-second fallback message
-- and mark the entity as busy. (If step 2 returns no rows, clear any
-- expired claim fields on Customers instead.)
INSERT INTO CustomerDirtyQueue (CustomerId, MessageId, DeliverTime, Payload)
VALUES (456, 'claim-uuid-2', TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 SECOND), b'');
UPDATE Customers
SET IsProcessing = TRUE,
ActiveClaimId = 'claim-uuid-2',
ProcessingExpiresAt = TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 SECOND)
WHERE CustomerId = 456;
-- Transaction 2 (after processing the batch in order outside a transaction):
-- 1. Verify the claim is still active by deleting the fallback message.
-- Let OUT_OF_RANGE propagate to roll back the transaction if another worker took over.
DELETE FROM CustomerDirtyQueue
WHERE CustomerId = 456 AND MessageId = 'claim-uuid-2'
ASSERT_ROWS_MODIFIED 1;
-- 2. Delete the completed work items
DELETE FROM CustomerWorkItems
WHERE CustomerId = 456
AND CreatedAt = TIMESTAMP '2026-05-01T12:00:00.123456Z'
AND BatchIndex IN (0, 1);
-- 3. Check whether any unprocessed work items remain:
SELECT 1 FROM CustomerWorkItems
WHERE CustomerId = 456
LIMIT 1;
-- Run this INSERT only if the preceding SELECT returned a row:
INSERT INTO CustomerDirtyQueue (CustomerId, MessageId, DeliverTime, Payload)
VALUES (456, 'continuation-uuid-3', CURRENT_TIMESTAMP(), b'');
-- 4. Release the entity claim
UPDATE Customers
SET IsProcessing = FALSE, ActiveClaimId = NULL, ProcessingExpiresAt = NULL
WHERE CustomerId = 456 AND ActiveClaimId = 'claim-uuid-2';
PostgreSQL
-- Stream wake-up messages from the queue:
SELECT customerid, messageid, payload, deliver_time, spanner_lease_token
FROM spanner.receive_customerdirtyqueue(
max_batch_size=>10, priority=>NULL, max_duration=>'20m');
-- Transaction 1 (claim the entity):
-- 1. Check whether another worker holds an active claim on the entity
SELECT
isprocessing,
activeclaimid,
COALESCE(processingexpiresat > CURRENT_TIMESTAMP, false) AS hasactiveclaim
FROM customers
WHERE customerid = 456;
-- Always acknowledge the incoming wake-up message in Transaction 1.
-- Let OUT_OF_RANGE propagate to roll back the transaction so duplicate workers exit.
-- If isprocessing = true and hasactiveclaim = true, commit after this DELETE and exit.
DELETE FROM customerdirtyqueue
WHERE customerid = 456 AND messageid = 'msg-uuid-1'
ASSERT_ROWS_MODIFIED 1;
-- 2. Only if no active claim exists, read the next ordered batch of work items
SELECT createdat, batchindex, worktype, workpayload
FROM customerworkitems
WHERE customerid = 456
ORDER BY createdat ASC, batchindex ASC
LIMIT 25;
-- 3. Always clean up any remaining expired fallback message
-- (when activeclaimid IS NOT NULL AND activeclaimid != 'msg-uuid-1'):
DELETE FROM customerdirtyqueue
WHERE customerid = 456 AND messageid = 'expired-claim-uuid';
-- 4. If step 2 returns work items, schedule a 10-second fallback message
-- and mark the entity as busy. (If step 2 returns no rows, clear any
-- expired claim fields on customers instead.)
INSERT INTO customerdirtyqueue (customerid, messageid, deliver_time, payload)
VALUES (456, 'claim-uuid-2', CURRENT_TIMESTAMP + INTERVAL '10 SECOND', CAST('' AS bytea));
UPDATE customers
SET isprocessing = true,
activeclaimid = 'claim-uuid-2',
processingexpiresat = CURRENT_TIMESTAMP + INTERVAL '10 SECOND'
WHERE customerid = 456;
-- Transaction 2 (after processing the batch in order outside a transaction):
-- 1. Verify the claim is still active by deleting the fallback message.
-- Let OUT_OF_RANGE propagate to roll back the transaction if another worker took over.
DELETE FROM customerdirtyqueue
WHERE customerid = 456 AND messageid = 'claim-uuid-2'
ASSERT_ROWS_MODIFIED 1;
-- 2. Delete the completed work items
DELETE FROM customerworkitems
WHERE customerid = 456
AND createdat = '2026-05-01T12:00:00.123456Z'::timestamptz
AND batchindex IN (0, 1);
-- 3. Check whether any unprocessed work items remain:
SELECT 1 FROM customerworkitems
WHERE customerid = 456
LIMIT 1;
-- Run this INSERT only if the preceding SELECT returned a row:
INSERT INTO customerdirtyqueue (customerid, messageid, deliver_time, payload)
VALUES (456, 'continuation-uuid-3', CURRENT_TIMESTAMP, CAST('' AS bytea));
-- 4. Release the entity claim
UPDATE customers
SET isprocessing = false, activeclaimid = NULL, processingexpiresat = NULL
WHERE customerid = 456 AND activeclaimid = 'claim-uuid-2';
시간적 일괄 처리를 사용하여 버스트 웨이크업 메시지 중복 삭제
항목이 몇 초 내에 업데이트를 자주 수신하는 경우 모든 트랜잭션에 별도의 절전 모드 해제 메시지를 전송하면 불필요한 큐 쓰기와 중복 절전 모드 해제 전송이 발생합니다.
쓰기 시점에 wake-up 메시지를 병합하려면 시간적 일괄 처리를 결정론적 MessageId와 결합합니다.
MessageId를 기간의 버킷 ID(예: 5초 버킷)로 설정합니다.DeliverTime를 다음 가능 시간대로 반올림하고FARM_FINGERPRINT(또는spanner.farm_fingerprint)로 계산된 항목별 오프셋을 더합니다.- GoogleSQL의
INSERT OR IGNORE또는 PostgreSQL의INSERT ... SELECT ... FROM ... WHERE NOT EXISTS를 사용하여 절전 모드 해제 메시지를 삽입합니다.
5초 기간 내에 동일한 항목에 대한 모든 트랜잭션은 동일한 MessageId 및 DeliverTime를 계산합니다. 모든 트랜잭션은 작업을 CustomerWorkItems에 삽입하지만 기간의 첫 번째 트랜잭션만 CustomerDirtyQueue에 절전 모드 해제 메시지를 작성합니다. 항목별 오프셋을 추가하면 5초 간격으로 전송 시간이 분산되므로 서로 다른 항목이 정확히 같은 초에 트리거되지 않습니다.
예를 들어 다음 발신자 트랜잭션은 wake-up 메시지를 5초 버킷으로 병합합니다.
GoogleSQL
-- 1. Insert the ordered work item
INSERT INTO CustomerWorkItems (CustomerId, CreatedAt, BatchIndex, WorkType, WorkPayload)
VALUES (456, PENDING_COMMIT_TIMESTAMP(), 0, 'METRIC_RECORDED', JSON '{"v": 42}');
-- 2. Coalesce wake-up messages into a 5-second window with a per-customer offset
INSERT OR IGNORE INTO CustomerDirtyQueue (CustomerId, MessageId, DeliverTime, Payload)
VALUES (
456,
CONCAT('bucket-', CAST(DIV(UNIX_SECONDS(CURRENT_TIMESTAMP()), 5) * 5 AS STRING)),
TIMESTAMP_SECONDS(
DIV(UNIX_SECONDS(CURRENT_TIMESTAMP()), 5) * 5 + 5
+ MOD(ABS(FARM_FINGERPRINT(CAST(456 AS STRING))), 5)
),
b''
);
PostgreSQL
-- 1. Insert the ordered work item
INSERT INTO customerworkitems (customerid, createdat, batchindex, worktype, workpayload)
VALUES (456, spanner.pending_commit_timestamp(), 0, 'METRIC_RECORDED', '{"v": 42}'::jsonb);
-- 2. Coalesce wake-up messages into a 5-second window with a per-customer offset
INSERT INTO customerdirtyqueue (customerid, messageid, deliver_time, payload)
SELECT
456,
'bucket-' || bucket.start_sec::text,
to_timestamp(
bucket.start_sec + 5
+ (abs(spanner.farm_fingerprint(456::text)) % 5)
),
CAST('' AS bytea)
FROM (
SELECT (floor(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP))::bigint / 5) * 5 AS start_sec
) AS bucket
WHERE NOT EXISTS (
SELECT 1 FROM customerdirtyqueue
WHERE customerid = 456
AND messageid = 'bucket-' || bucket.start_sec::text
);
동시 wake-up 메시지로 인한 잠금 경합 줄이기
동일한 사용 중인 항목에 대한 여러 깨우기 메시지가 동시에 성숙하면 여러 작업자가 트랜잭션 1을 동시에 시작하고 동일한 Customers 행에서 읽기-쓰기 잠금을 위해 경합할 수 있습니다.
핫 항목에 대한 잠금 경합을 줄이려면 트랜잭션 1을 시작하기 전에 잠금 없는 단일 읽기(client.Single())를 수행하여 IsProcessing = TRUE 및 ProcessingExpiresAt > CURRENT_TIMESTAMP()인지 확인합니다. 항목이 사용 중인 경우 트랜잭션 1을 실행하여 Customers를 다시 확인하고 중복 wake-up 메시지를 확인하기 전에 잠시 임의의 지연 시간(예: 10~50밀리초) 동안 절전 모드로 전환합니다.
단일 읽기는 읽기-쓰기 잠금을 획득하지 않고 항목의 클레임 상태를 확인하며, 무작위 지연은 후속 읽기-쓰기 트랜잭션을 분산시켜 작업자가 동일한 밀리초에 Customers 행에서 경합하지 않도록 합니다. 활성 작업자가 단일 읽기 직후에 완료되는 경우 새 태스크가 처리되지 않은 상태로 남아 있는 동안 절전 모드 해제 메시지가 삭제되지 않도록 절전 모드 해제 메시지를 삭제하기 전에 항상 트랜잭션 1 내에서 IsProcessing를 다시 확인합니다.
예를 들어 다음 Go 함수는 항목이 이미 사용 중일 때 무작위 지연을 적용합니다.
func maybeJitterBeforeClaim(ctx context.Context, client *spanner.Client, customerID int64) error {
iter := client.Single().Query(ctx, spanner.Statement{
SQL: `SELECT IsProcessing AND IFNULL(ProcessingExpiresAt > CURRENT_TIMESTAMP(), FALSE) AS IsBusy
FROM Customers WHERE CustomerId = @cid`,
Params: map[string]interface{}{"cid": customerID},
})
defer iter.Stop()
row, err := iter.Next()
if errors.Is(err, iterator.Done) {
return nil
}
if err != nil {
return err
}
var isBusy bool
if err := row.Columns(&isBusy); err != nil {
return err
}
if isBusy {
time.Sleep(time.Duration(10+rand.Intn(40)) * time.Millisecond)
}
return nil
}
장기 실행 배치 및 외부 호출 처리
태스크 배치를 처리하는 데 초기 10초 ProcessingExpiresAt 기간보다 오래 걸리거나 데이터베이스 트랜잭션이 중단될 때 롤백되지 않는 외부 API(예: Payment Gateway 또는 웹훅)를 호출하는 경우 중복된 외부 작업과 조기 클레임 만료를 방지해야 합니다.
외부 호출을 보호하고 느린 배치의 항목 클레임을 연장하려면 다음 안내를 따르세요.
- 외부 API에 결정론적 멱등성 키 전달:
CustomerId,CreatedAt,BatchIndex(예:456:2026-05-01T12:00:00.123456Z:0)를 결합하고 2단계에서 해당 키를 다운스트림 서비스에 전달합니다. - 주기적인 하트비트로 항목 클레임 연장: 트랜잭션 1에서 더 긴 초기
ProcessingExpiresAt및 대체DeliverTime(예: 30초 또는 60초)를 설정하거나 클레임이 만료되기 전에 백그라운드 하트비트 트랜잭션을 실행합니다(예: 10초 클레임 기간에서 3~4초마다). 각 하트비트 트랜잭션은ASSERT_ROWS_MODIFIED 1를 사용하여 현재 대체 메시지(ActiveClaimId)를 삭제하고, 새로고침된 미래DeliverTime를 사용하여 새 대체 메시지를 삽입하고,Customers에서ActiveClaimId및ProcessingExpiresAt를 업데이트합니다. 트랜잭션 2를 시작하기 전에 하트비트를 중지합니다.
2단계는 데이터베이스 트랜잭션 외부에서 실행되고 큐 전송은 최소 한 번 이상이므로 외부 API 호출 후 작업자가 비정상 종료되면 다음 작업자가 작업을 다시 시도합니다. 결정론적 멱등성 키를 전달하면 외부 서비스에서 중복 요청을 무시할 수 있습니다. 자세한 내용은 트랜잭션 아웃박스를 참조하세요.
대체 메시지를 주기적으로 교체하고 ProcessingExpiresAt를 연장하면 작업자가 정상인 동안 항목 소유권 주장이 활성 상태로 유지되지만 작업자가 비정상 종료되면 다른 작업자가 인계받을 수 있습니다.
예를 들어 다음 하트비트 트랜잭션은 활성 항목 클레임을 10초 연장합니다.
GoogleSQL
-- Run every 3 to 4 seconds on a 10-second claim window before starting Transaction 2:
DELETE FROM CustomerDirtyQueue
WHERE CustomerId = 456 AND MessageId = 'claim-uuid-2'
ASSERT_ROWS_MODIFIED 1;
INSERT INTO CustomerDirtyQueue (CustomerId, MessageId, DeliverTime, Payload)
VALUES (456, 'claim-uuid-3', TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 SECOND), b'');
UPDATE Customers
SET ActiveClaimId = 'claim-uuid-3',
ProcessingExpiresAt = TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 SECOND)
WHERE CustomerId = 456 AND ActiveClaimId = 'claim-uuid-2';
PostgreSQL
-- Run every 3 to 4 seconds on a 10-second claim window before starting Transaction 2:
DELETE FROM customerdirtyqueue
WHERE customerid = 456 AND messageid = 'claim-uuid-2'
ASSERT_ROWS_MODIFIED 1;
INSERT INTO customerdirtyqueue (customerid, messageid, deliver_time, payload)
VALUES (456, 'claim-uuid-3', CURRENT_TIMESTAMP + INTERVAL '10 SECOND', CAST('' AS bytea));
UPDATE customers
SET activeclaimid = 'claim-uuid-3',
processingexpiresat = CURRENT_TIMESTAMP + INTERVAL '10 SECOND'
WHERE customerid = 456 AND activeclaimid = 'claim-uuid-2';
샤딩 및 비활성 읽기로 대용량 항목 확장
단일 항목이 하나의 Spanner 분할에서 처리할 수 있는 것보다 많은 쓰기를 수신하는 경우, 커밋 순서대로 해당 항목의 태스크를 처리해야 하더라도 모든 태스크를 단일 Customers 분할에 쓰면 쓰기 핫스팟이 생성됩니다.
전역 순서를 유지하면서 대용량 항목의 쓰기 처리량을 확장하려면 N 샤드에 쓰기를 분산하고 비활성 읽기를 사용하여 주기적인 스위퍼 작업자와 비동기식으로 병합합니다.
- 작업 및 중복 삭제 테이블 샤딩:
PRIMARY KEY (ShardId, CustomerId)(0에서N - 1까지ShardId)를 사용하여CustomerShards상위 테이블을 만들고(ShardId, CustomerId, CreatedAt, BatchIndex)를 키로 사용하는 샤딩된 작업 테이블을 인터리브 처리합니다.ShardId를 선행 키 열로 만들면 쓰기가N분할에 분산됩니다. 재시도된 트랜잭션이 새PENDING_COMMIT_TIMESTAMP()를 수신할 때 중복된 태스크 행을 방지하려면(ShardId, CustomerId, BatchId)로 키가 지정된 일괄 중복 삭제 테이블을 TTL 정책과 인터리브 처리합니다. - 큐 쓰기 없이 각 프로듀서 배치를 하나의 샤드로 라우팅: 각 프로듀서 트랜잭션에서 고유한
BatchId(예:FARM_FINGERPRINT)의 해시에서ShardId를 계산하고 큐에 삽입하지 않고 중복 삭제 테이블과 샤딩된 작업 테이블에 모두 삽입합니다.BatchId을 해싱하면 각 프로듀서 트랜잭션이 단일 분할 내에 유지되고 쓰기당 큐 오버헤드가 제거됩니다. - 비활성 읽기 및 진행률 커서를 사용하여 순서대로 샤드 스윕: 항목당 하나의 반복 스위퍼 메시지가 포함된 인터리브 처리된 wake-up 큐가 있는 별도의
CustomerSweeperState테이블에서 활성 클레임과(LastSweptAt, LastBatchIndex, LastShardId)커서를 유지합니다. 트리거되면 작업자가 항목을 클레임하고(순서가 지정된 작업 테이블 및 절전 모드 해제 큐 사용과 동일한 클레임 및 대체 메시지 패턴 사용),CreatedAt ASC, BatchIndex ASC, ShardId ASC로 정렬된 10초 정확한 비활성 읽기를 사용하여 커서 뒤에 있는 모든N샤드를 쿼리하고, 일괄을 순서대로 처리하고, 처리된 행을 삭제하고, 커서를 진행하고, 다음 스윕을 예약하는 완료 트랜잭션을 커밋합니다. 비활성 읽기를 사용하면 분할 간에 진행 중인 프로듀서 쓰기가 차단되지 않으며, 커서는 비활성 기간 내에 처리되고 삭제된 행을 건너뜁니다.
다음 단계
- 권장사항 및 모니터링을 포함하여 Spanner 큐를 사용하는 방법 알아보기
- Spanner 큐 시나리오 및 예시 자세히 알아보기
- 정확히 한 번 처리 및 최대 한 번 확인에 대해 알아보기
- 큐에 대한 세분화된 액세스 제어로 액세스 제어를 구성합니다.