在 Rails 7 中如何缓存向量计算结果到 Redis
解读
面试官问“向量计算结果”而非简单字符串,核心想验证三点:
- 你是否理解 Rails 7 的 Cache API 与 Redis 适配层(默认用
redis_cache_store); - 能否把 高维浮点数组 高效序列化/反序列化,并保证精度;
- 是否掌握 缓存失效、并发竞争、内存淘汰 等生产级细节。
国内大厂面试常把“向量”与“推荐/搜索”场景挂钩,答不出 MessagePack + 压缩 + 分片 容易被打上“只会基础 KV”标签。
知识点
- Rails 7 内置
RedisCacheStore,支持 connection pooling、分布式节点、TTL、race_condition_ttl、compress; - 向量数据类型:Ruby 侧为
Array<Float>或NMatrix/Numo::NArray,Redis 侧只能存 String; - 序列化方案:
–MessagePack比Marshal跨语言、体积小 30%+;
– 若维度>1 024,先 gzip/zstd 再落盘,省 50% 内存; - 键设计:业务前缀 + 维度 + 版本号,如
rec:v2:uid:123456#512d,方便 批量失效; - 并发写:用
Redis#watch+multi或Lua脚本保证 原子累加/替换; - 内存淘汰:国内云 Redis 多为 8 G 主从,必须设置
maxmemory-policy allkeys-lfu,并评估 向量维度×用户量 是否触发逐出; - 安全:禁用
EVAL危险命令,开启 阿里云 Redis 的审计日志,防止研发误删。
答案
- 配置 Redis 缓存
# config/environments/production.rb
config.cache_store = :redis_cache_store, {
url: ENV.fetch("REDIS_URL", "redis://redis-cluster:6379/1"),
pool_size: 10,
pool_timeout: 5,
compress: true, # 开启 gzip
compress_threshold: 1.kilobyte,
expires_in: 2.hours,
race_condition_ttl: 10.seconds
}
- 向量工具模块
module VectorCache
KEY_PREFIX = "vec:rec"
DIMENSION = 512
def self.encode(vec)
Zlib.gzip(MessagePack.pack(vec))
end
def self.decode(str)
MessagePack.unpack(Zlib.gunzip(str))
end
end
- 计算入口(推荐服务)
class RecommendationService
def initialize(user_id)
@user_id = user_id
@key = "#{VectorCache::KEY_PREFIX}:#{user_id}:#{VectorCache::DIMENSION}d"
end
def vector
Rails.cache.fetch(@key, expires_in: 2.hours, race_condition_ttl: 10) do
raw = compute_raw_vector # 耗时 200 ms
VectorCache.encode(raw)
end.then { |compressed| VectorCache.decode(compressed) }
end
private
def compute_raw_vector
# 调用 TensorFlow Serving 或 Faiss,返回 Array<Float>
Array.new(VectorCache::DIMENSION) { rand }
end
end
- 失效策略
# 用户画像变更后同步清缓存
Redis.current.del("vec:rec:#{user_id}:*")
# 或按版本号批量失效
Redis.current.scan_each(match: "vec:rec:v2:*").each_slice(1000) { |keys| Redis.current.del(*keys) }
- 监控
# config/initializers/cache_instrumentation.rb
ActiveSupport::Notifications.subscribe "cache_read.active_support" do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
Rails.logger.info "[Cache] hit=#{!event.payload[:hit]} key=#{event.payload[:key]} duration=#{event.duration}ms"
end
拓展思考
- 若向量维度高达 768/1024 且日活千万,单 Key 会超过 1 MB,考虑 分片存储(Hash 结构
vec:uid:123:part0…partN)或 RedisBloom 的 Cuckoo Filter 做预判断; - 对实时性要求高的场景,可把计算结果先写 Kafka,由消费者异步写 Redis,并通过 双 Key 版本号 实现 灰度切换;
- 国内合规要求“数据出境评估”,若向量含用户隐私,需 AES-256-GCM 加密后再落盘,密钥放 KMS;
- 面试加分项:提到 Redis 7.0 的 Functions 可固化向量相似度 Lua 脚本,避免每次 EVAL 传输代码,降低网络 IO 30%。