1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

DynamoDBの条件付き書き込みで作る、期限付きロックと分散レートゲート(TypeScript / AWS SDK v3)

1
Posted at

Lambda で「同じ処理を同時に2本走らせたくない」「外部 API を全体で1秒に1回までに抑えたい」とき、Redis などを足さなくても、DynamoDB の条件付き書き込み(ConditionExpression)を使って、期限付きの取得権と送信枠の予約を作れます。期限超過時の処理の重なりや、予約後の実送信の遅延は、別途考慮が必要です。

この記事では、個人開発のサービスで使っている2つの部品を、TypeScript(AWS SDK v3 の lib-dynamodb)のコードで紹介します。

  • 期限付きロック(リース):有効期間内の取得者を1つにし、期限後は再取得できる
  • 分散レートゲート:複数の Lambda をまたいで送信枠を1秒間隔で予約する。実際の送信間隔には追加の制御が必要

前提:条件付き書き込みは「失敗」が合図

UpdateCommand に ConditionExpression を付けると、条件を満たさないときは書き込まれず、ConditionalCheckFailedException が投げられます。判定と書き込みは1つの操作としてまとめて行われるので、同時に2つ来ても片方しか通りません。

この「失敗」を、「ほかの誰かが先に取った」という合図として使います。

function isConditionFailed(e: unknown): boolean {
  return typeof e === 'object' && e !== null &&
    'name' in e && e.name === 'ConditionalCheckFailedException';
}

それ以外の例外(スロットリングなど)は、握りつぶさずにそのまま投げ直します。

部品1:期限付きロック

ロックを「取った/取っていない」の真偽値で持つと、取ったまま Lambda が落ちたときに、誰も取れなくなります。そこで、いつまで有効かという時刻を持たせます。期限が切れていれば、次の人が上書きして取れます。

import { randomUUID } from 'node:crypto';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, UpdateCommand, DeleteCommand } from '@aws-sdk/lib-dynamodb';

const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE = process.env.TABLE_NAME!;

type Lease = { userId: string; ownerId: string; expiresAt: string };

export async function tryAcquireLock(userId: string, holdMs: number): Promise<Lease | null> {
  if (!Number.isSafeInteger(holdMs) || holdMs <= 0) {
    throw new RangeError("holdMs must be a positive safe integer");
  }
  const now = Date.now();
  const ownerId = randomUUID();
  const expiresAt = new Date(now + holdMs).toISOString();
  try {
    await ddb.send(
      new UpdateCommand({
        TableName: TABLE,
        Key: { PK: `USER#${userId}`, SK: 'LOCK#collect' },
        UpdateExpression: 'SET expiresAt = :exp, ownerId = :owner, #ttl = :ttl',
        // 誰も持っていないか、前の人の期限が切れていれば取れる
        ConditionExpression: 'attribute_not_exists(expiresAt) OR expiresAt < :now',
        ExpressionAttributeNames: { '#ttl': 'ttl' },
        ExpressionAttributeValues: {
          ':exp': expiresAt,
          ':owner': ownerId,
          ':now': new Date(now).toISOString(),
          // DynamoDB の TTL で、古いロックの項目も最後には消える
          ':ttl': Math.floor(now / 1000) + Math.ceil(holdMs / 1000) + 3600,
        },
      }),
    );
    return { userId, ownerId, expiresAt };
  } catch (e) {
    if (isConditionFailed(e)) return null;
    throw e;
  }
}

export async function releaseLock(lease: Lease): Promise<void> {
  try {
    await ddb.send(new DeleteCommand({
      TableName: TABLE,
      Key: { PK: `USER#${lease.userId}`, SK: 'LOCK#collect' },
      ConditionExpression: 'ownerId = :owner',
      ExpressionAttributeValues: { ':owner': lease.ownerId },
    }));
  } catch (e) {
    // 期限切れ後に別の所有者へ移った場合や、すでに解放済みなら何もしない
    if (!isConditionFailed(e)) throw e;
  }
}

取得した Lease を呼び出し側で保持し、解放時には releaseLock(lease) を呼びます。Aの期限切れ後にBが取得しても、Aの解放は所有者が一致せず、Bのロックを削除しません。

ポイントは次のとおりです。

  • 時刻は ISO 8601 の文字列で持っています。同じ形式・同じタイムゾーン(UTC)なら、文字列の大小比較がそのまま時刻の前後になります
  • ttl は予約語なので、ExpressionAttributeNames で #ttl に置き換えます
  • DynamoDB の TTL による削除はすぐには行われません。有効かどうかの判定は expiresAt で行い、TTL は掃除のためだけに使います

期限切れ後も古い処理が動く場合

所有者付きの解放が防ぐのは、古い所有者による新しいロックの削除です。処理そのものは期限切れで停止しないため、Aが動き続ける間にBが取得すると処理は重なります。実運用では最大処理時間と余裕を考えてリース期間を決め、長い処理では所有者を条件に期限を更新します。更新できなければ処理を中断します。

厳密に古い処理の副作用を防ぐには、書き込み先で単調増加するフェンシングトークンを検証するなどの仕組みも必要です。外部APIへの副作用には冪等キーなども検討します。以下の例は、この仕組みまで実装したものではありません。

「最後に成功した時刻」とロックを分ける

連続実行を間引く(デバウンスする)用途では、「前回いつ成功したか」も条件に入れたくなります。そのとき、ロックの期限と、最後に成功した時刻は別の属性にします。

ConditionExpression:
  '(attribute_not_exists(lastBuiltAt) OR lastBuiltAt < :threshold) AND ' +
  '(attribute_not_exists(buildLeaseUntil) OR buildLeaseUntil < :now)',

最初は、ロックを取った時点で lastBuiltAt を進めていました。すると、そのあと処理が失敗しても「たった今成功した」扱いになり、直後の再試行が間引かれて捨てられていました。lastBuiltAt は成功したあとにだけ進めるようにしています。

// この例は、同じ項目にbuildLeaseOwnerも保存して取得する構成の抜粋
// :owner は取得時の所有者ID、:now は更新時点のUTC時刻
ConditionExpression: 'buildLeaseOwner = :owner AND buildLeaseUntil > :now',
UpdateExpression: 'SET lastBuiltAt = :now REMOVE buildLeaseUntil, buildLeaseOwner',

部品2:分散レートゲート

外部 API に「1アプリにつき1リクエスト/秒」のような制限があるとき、プロセスの中で待ち時間を管理するだけでは足りません。Lambda が並列で動いたり、画面からの操作と定期処理が重なったりすると、同じ API に同時にリクエストが飛ぶからです。

そこで、DynamoDB の1項目に「次に予約できる時刻(nextAt)」を持たせ、それを奪い合います。

これは予約時刻を分散する仕組みです。Aが予約時刻のあとに停止し、Bの送信直前に復帰すると、実際のAPI送信は接近したり順序が逆転したりします。厳密な最小送信間隔が必要なら、単一の送信ワーカーなどで実送信を直列化し、送信時刻に基づいて間隔を制御します。この予約だけで外部APIの制限を必ず守れるとは保証しません。

import { GetCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb';

export class RateGateBusyError extends Error {
  constructor(readonly waitMs: number) {
    super(`順番待ちが ${Math.ceil(waitMs / 1000)} 秒あります`);
    this.name = 'RateGateBusyError';
  }
}

const KEY = { PK: 'RATE#external-api', SK: 'GATE#global' };
const CONTENTION_BUDGET_MS = 60_000;

/** 予約時刻(epoch ms)を返す。実送信の間隔は保証しない */
export async function reserveSlot(
  minIntervalMs: number,
  maxWaitMs = Number.POSITIVE_INFINITY,
): Promise<number> {
  const startedAt = Date.now();
  const deadline = startedAt + Math.min(maxWaitMs, CONTENTION_BUDGET_MS);

  for (;;) {
    const res = await ddb.send(new GetCommand({ TableName: TABLE, Key: KEY }));
    const current = (res.Item as { nextAt?: number } | undefined)?.nextAt ?? 0;
    const now = Date.now();
    const slot = Math.max(now, current); // 空いていれば今すぐ、詰まっていれば最後尾

    // 待ちが長すぎるなら、枠を取る前に諦める
    if (slot - now > maxWaitMs) throw new RateGateBusyError(slot - now);

    try {
      await ddb.send(
        new UpdateCommand({
          TableName: TABLE,
          Key: KEY,
          UpdateExpression: 'SET nextAt = :next, #ttl = :ttl',
          // 読んだ値から変わっていなければ書ける(楽観ロック)
          ConditionExpression: 'attribute_not_exists(nextAt) OR nextAt = :observed',
          ExpressionAttributeNames: { '#ttl': 'ttl' },
          ExpressionAttributeValues: {
            ':next': slot + minIntervalMs,
            ':observed': current,
            ':ttl': Math.floor(slot / 1000) + 3600,
          },
        }),
      );
      return slot;
    } catch (e) {
      if (!isConditionFailed(e)) throw e;
      if (Date.now() >= deadline) throw new RateGateBusyError(Date.now() - startedAt);
      // 少し散らしてから読み直す
      await new Promise((r) => setTimeout(r, 20 + Math.floor(Math.random() * 80)));
    }
  }
}

使う側はこうなります。

const slot = await reserveSlot(1000, 10_000);
const wait = slot - Date.now();
if (wait > 0) await new Promise((r) => setTimeout(r, wait));
await callExternalApi();

気をつけたこと

  • 枠を取れないまま送らない:競合に負け続けたときに「とりあえず今の時刻」を返すと、複数の呼び出しが同時に送れてしまいます。予算(60秒)を使い切ったら、送らずに失敗させます
  • 諦めるなら、枠を取る前に:枠を取ってから諦めると、使われない枠のぶん、後ろの呼び出しを無駄に待たせます
  • 画面からの操作には上限を付ける:利用者が押した検索などは、maxWaitMs を短くして「混んでいます」と返します。定期処理は上限なしで待たせます

弱点

この方法は、時計がずれていないことを前提にしています。Lambda の時計は通常は十分正確ですが、厳密な保証が必要な用途には向きません。また、競合がない場合でも呼び出しごとに読み1回・書き1回が増え、競合時は再試行でさらに増えるので、1秒に何十回も呼ぶような用途ではコストと競合が増えます。低頻度の送信予約を調整する部品、という位置づけです。外部APIが採用する固定窓・移動窓などの制限方式と、予約後の遅延も考慮してください。

まとめ

  • ConditionExpression の失敗(ConditionalCheckFailedException)を「先を越された」の合図にする
  • ロックは期限と所有者IDで持ち、解放は所有者一致を条件にする。期限切れ後の副作用には別の対策が必要
  • 「最後に成功した時刻」とロックの期限は、別の属性に分ける
  • レートゲートは「次に予約できる時刻」を楽観ロックで奪い合う。実送信の間隔は別途制御する
  • 枠を取れないまま送らない。諦めるなら枠を取る前に

この2つを入れることになった経緯(「今すぐ収集」ボタンの連打と、外部APIの1リクエスト/秒の制限)や、テストで挙動を固めた話は、ブログに書きました。

参考資料

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?