Caching Pitfalls Every Developer Should Know

ByteByteGo
7 Mar 202406:40

Summary

TLDRキャッシングは、よく利用されるデータのコピーを保存する手法で、システムのパフォーマンスを向上させるのに重要です。しかし、適切に処理されないと、キャッシュスタンピーやキャッシュ侵入、キャッシュクラッシュやキャッシュアバランチなどの問題が発生する可能性があります。このビデオは、これらの問題の原因と対策について説明しています。ロックの獲得、リフレッシュの分散化、ブルームフィルタの利用、冗長性の確保などの戦略が紹介されており、大規模システムの設計におけるキャッシングの重要性が強調されています。

Takeaways

  • 📚 キャッシングとは、頻繁にアクセスされるデータのコピーを保存して高速アクセスを実現する技術です。
  • ⚡ キャッシングにより高いパフォーマンスが得られる一方で、キャッシュ競合、キャッシュ汚染、キャッシュ障害などの課題が生じる可能性があります。
  • 🔒 キャッシュ競合を防ぐ対策としては、ロック、外部プロセスへの計算オフロード、確率的な早期期限切れなどがあります。
  • 🚫 キャッシュ汚染は、存在しないデータに対する無駄な読み込み試行を防ぐことで回避できます。プレースホルダ値やBloomフィルタを活用するのが有効です。
  • 💥 キャッシュ障害が発生すると、すべてのリクエストがデータベースに直接ヒットし、システム全体に大きな負荷がかかります。
  • 📉 キャッシュ障害を軽減するには、回路ブレーカーの導入、可用性の高いキャッシュクラスタの構築、冷起動時のウォームアップが重要です。
  • ⚠️ キャッシュ競合とキャッシュ障害は似ているが異なる概念で、前者は単一のキャッシュエントリに対して発生し、後者はキャッシュ全体に影響を与えます。
  • 📝 キャッシングの利点を最大化し、問題を回避するには、システムの特性に応じた適切な戦略を立てる必要があります。
  • 🕵️ キャッシングは性能向上に不可欠ですが、さまざまな潜在的な課題にも注意を払う必要があります。
  • 📈 適切なキャッシング戦略を採用することで、高性能かつ安定したシステムを実現できます。

Q & A

  • キャッシングとは何ですか?

    -キャッシングとは、頻繁にアクセスされるデータのコピーを保存する一時的なメモリ層のことです。データベースからデータを取得するよりも高速にデータを提供することができ、システムのパフォーマンスを向上させます。

  • キャッシュで発生する可能性のある一般的な問題にはどのようなものがありますか?

    -一般的な問題としては、キャッシュスタンピー、キャッシュペネトレーション、キャッシュクラッシュ、キャッシュアバランチェがあげられます。これらは、システムのパフォーマンスや安定性に深刻な影響を及ぼす可能性があります。

  • キャッシュスタンピーとは何ですか? その対策方法は何ですか?

    -キャッシュスタンピーとは、複数のリクエストが同時にキャッシュ期限切れのエントリを更新しようとした際に、データベースが過負荷になる現象です。対策としては、ロック、外部プロセスでの再計算、確率的な早期期限切れなどの手法があります。

  • キャッシュペネトレーションとは何ですか? その対策方法は何ですか?

    -キャッシュペネトレーションとは、存在しないデータに対するリクエストがキャッシュやデータベースに無駄に負荷をかける現象です。対策としては、存在しないキーに対してプレースホルダ値を設定したり、Bloomフィルタを使用したりすることができます。

  • キャッシュクラッシュとキャッシュアバランチェの違いは何ですか?

    -キャッシュクラッシュとは、キャッシュシステム全体が突然停止した際に発生する現象で、全てのリクエストがデータベースに直接向かうため過負荷になります。一方のキャッシュアバランチェは、大量のキャッシュデータが一度に期限切れになったり、キャッシュが再起動した際に発生する現象です。

  • キャッシュクラッシュやアバランチェに対してどのような対策があるでしょうか?

    -対策としては、回路ブレーカーを導入してリクエストを一時的にブロックしたり、可用性の高いキャッシュクラスターを導入したり、コールドキャッシュ時にデータを事前に投入したりすることが効果的です。

  • キャッシングの利点は何ですか?

    -キャッシングの主な利点は、データベースからの取得よりも高速にデータを提供できるため、システム全体のパフォーマンスが向上することです。また、データベースへの負荷も軽減できます。

  • キャッシングを適切に行うためには、どのようなことに注意が必要でしょうか?

    -キャッシングを適切に行うためには、キャッシュの有効期限の設定、キャッシュのサイズ管理、データの一貫性の確保、各種キャッシュ関連の問題への対策など、さまざまな点に注意が必要です。システムの要件やトラフィックパターンに応じて、適切にチューニングする必要があります。

  • Bloomフィルタとは何ですか?

    -Bloomフィルタとは、データの存在の有無を確認する確率的なデータ構造です。データベースへのアクセスの前に、データが存在するかどうかを高速にチェックすることができ、キャッシュペネトレーションの問題を軽減できます。

  • システム設計におけるキャッシングの重要性を教えてください。

    -キャッシングは、システム設計において極めて重要な概念です。適切なキャッシング戦略を立てることで、システム全体のパフォーマンス、スケーラビリティ、応答性を大幅に改善することができます。一方で、キャッシングに関する問題を無視すれば、システムの信頼性や可用性に深刻な影響を与える可能性があります。

Outlines

00:00

📚 キャッシングの概要と課題

この文章では、システム設計において重要なキャッシングの概念と、適切に扱われない場合に生じる可能性のある課題について説明しています。キャッシングの基本的な役割と、キャッシングを使うことによるパフォーマンス向上の利点を簡潔に説明した上で、キャッシュスタンプ、キャッシュ侵入、キャッシュクラッシュといった一般的な問題について詳しく解説しています。また、それぞれの問題に対する対策の概要も示されています。

05:02

⚡️ キャッシュ問題への対処法

この文章では、キャッシュ関連の問題に対処するための具体的な戦略が説明されています。主な対策としては、ロック、計算のオフロード、確率的な早期期限切れ、ブルームフィルタの使用などが挙げられています。また、キャッシュクラッシュやキャッシュアバランシュに対しては、回路ブレーカー、高可用性キャッシュクラスタ、キャッシュウォーミングなどの対策が提案されています。最後に、キャッシュスタンプとキャッシュアバランシュの違いについても簡潔に説明されています。

Mindmap

Keywords

💡キャッシュ

キャッシュとは、頻繁にアクセスされるデータのコピーを保存する一時的な記憶層のことです。データベースからデータを取得する代わりに、キャッシュからデータを取得することで、パフォーマンスを向上させます。このビデオでは、ユーザープロフィールのデータをキャッシュに保存する例が挙げられています。キャッシュのメリットは高速なデータアクセスですが、適切に管理されない場合、いくつかの問題が発生する可能性があります。

💡キャッシュ救世主

キャッシュ救世主は、キャッシュされたページの有効期限が切れた際に発生する問題のことです。この状況では、ウェブクラスター上の複数のスレッドが同時にページを更新しようとするため、データベースに過剰な負荷がかかる可能性があります。この問題を回避するための戦略として、ロックの取得、再計算のオフロード、確率的な早期期限切れなどが紹介されています。

💡キャッシュ侵入

キャッシュ侵入とは、データベースやキャッシュ内に存在しないデータが要求された場合に発生する問題です。このような無駄なリクエストが大量に発生すると、システム全体のパフォーマンスに影響を与える可能性があります。この問題を軽減するには、存在しないキーに対するプレースホルダー値を設定したり、Bloom フィルターを使用したりする方法があります。

💡キャッシュクラッシュ

キャッシュクラッシュとは、キャッシュシステム全体が突然失敗した場合に発生する問題のことです。キャッシュがない場合、すべてのリクエストがデータベースに直接ヒットするため、データベースが過負荷になる可能性があります。さらに、ユーザーがリフレッシュを繰り返すことでこの問題が深刻化する恐れがあります。この問題に対処するには、回路ブレーカーの導入やキャッシュクラスターの冗長化、キャッシュウォーミングなどの対策が有効です。

💡キャッシュアバランチ

キャッシュアバランチは、キャッシュが空の状態やキャッシュの再起動後に発生する問題です。この場合、多数のリクエストがデータベースに一斉に殺到するため、リソースが圧迫されてシステム全体のパフォーマンスが低下します。キャッシュアバランチはキャッシュクラッシュとは異なり、さまざまなデータに対するリクエストが原因となります。この問題に対処するには、キャッシュウォーミングが重要になります。

💡ロック

ロックは、キャッシュ救世主の問題を回避する方法の1つです。キャッシュミスが発生した場合、各リクエストはキャッシュキーに対するロックを取得しようとします。ロックが取得できれば、そのスレッドのみがキャッシュの再計算を行えます。ロックの取得に失敗した場合は、再計算の結果を待つか、一時的に古いデータを使用するなどの対処が必要です。しかし、ロックの実装には難しさがあります。

💡再計算のオフロード

再計算のオフロードとは、キャッシュの再計算処理を別のプロセスに移行させる方法です。この方法では、キャッシュの有効期限が近づいた時点で予防的に再計算を開始したり、キャッシュミスが発生した時点で再計算を開始したりすることができます。しかし、この方法ではアーキテクチャに別の移動部品が追加されるため、慎重な維持と監視が必要になります。

💡確率的な早期期限切れ

確率的な早期期限切れは、キャッシュ救世主の問題を軽減する別の方法です。この戦略では、各リクエストに対して一定の確率でキャッシュ値の再計算をトリガーさせます。この確率は、有効期限が近づくにつれて高くなります。このようにキャッシュの期限切れをずらすことで、同時に発生する再計算リクエストの数を減らすことができます。

💡プレースホルダー値

プレースホルダー値は、キャッシュ侵入の問題を軽減するための方法の1つです。存在しないキーに対してプレースホルダー値をキャッシュに設定することで、後続の同じリクエストがデータベースに到達する前にキャッシュからプレースホルダーを取得できます。ただし、プレースホルダー値のTTL設定には注意が必要で、キャッシュリソースの消費を抑える適切なチューニングが重要になります。

💡Bloom フィルター

Bloom フィルターは、キーがデータセット内に存在するかどうかを確認するための空間効率的なデータ構造です。Bloom フィルターを使用することで、キャッシュ侵入の問題を軽減できます。データベースを参照する前に Bloom フィルターを確認し、キーが存在しない場合はリクエストを早期に拒否できます。ただし、Bloom フィルターには一定の誤検出率があり、本当に存在するキーが存在しないと判断される可能性もあります。

Highlights

Caching is a memory layer that stores copies of frequently accessed data to speed up performance by reducing the need to fetch data from slower databases.

Cache stampede can occur when multiple threads try to refresh an expired cache page at the same time, potentially overwhelming the database.

Locking upon a cache miss can prevent cache stampede, with options like waiting for recomputation, returning a not-found response, or serving a stale cache value.

Offloading recomputation to an external process is another solution for cache stampede, but adds complexity to the architecture.

Probabilistic early expiration staggered refreshing can mitigate cache stampede by proactively triggering recomputation before actual expiration.

Cache penetration occurs when requests are made for data that doesn't exist in the database or cache, resulting in unnecessary load.

Implementing a placeholder value for non-existent keys can mitigate cache penetration, but requires careful tuning to avoid cache resource consumption.

Bloom filters can quickly check if data exists before querying the database, potentially reducing cache penetration.

Cache crash or avalanche can occur when the entire cache system fails or a massive chunk of cache data expires, causing a sudden spike in database traffic.

Implementing a circuit breaker can temporarily block incoming requests when the system is overloaded, preventing total meltdown.

Deploying a highly available cache cluster with redundancy can reduce the severity of full cache crashes.

Cache priming by proactively populating critical data in a cold cache before putting it into service can help avoid sudden database load spikes.

Cache stampede happens when many requests simultaneously hit the same expired cache entry, overwhelming the database for that single data point.

Cache avalanche is a broader issue where numerous requests for different data flood the system after a cache is cleared or restarted, straining resources.

The transcript provides an overview of caching, its benefits, and common pitfalls like cache stampede, penetration, crashes, and avalanches, along with strategies to mitigate these issues.

Transcripts

play00:00

today we're going to talk about caching

play00:02

a key Concept in system design that is

play00:04

critical for performance can also cause

play00:06

some issues if not handled properly

play00:08

before jumping into what can go wrong

play00:10

let's quickly cover the basics of what

play00:12

caching is and why it matters simply put

play00:15

caching is like a memory layer that

play00:17

store copies of frequently accessed data

play00:20

it's a strategy to speed things up by

play00:22

keeping data readily available reducing

play00:24

the need to fetch it from slower

play00:26

databases every time it is requested for

play00:29

example think about a database with user

play00:31

profiles a cach with this database might

play00:34

store the most popular user profile so

play00:36

that when someone view a profile it

play00:38

loads instantly instead of hitting the

play00:40

database on every view now even with

play00:43

these performance gains caching also

play00:45

introduces new challenges let's unpack

play00:47

the common problems that can come up

play00:50

first let's explore cash Stampy imagine

play00:53

a web server using RIT to cat Pages for

play00:55

a set duration these Pages require

play00:58

extensive database costs and takes

play01:00

several seconds to render with caching

play01:03

the system stays responsive under high

play01:05

low since resource heavy Pages ass serve

play01:07

from cash however under extreme traffic

play01:10

if a cash page expires multiple threats

play01:13

across the web cluster may try

play01:14

refreshing the expire page at the same

play01:17

time this flood of requests could

play01:19

overwhelm the database potentially

play01:21

causing system failure and prevent the

play01:24

page from being Rec cached so how can we

play01:27

prevent St piece a few key strategies

play01:30

one is locking upon a cache miss each

play01:32

request attempts to acquire a lock for

play01:34

that cash key before recomputing the

play01:37

expired page if the lock is not acquired

play01:40

there are some options one the request

play01:42

can wait until the value is recomputed

play01:44

by another thread two the request can

play01:47

immediately return a notfound response

play01:50

and let the client handle the situation

play01:52

with a backup retry three the system can

play01:55

maintain a stale version of the cach

play01:57

item to be used temporarily while the

play02:00

new value is Rec computed locking

play02:02

requires an additional right operation

play02:04

for the lock itself and implementing

play02:06

lock acquisition correctly can be

play02:08

challenging another solution is

play02:10

offloading recomputation to an external

play02:13

process this method can be activated in

play02:15

various ways either proactively when a

play02:18

cach key is nearing expiration or

play02:20

reactively when a cach m occurs this

play02:23

approach add another moving part to the

play02:25

architecture that requires careful

play02:28

ongoing maintenance and monitoring a

play02:30

third approach is probabilistic early

play02:32

expiration in this strategy each request

play02:35

has a small chance of proactively

play02:36

triggering recomputation of the cash

play02:39

value before its actual expiration the

play02:42

likelihood of this happening increases

play02:43

as the expiration time approaches this

play02:46

stagger early refreshing mitigates the

play02:48

impact of stamped since fewer keys will

play02:51

expire moving on to cach penetration

play02:54

this happens when a request is made for

play02:56

data that doesn't exist in the database

play02:58

or cash this result results in

play03:00

unnecessary low as the system tries to

play03:02

retrieve non-existent data this can

play03:05

stabilize the entire system if the

play03:06

request volume is high to mitigate cash

play03:10

penetration Implement a placeholder

play03:12

value for non-existent keys this way

play03:15

followup request for the same missing

play03:17

data hit the placeholders in Cache

play03:20

instead of pointlessly hitting the

play03:21

database again setting appropriate TTL

play03:24

for these placeholders prevents them

play03:26

from occupying cash base indefinitely

play03:30

however this approach requires careful

play03:32

tuning to avoid significant cash

play03:34

resource consumption especially for

play03:36

systems with many lookups of

play03:38

non-existent keys another approach uses

play03:41

Bloom filters a space efficient

play03:43

probabilistic data structure for quickly

play03:45

checking if elements are in a set before

play03:48

querying the databases here's how they

play03:50

work when new records are added to

play03:52

storage their keys are recorded in bloom

play03:54

filter before fetching records the

play03:57

application checks the bloom filter

play03:58

first if the key key is absent the

play04:00

record conclusively doesn't exist

play04:02

allowing the application to return a no

play04:05

value immediately however positive key

play04:08

presence doesn't guarantee existence a

play04:10

small percentage of cash reads may still

play04:13

result in misses we have a video on how

play04:16

Bloom filters work if you want to learn

play04:18

more finally we come to cash crash

play04:21

picture this our entire Cash System

play04:23

suddenly fails what happens next with no

play04:26

cash layer every single request now

play04:28

slams straight into the data base this

play04:30

sudden spike in traffic can easily

play04:32

overwhelm databases jeopardizing overall

play04:35

system stability what's worse users

play04:38

start obsessively hitting refresh

play04:40

compounding the problem a close cousin

play04:42

to the cash crash is cash avalan this

play04:45

can happen in two scenarios one when a

play04:48

massive chunk of cash data expires all

play04:51

at once two when the cash restarts and

play04:54

is cold and empty in both cases a

play04:57

crushing wave of request hits the dat

play04:59

databases all at once this sudden low

play05:02

Spike overwhelms the system much like

play05:04

hundreds of people abruptly cramming

play05:06

through a single tiny door after a fire

play05:09

alarm so how do we tackle these

play05:11

challenges First Option Implement a

play05:13

circuit breaker which temporarily blocks

play05:16

incoming request when the system is

play05:18

clearly overloaded this prevents total

play05:20

meltdown and buys time for Recovery next

play05:23

strategy deploy highly available cash

play05:26

cluster with redundancy it parts of the

play05:29

cash go down other parts remain

play05:31

operational the goal is to reduce the

play05:33

severity of full crashes and don't

play05:36

dismiss cash proring particularly

play05:38

critical after a co- here essential data

play05:41

is proactively populated in the co-

play05:43

cache before it's put into service pleas

play05:46

avoid abruptly bombarding the databases

play05:49

as we wrap up let's distinguish cash

play05:52

stamp versus cash Avalanche since they

play05:54

sound similar a cash STP happens when

play05:57

many request simultaneous ly hit the

play06:00

same expired cash entry overwhelming the

play06:02

database as it stes to refresh just that

play06:05

single data point a cash Avalanche is a

play06:08

broader issue where numerous requests

play06:11

for different data flood the system

play06:13

after a cach is clear or restarted

play06:15

putting a strain on

play06:17

resources and that concludes our walk

play06:20

through of the common caching pitfalls

play06:22

and how to navigate them if you like our

play06:25

videos you might like our system design

play06:27

newsletter as well it covers top and

play06:29

Trends in large scale system design

play06:32

trusted by 500,000 readers subscribe at

play06:35

blog. bybg

play06:39

go.com

Rate This

5.0 / 5 (0 votes)

Связанные теги
システム設計パフォーマンスキャッシング技術解説トラブルシューティングアーキテクチャスケーラビリティモニタリング最適化ベストプラクティス
Вам нужно краткое изложение на английском?