> ## Documentation Index
> Fetch the complete documentation index at: https://docs.devin.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 3つの競合戦略でチェックアウトのレイテンシを解消する

export const UseCaseHero = ({title, description, prompt, category, features, devinUrl, agent, intent, playbookId, type}) => {
  const encodedPrompt = encodeURIComponent(prompt || '');
  const tag = 'docs-use-case-gallery';
  const utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=hero-cta';
  const agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  const devinHref = type === 'schedule' ? 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + (prompt ? '&prompt=' + encodedPrompt : '') : type === 'review' ? 'https://app.devin.ai/review?' + utm : agent === 'ada' ? 'https://app.devin.ai/search?' + utm + '&noSubmit=true' + (prompt ? '&prompt=' + encodedPrompt : '') : devinUrl ? devinUrl.includes('?') ? devinUrl + '&' + utm + agentParams : devinUrl + '?' + utm + agentParams : prompt ? 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encodedPrompt : 'https://app.devin.ai/?' + utm + agentParams;
  const buttonLabel = type === 'schedule' ? 'Schedule in Devin ↗' : type === 'review' ? 'Set Up Devin Review ↗' : agent === 'advanced' ? 'Try in Devin ↗' : agent === 'dana' ? 'Try in Dana ↗' : agent === 'ada' ? 'Try in Ask Devin ↗' : 'Try in Devin ↗';
  const featureList = features ? features.split(',').map(f => f.trim()) : [];
  return <div className="uc-hero">
      <div className="uc-hero-inner">
        <div className="uc-hero-left">
          <h1 className="uc-hero-title">{title}</h1>
          <p className="uc-hero-desc">{description}</p>
          <div>
            <a href={devinHref} target="_blank" rel="noopener noreferrer" className="try-in-devin-btn">
              {buttonLabel}
            </a>
          </div>
        </div>
        <div className="uc-hero-meta">
          <div className="uc-meta-item">
            <span className="uc-meta-label">Author</span>
            <span className="uc-meta-value">Cognition</span>
          </div>
          <div className="uc-meta-item">
            <span className="uc-meta-label">Category</span>
            <span className="uc-meta-value">{category}</span>
          </div>
          {featureList.length > 0 && <div className="uc-meta-item">
              <span className="uc-meta-label">Features</span>
              <span className="uc-meta-value">{featureList.join(', ')}</span>
            </div>}
        </div>
      </div>
    </div>;
};

export const PromptBlock = ({children, type, agent, intent, playbookId}) => {
  var utm = 'utm_source=docs&utm_medium=use-case-gallery&utm_campaign=prompt-block';
  var tag = 'docs-use-case-gallery';
  var agentParams = (agent ? '&agent=' + agent : '') + (intent ? '&intent=' + intent : '') + (playbookId ? '&playbookId=' + playbookId : '');
  var label = type === 'schedule' ? 'Schedule in Devin' : type === 'playbook' ? 'Create Playbook' : type === 'knowledge' ? 'Add to Knowledge' : agent === 'advanced' ? 'Try in Devin' : agent === 'dana' ? 'Try in Dana' : agent === 'ada' ? 'Try in Ask Devin' : 'Try in Devin';
  var buildUrl = function (text) {
    var encoded = encodeURIComponent(text);
    if (type === 'schedule') return 'https://app.devin.ai/settings/schedules/create?' + utm + agentParams + '&prompt=' + encoded;
    if (type === 'playbook') return 'https://app.devin.ai/settings/playbooks/create?' + utm + '&body=' + encoded;
    if (type === 'knowledge') return 'https://app.devin.ai/knowledge?' + utm + '&body=' + encoded;
    if (agent === 'ada') return 'https://app.devin.ai/search?' + utm + '&noSubmit=true&prompt=' + encoded;
    return 'https://app.devin.ai/?tags=' + tag + '&' + utm + agentParams + '&prompt=' + encoded;
  };
  const ref = React.useRef(null);
  const [href, setHref] = React.useState('#');
  React.useEffect(() => {
    if (!ref.current) return;
    var codeEl = ref.current.querySelector('pre code');
    if (codeEl) {
      var text = codeEl.textContent.trim();
      if (text) setHref(buildUrl(text));
    }
    var header = ref.current.querySelector('[data-component-part="code-block-header"]');
    if (header && !header.querySelector('.prompt-block-devin-link')) {
      var link = document.createElement('a');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'prompt-block-devin-link';
      link.style.cssText = 'display:inline-flex;align-items:center;gap:6px;text-decoration:none;color:#fff;font-size:11px;font-weight:500;padding:4px 10px;border-radius:6px;white-space:nowrap;background:#317CFF;transition:background 0.2s;margin-left:8px;';
      link.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg> ' + label;
      link.onmouseenter = function () {
        link.style.background = '#2968D9';
      };
      link.onmouseleave = function () {
        link.style.background = '#317CFF';
      };
      header.appendChild(link);
    }
    var existingLink = ref.current.querySelector('.prompt-block-devin-link');
    if (existingLink && href !== '#') existingLink.href = href;
  });
  return <div className="prompt-block" ref={ref}>{children}</div>;
};

<UseCaseHero title="3つの競合戦略でチェックアウトのレイテンシを改善する" description="遅いチェックアウトAPIに対して3つのDevinセッションを並列に競わせます — それぞれ異なる最適化に取り組み、最良のアプローチを本番に反映します。" prompt="チェックアウトAPIのp99レイテンシが1.8秒で、400ms未満にする必要があります。3つのDevinセッションを並列に起動し、それぞれが独立してこのAPIを最適化してください。各セッションはエンドポイントをプロファイルし、異なる最適化戦略を実装し、その結果をベンチマークする必要があります。3つすべてが完了したら、それぞれのアプローチを比較し、最良の解決策で最終的なPRを作成して提出してください。" category="Devin 最適化" features="高度" agent="advanced" intent="batch" />

<div className="uc-detail-wrapper">
  <Tip>手動でのセットアップを省略したいですか？このページのリンクを Devin のセッションに貼り付けて、すべてのセットアップを依頼してください。</Tip>

  <Steps>
    <Step title="課題と成功基準を定義する">
      あなたの checkout API (`POST /api/checkout`) は p99 レイテンシが 1.8 秒で、ユーザーはカートを放棄しており、SLA 目標は 400ms です。これを改善するための有効な手段はいくつかあります。キャッシュ、クエリ最適化、非同期処理、コネクションプーリングなどです。ですが、実際に試してみるまでどれが最適かわからず、順番に試していくと、結果が出るまでに数日かかってしまいます。

      そこで、Devin に 3 つのセッションを並列に起動させ、それぞれに異なる戦略を試させます。3 つすべてが完了したら、Devin が結果を比較し、最も優れたアプローチを採用してリリースするか、それぞれの最良の部分を組み合わせて 1 つの PR にまとめます。

      始めるには、[Devin ホームページ](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) から新しい Devin セッションを開き、バッチタスクの内容を記述します。
    </Step>

    <Step title="各セッションがそれぞれ異なる修正内容に向かうように誘導するプロンプトを作成してください">
      3 つのセッションを実行する価値は、それぞれが本当に異なるアプローチを探索できているかどうかにかかっています。発散を促すようにプロンプトを書き、具体的な戦略を提案しつつ、「best (最良) 」の意味を定義して、結果を直接比較できるようにしましょう。

      <PromptBlock agent="advanced" intent="batch">
        ```txt Fix checkout latency — 3 competing strategies theme={null}
        Our checkout API (POST /api/checkout in src/routes/checkout.ts) has
        a p99 latency of 1.8s. We need it under 400ms.

        Start 3 parallel sessions. Each should:
        1. Profile the endpoint to find bottlenecks (run `npm run bench:checkout`)
        2. Pick a DIFFERENT optimization strategy — e.g., caching, query
           optimization, async processing, connection pooling, or denormalization
        3. Implement the optimization
        4. Re-run the benchmark and report the new p99

        Comparison criteria — rank each result by:
        - p99 latency (must be under 400ms to pass)
        - Error rate (must not increase)
        - Code complexity added (fewer new dependencies = better)
        - Data consistency tradeoffs (document any eventual-consistency risks)

        Once all 3 finish, compare the results using the criteria above and
        create a final PR that uses the best approach — or combines ideas
        from multiple sessions if that gets us lower latency.
        ```
      </PromptBlock>

      **良いマルチストラテジープロンプトを書くためのヒント:**

      * **「best」を順位付きの評価基準で定義する。** レイテンシ、エラー率、複雑さ、一貫性といった比較軸を列挙することで、Devin が単純に速度だけを優先することを防げます。
      * **具体的な戦略を提案する。** 「キャッシュ、クエリ書き換え、非同期処理」などの選択肢を示すことで、それぞれのセッションを異なる方向性に誘導できます。
      * **ベンチマーク用コマンドを含める。** 各セッションが自分の結果を測定するための再現可能な方法が必要です — `npm run bench`、`k6 run load-test.js`、または簡単な curl ループなど。
      * **コードへのパスを示す。** `src/routes/checkout.ts` のようなファイルパスを指定することで、3 つのセッションすべてが同じ地点から開始できます。
    </Step>

    <Step title="結果を比較して勝者を決定する">
      3つのセッションがすべて完了すると、Devin があなたの基準に照らして成果物を並べてレビューします。使用した戦略、ベンチマークの数値、トレードオフなどを比較し、最も優れたものを選ぶか、それらを統合して最終的な PR にまとめます。

      チェックアウトのレイテンシ問題についての比較は、次のとおりです。

      ```
      Session 1 — Redis response caching
        Strategy:   Cache serialized cart + inventory lookups in Redis with
                    30s TTL, bypass DB for repeat requests
        p99:        1.8s -> 320ms  (PASS — 82% reduction)
        Errors:     No change
        Complexity: +1 dependency (ioredis), 2 new files
        Tradeoff:   Stale inventory data for up to 30s; 40MB Redis memory

      Session 2 — Query optimization + connection pooling
        Strategy:   Replaced N+1 queries with a single JOIN, added PgBouncer
                    connection pool (25 connections)
        p99:        1.8s -> 580ms  (FAIL — still above 400ms)
        Errors:     No change
        Complexity: 0 new dependencies, cleaner queries
        Tradeoff:   None significant — lower DB load overall

      Session 3 — Async order processing
        Strategy:   Moved payment processing and email to a background queue
                    (BullMQ), return 202 immediately after inventory check
        p99:        1.8s -> 190ms  (PASS — 89% reduction)
        Errors:     No change
        Complexity: +1 dependency (bullmq), 3 new files, webhook handler
        Tradeoff:   Checkout becomes eventually consistent; needs webhook
                    for payment confirmation

      Verdict: Sessions 1 and 3 both pass the 400ms target. Session 2's
      query fixes are valuable but insufficient alone.

      Final PR: Combined Session 2's query optimization (no cost, strictly
      better) with Session 3's async processing. Payment + email moved to
      queue, N+1 queries fixed. Final p99: 150ms. PR #412 opened.
      ```

      Devin が統合版の PR を作成する前に、各セッションの PR を個別にレビューできます。特定のアプローチをそのまま採用したい場合は、Devin に "Session 3 のアプローチで進めて、統合はスキップして" と伝えてください。
    </Step>

    <Step title="1つの問題に対して3つの戦略を並行して試すタイミング">
      **適しているケース — 複数の有効なアプローチが存在する場合:**

      * キャッシュ、クエリチューニング、アーキテクチャ変更のいずれもが有効になりうるパフォーマンスボトルネック
      * 明確なトレードオフがあるアーキテクチャ上の意思決定 (モノリスの分割、状態管理の再設計など)
      * データ量が多い問題に対するアルゴリズム選定 (異なるインデックス方式、ランキング手法、ML アプローチなど)

      **適していないケース — 解決策が明らかな場合:**

      * 根本原因が明確なバグ修正
      * 標準的な CRUD エンドポイントの追加
      * 依存関係や設定ファイルの更新

      このパターンは、単一セッションの 3 倍の [ACU](/ja/admin/billing/usage) を使用します。本来であれば数日かけてアプローチを順番に試すような問題に限定して使ってください。単純なタスクであれば、単一の Devin セッションの方が速く、かつコストも低くなります。

      `advanced_mode` を `batch` に設定することで、[API 経由](/ja/api-reference/v3/sessions/post-organizations-sessions)で並列セッションを起動することもできます。これは、性能劣化に対して複数の修正案を自動的に競争させる CI パイプラインへの統合に便利です。提案に対してあなたの承認を待たずに Devin を完全自律的に実行したい場合は、**bypass permissions** フラグを有効にして、セッションが自動承認され継続実行されるようにします。
    </Step>
  </Steps>
</div>
