How to Record Last N Errors with a Ring Buffer in Python

Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 13 views 0 copies

Python code

17 lines
Python 3.9+
import collections

class ErrorRecorder:
    def __init__(self, size):
        self.buffer = collections.deque(maxlen=size)

    def record_error(self, message):
        self.buffer.append(message)

    def get_errors(self):
        return list(self.buffer)

if __name__ == "__main__":
    recorder = ErrorRecorder(3)
    for i in range(5):
        recorder.record_error(f"Error #{i}")
    print(recorder.get_errors())

Output

stdout
['Error #2', 'Error #3', 'Error #4']

How it works

The collections.deque with a maxlen acts as a ring buffer: when the deque reaches its maximum size, appending a new element automatically discards the oldest one. This makes it perfect for keeping a fixed-size rolling window of the last N errors. The record_error method appends each message, and get_errors returns a list copy so callers cannot mutate the internal state. The demo records five errors into a buffer of size three, so the final output contains only the last three messages.

Common mistakes

  • Using a plain list and forgetting to trim it, causing unbounded memory growth
  • Confusing deque.append with deque.popleft when trying to manually manage capacity
  • Returning the deque directly instead of a list, which exposes mutable internal state

Variations

  1. Use a helper function with a closure that wraps the deque for a lightweight solution
  2. Store timestamps along with messages in a deque of tuples for diagnostics

Real-world use cases

  • Keeping a rolling log of recent exceptions in a long-running service for quick on-demand diagnostics.
  • Bounding memory usage in an error-collection agent that forwards the latest N failures to a monitoring endpoint.
  • Storing the most recent validation failures in an ETL pipeline to reset processing without persisting the full history.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.