> ## 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.

# 通过三种互相竞争的方案优化结账延迟

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="用三种竞争策略降低结账延迟" description="让 3 个并行 Devin 会话与一个缓慢的结账 API 展开竞赛——每个会话尝试不同的优化，然后将最佳方案上线。" prompt="我们的结账 API 的 p99 延迟为 1.8s，需要降到 400ms 以下。启动 3 个并行 Devin 会话分别对其进行独立优化。每个会话都应对该端点进行性能剖析、实现一种不同的优化策略，并对结果进行基准测试。等 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 会比较结果并交付最优方案——或者将各个方案中最好的部分合并到一个拉取请求 (PR) 中。

      要开始使用，请从 [Devin 主页](https://app.devin.ai/?utm_source=docs\&utm_medium=use-case-gallery) 打开一个新的 Devin 会话，并描述这个批量任务。
    </Step>

    <Step title="编写一个提示，使每次会话都朝向不同的修复方案推进">
      运行 3 个会话的价值取决于每个会话是否真正探索了一种彼此截然不同的方案。编写提示时要鼓励多样化探索——给出具体策略，并定义什么是“最佳”，这样结果才能直接进行对比。

      <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>

      **编写优质多策略提示的建议：**

      * **用排序后的标准定义“最佳”。** 列出对比维度——延迟、错误率、复杂度、一致性——可以避免 Devin 只默认追求速度本身。
      * **提出具体策略选项。** 像 “caching, query rewriting, async processing” 这样的选项，可以引导每个会话走向不同的优化路径。
      * **包含基准测试命令。** 每个会话都需要一种可复现的方式来衡量自己的结果——如 `npm run bench`、`k6 run load-test.js`，或一个简单的 curl 循环。
      * **指向具体代码。** 像 `src/routes/checkout.ts` 这样的文件路径，可以确保 3 个会话都从同一个起点出发。
    </Step>

    <Step title="比较结果并选出最佳方案">
      当 3 个会话全部完成后，Devin 会按照你的评估标准，并排审查它们的工作成果——包括采用的策略、基准指标、权衡取舍——然后要么选出最佳方案，要么将多个方案整合成一个最终 PR。

      下面是针对结账延迟问题的对比结果示例：

      ```
      会话 1 — Redis 响应缓存
        策略：      将序列化的购物车 + 库存查询缓存至 Redis，
                    TTL 30 秒，重复请求绕过数据库
        p99：       1.8s -> 320ms（通过 — 降低 82%）
        错误：      无变化
        复杂度：    +1 个依赖项（ioredis），2 个新文件
        权衡：      库存数据最多延迟 30 秒；占用 40MB Redis 内存

      会话 2 — 查询优化 + 连接池
        策略：      将 N+1 查询替换为单次 JOIN，添加 PgBouncer
                    连接池（25 个连接）
        p99：       1.8s -> 580ms（失败 — 仍高于 400ms）
        错误：      无变化
        复杂度：    0 个新依赖项，查询更简洁
        权衡：      无显著影响 — 整体降低数据库负载

      会话 3 — 异步订单处理
        策略：      将支付处理和邮件发送移至后台队列
                    （BullMQ），库存检查完成后立即返回 202
        p99：       1.8s -> 190ms（通过 — 降低 89%）
        错误：      无变化
        复杂度：    +1 个依赖项（bullmq），3 个新文件，webhook 处理器
        权衡：      结账流程变为最终一致性；需要 webhook
                    确认支付结果

      结论：会话 1 和会话 3 均达到 400ms 目标。会话 2 的
      查询优化有价值，但单独使用仍不足。

      最终 PR：将会话 2 的查询优化（零成本，纯收益）与
      会话 3 的异步处理相结合。支付 + 邮件移至队列，
      N+1 查询已修复。最终 p99：150ms。PR #412 已创建。
      ```

      在 Devin 创建汇总 PR 之前，你可以先审查每个会话各自的 PR。如果你明确更倾向于某一种方案，只需告诉 Devin — "采用第 3 个会话的方案，跳过合并。"
    </Step>

    <Step title="何时在同一问题上并行运行 3 种策略">
      **适用场景 — 存在多种可行方案时：**

      * 性能瓶颈问题，可以通过缓存、查询调优或架构调整等多种方式解决
      * 需要权衡取舍的架构决策 (如从单体拆分、重新设计状态管理)
      * 针对海量数据问题的算法选择 (不同索引方式、排序策略或 ML 方法)

      **不适用场景 — 解决方案非常显而易见时：**

      * 具有明确根因的 Bug 修复
      * 添加一个标准的 CRUD 接口
      * 更新依赖或配置文件

      此模式会使用单次会话 3 倍的 [ACUs](/zh/admin/billing/usage)。仅在那些否则你可能需要花上几天时间依次尝试不同方案的问题上使用。对于简单任务，单次 Devin 会话更快且更省成本。

      你也可以通过在 [API 中](/zh/api-reference/v3/sessions/post-organizations-sessions) 将 `advanced_mode` 设置为 `batch` 来触发并行会话——非常适合集成到 CI 流水线中，让其自动并行尝试多种修复方案来应对性能回归。如果你希望 Devin 完全自主运行，而不必等待你对方案的批准，可以启用 **bypass permissions** 开关，让会话自动批准并持续推进。
    </Step>
  </Steps>
</div>
