Skip to content

Conversation

@BrianLusina
Copy link
Owner

@BrianLusina BrianLusina commented Jan 5, 2026

Describe your change:

Has a design for a request logger rate limiter

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms have a URL in its comments that points to Wikipedia or other similar explanation.
  • If this pull request resolves one or more open issues then the commit message contains Fixes: #{$ISSUE_NO}.

Summary by CodeRabbit

  • New Features

    • Added Request Logger design pattern to manage message requests with time-based rate limiting.
  • Documentation

    • Added comprehensive documentation for Request Logger pattern, including algorithm mechanics, per-message cooldown approach, and complexity analysis with visual examples.
  • Tests

    • Added parameterized test suite validating Request Logger behavior across multiple scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

@BrianLusina BrianLusina self-assigned this Jan 5, 2026
@BrianLusina BrianLusina added enhancement Algorithm Algorithm Problem Datastructures Datastructures Documentation Documentation Updates Hash Map Hash Map Data structure Design labels Jan 5, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 5, 2026

📝 Walkthrough

Walkthrough

Introduces a new design pattern called "Request Logger" that implements rate limiting for messages using timestamp-based cooldowns. Includes the pattern documentation, Python implementation with a RequestLogger class, test suite, and a catalog entry.

Changes

Cohort / File(s) Summary
Design Pattern Catalog
DIRECTORY.md
Added "Request Logger" entry under Pubsub → Simple Events section, linking to the new pattern implementation.
Request Logger Pattern
design_patterns/request_logger/README.md, design_patterns/request_logger/__init__.py, design_patterns/request_logger/test_request_logger.py
New design pattern files: documentation explaining the rate-limiting algorithm (O(1) decision, O(n) space via hashmap tracking per-message timestamps), production RequestLogger class with message_request_decision method enforcing per-message cooldown, and parameterized test suite validating acceptance/rejection logic across multiple scenarios.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 A logger bounds through the design,
Tracking timestamps in a line,
Messages cool for a while, you see—
Rate-limited, happy, and free! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main addition: a request logger rate limiter design pattern, matching the core changeset objective.
Description check ✅ Passed The PR description follows the template with the change description and completes all checklist items except one (the optional issue-resolution item), meeting the requirements for a complete submission.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
design_patterns/request_logger/__init__.py (2)

5-9: Consider validating the time_limit parameter and fix comment typo.

Two issues:

  1. Comment typo: Line 7 says "first lookups" but should be "fast lookups (O(1))"
  2. Missing validation: The constructor doesn't validate that time_limit is non-negative. A negative time_limit could cause unexpected behavior.
🔎 Proposed improvements
 class RequestLogger:
     def __init__(self, time_limit: int):
+        if time_limit < 0:
+            raise ValueError("time_limit must be non-negative")
         self.time_limit = time_limit
-        # keeps track of the requests as they come in key value pairs, which allows for first lookups (O(1)).
+        # keeps track of the requests as they come in key value pairs, which allows for fast lookups (O(1)).
         # the key is the request, the value is the time.
         self.request_map: Dict[str, int] = {}

12-23: Logic is correct; consider minor refactoring to reduce duplication.

The rate limiting logic correctly implements the algorithm described in the README. However, there's code duplication on lines 19 and 22 where self.request_map[formatted_message] = timestamp and return True appear twice.

🔎 Optional refactor to reduce duplication
 def message_request_decision(self, timestamp: int, request: str) -> bool:
     formatted_message = request.lower()
     if formatted_message in self.request_map:
         latest_time_for_message = self.request_map[formatted_message]
         difference = timestamp - latest_time_for_message
         if difference < self.time_limit:
             return False
-        self.request_map[formatted_message] = timestamp
-        return True
 
     self.request_map[formatted_message] = timestamp
     return True
design_patterns/request_logger/test_request_logger.py (1)

6-23: Test cases are well-designed; consider adding edge case for exact time_limit boundary.

The existing test cases comprehensively cover the main scenarios. However, consider adding a test case where the timestamp difference equals exactly the time_limit to verify the boundary condition.

🔎 Suggested additional test case
# Add to REQUEST_LOGGER_TEST_CASES
(7, [(1, "Hello", True), (8, "Hello", True)]),  # difference = 7, exactly at boundary

This would test the edge case where difference == time_limit, which should return True (accept) based on the implementation's < time_limit check.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8f7d65b and 64542d2.

⛔ Files ignored due to path filters (8)
  • design_patterns/request_logger/images/examples/request_logger_example_1.png is excluded by !**/*.png
  • design_patterns/request_logger/images/examples/request_logger_example_2.png is excluded by !**/*.png
  • design_patterns/request_logger/images/examples/request_logger_example_3.png is excluded by !**/*.png
  • design_patterns/request_logger/images/solutions/request_logger_solution_1.png is excluded by !**/*.png
  • design_patterns/request_logger/images/solutions/request_logger_solution_2.png is excluded by !**/*.png
  • design_patterns/request_logger/images/solutions/request_logger_solution_3.png is excluded by !**/*.png
  • design_patterns/request_logger/images/solutions/request_logger_solution_4.png is excluded by !**/*.png
  • design_patterns/request_logger/images/solutions/request_logger_solution_5.png is excluded by !**/*.png
📒 Files selected for processing (4)
  • DIRECTORY.md
  • design_patterns/request_logger/README.md
  • design_patterns/request_logger/__init__.py
  • design_patterns/request_logger/test_request_logger.py
🧰 Additional context used
🧬 Code graph analysis (1)
design_patterns/request_logger/test_request_logger.py (1)
design_patterns/request_logger/__init__.py (2)
  • RequestLogger (4-23)
  • message_request_decision (12-23)
🪛 markdownlint-cli2 (0.18.1)
DIRECTORY.md

517-517: Unordered list indentation
Expected: 0; Actual: 2

(MD007, ul-indent)


518-518: Unordered list indentation
Expected: 2; Actual: 4

(MD007, ul-indent)

🔇 Additional comments (3)
DIRECTORY.md (1)

517-518: LGTM! Catalog entry follows existing conventions.

The new "Request Logger" entry is properly placed within the Pubsub > Simple Events section and follows the same indentation pattern as surrounding entries. The static analysis indentation warnings can be safely ignored as they don't account for the file's established conventions.

design_patterns/request_logger/test_request_logger.py (1)

26-39: LGTM! Well-structured parameterized tests.

The test implementation is clean and effective:

  • Proper use of parameterized testing to reduce duplication
  • Clear assertion messages that include timestamp and request for debugging
  • Type hints enhance readability and catch potential issues
design_patterns/request_logger/README.md (1)

19-21: All referenced image files exist. The 3 example images and 5 solution images are present in the repository, so the documentation links are valid.

@BrianLusina BrianLusina merged commit 5b7366c into main Jan 5, 2026
5 of 6 checks passed
@BrianLusina BrianLusina deleted the feat/design-request-logger-rate-limiter branch January 5, 2026 05:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Algorithm Algorithm Problem Datastructures Datastructures Design Documentation Documentation Updates enhancement Hash Map Hash Map Data structure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants