Amazon 追问:Amazon 规模下价格查询的性能

追问:Amazon 规模下价格查询的性能——批量、缓存与组件边界。

2026-04OAVO Helper · 面经整理

01 · QUESTIONS

面试题目

  • 目录取价每次需要十到一百毫秒。在 Amazon 的规模下,这段取价与计价代码应如何改造?批量与缓存放在哪里?是否应该合成一个组件?

02 · FOLLOW-UPS

追问

  • 能否接受旧价格
  • 缓存与折扣变更如何配合

03 · ANSWERS

参考答案

规模放大后,取价必须批量、结果必须缓存;计价与取价可以分成两个组件,但缓存失效要与折扣变更联动。

解题思路

  • 批量:一次请求多个 SKU,避免逐个远程调用。
  • 缓存:在计价服务本地或共享缓存中缓存「购物车内容 → 总价」,并设置过期时间。
  • 组件:取价(目录服务)与计价(折扣引擎)保持分离,通过批量接口协作;缓存可以放在计价侧。
  • 折扣或目录价格变更时,要能按规则失效相关缓存。

代码

from abc import ABC, abstractmethod

class Catalog:
    def __init__(self, prices):
        self.prices = prices                 # sku -> 单价(分)
    def price_of(self, sku):
        return self.prices[sku]
    def prices_of(self, skus):               # 批量取价,减少调用次数
        return [self.prices[s] for s in skus]

class Discount(ABC):
    @abstractmethod
    def amount(self, items, subtotal):
        ...

class ThresholdPercent(Discount):
    def __init__(self, threshold, percent):
        self.threshold, self.percent = threshold, percent
    def amount(self, items, subtotal):
        return subtotal * self.percent // 100 if subtotal >= self.threshold else 0

class CartPricer:
    def __init__(self, catalog, discounts, cache=None):
        self.catalog, self.discounts, self.cache = catalog, discounts, cache or {}

    def total(self, skus):
        key = tuple(sorted(skus))
        if key in self.cache:
            return self.cache[key]
        prices = self.catalog.prices_of(skus)
        subtotal = sum(prices)
        total = subtotal
        for d in self.discounts:             # 按列表顺序叠加
            total -= d.amount(list(zip(skus, prices)), total)
        self.cache[key] = max(0, total)
        return self.cache[key]

    def invalidate(self):
        self.cache.clear()

复杂度

  • 批量取价把多次网络往返变成一次;缓存命中时为常数时间。
  • 缓存空间与不同购物车组合数有关,需要容量上限与淘汰策略。

追问解答

能否接受旧价格

  • 短时间的旧价格通常可以接受,用过期时间控制窗口;涉及大额促销或法律要求时,变更后必须主动失效相关缓存。

缓存与折扣变更如何配合

  • 折扣规则变更时清空计价缓存,或按折扣 ID 做版本号,缓存键带上版本。
  • 目录价格变更时,按 SKU 失效包含该 SKU 的缓存条目,或接受短时间的旧价并尽快过期。

联系 OAVO Helper

想针对这题做模拟练习?

加微信咨询陪跑,我们可以按你的目标岗位安排简历、模拟面试或代投。

加微信咨询陪跑微信:aasummer