Visualize FIFO cache replacement. Watch how items enter and exit the cache in strict insertion order, regardless of access frequency.
About this algorithm
A FIFO cache keeps a fixed number of items and, when it is full, throws out the item that arrived first. It works like a line at a ticket counter: whoever joined earliest leaves first, no matter how often they were needed while they waited. It is the simplest replacement policy there is, and it is the one most likely to throw out something you are about to use again.
Pick FIFO when you want the cheapest possible bookkeeping and the data has little reuse, or when the hardware only gives you a ring of slots and a pointer, as in some TLBs and network buffers. A hit costs nothing extra because nothing moves. Choose LRU when items used recently tend to come back, which is true of most programs and web traffic: LRU would have kept the pages FIFO throws away below. Clock gives you most of LRU for little more than FIFO costs. LFU suits data whose popular items stay popular, and MRU suits loops that scan more data than the cache holds.
Hold the cached keys in a queue, oldest at the front and newest at the back, plus a set for quick lookups. The queue records only when each item came in, never when it was last used.
When a request arrives, look the key up in the set. If it is there, that is a hit: return it and change nothing. The queue order stays exactly as it was, which is the whole difference from LRU.
If the key is missing and the cache is not yet full, add it to the back of the queue and to the set.
If the cache is full, remove the key at the front of the queue, the oldest arrival, then add the new key at the back.
The page requests 1 2 3 4 1 2 5 1 2 3 4 5 with room for four items. The first four requests are misses that fill the cache, with 1 oldest. Requests 1 and 2 are hits, but they do not move: 1 is still at the front. So when 5 arrives, FIFO evicts 1, the page it used two requests ago. Then 1 comes back and evicts 2, 2 evicts 3, 3 evicts 4, 4 evicts 5, and 5 evicts 1. Every one of the last six requests misses. The run ends with 2 hits and 10 misses, a 17% hit rate, and the cache holding 2, 3, 4 and 5.
Drag the capacity slider down to 3 and play the same sequence again. FIFO now gets 3 hits and 9 misses, better than it did with four slots. This sequence is the textbook case of Belady's anomaly: with FIFO, a bigger cache can miss more often, because the extra slot shifts which page is oldest at each eviction. LRU cannot do this. Whatever an LRU cache of size k holds, a cache of size k + 1 holds as well, so adding room never adds a miss.
Time: a set lookup, a push to the back of the queue and a pop from its front are each constant time, and a hit does no work at all. Space: the queue and the set each hold at most one entry per slot.