Skip to content

Comments

chore: Implement short-lived redis cache for slots#22787

Merged
ThyMinimalDev merged 29 commits intomainfrom
chore/shortlived-slots-cache
Aug 5, 2025
Merged

chore: Implement short-lived redis cache for slots#22787
ThyMinimalDev merged 29 commits intomainfrom
chore/shortlived-slots-cache

Conversation

@emrysal
Copy link
Contributor

@emrysal emrysal commented Jul 29, 2025

What does this PR do?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 29, 2025

Walkthrough

This change introduces Redis caching for available slots within the application. It adds a Redis service implementation with connection status tracking, connection lifecycle event logging, error handling, and common Redis operations such as get, set (with optional TTL), del, expire, lrange, and lpush. A no-operation Redis service stub is added as a fallback when Redis environment variables are not configured. Dependency injection tokens and modules are updated to support the new Redis service, including conditional binding to either the real or noop Redis service. The AvailableSlotsService is refactored to accept a Redis client and now utilizes Redis caching for slot availability queries, with cache keys derived from input arguments and a configurable TTL via an environment variable. Minor formatting and dependency version updates are also included.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Complexity arises from the introduction of new caching logic, Redis client enhancements, and dependency injection changes across multiple files and layers.
  • Reviewers will need to verify correct integration of Redis, cache key generation, TTL handling, connection readiness checks, and safe fallback behavior.
  • Supporting changes (noop service, DI tokens, and module wiring) are straightforward but require attention to ensure consistency.
  • No high-risk refactoring or large-scale logic changes are present, keeping the review effort moderate.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 59903d9 and d279e9a.

📒 Files selected for processing (1)
  • apps/api/v2/test/setEnvVars.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/api/v2/test/setEnvVars.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/shortlived-slots-cache

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@vercel
Copy link

vercel bot commented Jul 29, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Aug 5, 2025 5:09pm
cal-eu ⬜️ Ignored (Inspect) Aug 5, 2025 5:09pm

@socket-security
Copy link

socket-security bot commented Jul 29, 2025

All alerts resolved. Learn more about Socket for GitHub.

This PR previously contained dependency changes with security issues that have been resolved, removed, or ignored.

View full report

@emrysal emrysal marked this pull request as ready for review July 31, 2025 13:27
@emrysal emrysal requested a review from a team as a code owner July 31, 2025 13:27
@emrysal emrysal requested a review from a team July 31, 2025 13:27
@dosubot dosubot bot added the api area: API, enterprise API, access token, OAuth label Jul 31, 2025
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: 1

🧹 Nitpick comments (2)
packages/features/redis/di/redisModule.ts (1)

10-16: LGTM! Graceful fallback pattern is well implemented.

The factory function correctly provides graceful degradation from RedisService to NoopRedisService when Redis is unavailable. The singleton binding ensures consistent behavior across the application.

Consider adding optional error logging to aid debugging in production environments:

redisModule.bind(DI_TOKENS.REDIS_CLIENT).toFactory(() => {
  try {
    return new RedisService();
-  } catch (error) {}
+  } catch (error) {
+    // Optional: Log for debugging in production
+    // console.warn("Redis unavailable, falling back to noop service:", error);
+  }
  // or fall back to a noop service if Redis is not available
  return new NoopRedisService();
}, "singleton");
packages/trpc/server/routers/viewer/slots/util.ts (1)

139-139: Consider making TTL configurable

The hardcoded 2-second TTL might not be optimal for all scenarios. Consider making this configurable through environment variables or service configuration.

-    redisClient.set(cacheKey, result, { ttl: 2000 }); // Cache for 2 seconds
+    const ttl = process.env.SLOTS_CACHE_TTL_MS ? parseInt(process.env.SLOTS_CACHE_TTL_MS) : 2000;
+    redisClient.set(cacheKey, result, { ttl }); // Cache with configurable TTL
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ef66187 and f409cc5.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (12)
  • apps/api/v2/src/lib/modules/available-slots.module.ts (2 hunks)
  • apps/api/v2/src/lib/services/available-slots.service.ts (3 hunks)
  • apps/api/v2/src/modules/redis/redis.service.ts (2 hunks)
  • apps/web/package.json (1 hunks)
  • packages/features/redis/IRedisService.d.ts (1 hunks)
  • packages/features/redis/NoopRedisService.ts (1 hunks)
  • packages/features/redis/RedisService.ts (2 hunks)
  • packages/features/redis/di/redisModule.ts (1 hunks)
  • packages/lib/di/containers/available-slots.ts (2 hunks)
  • packages/lib/di/modules/available-slots.ts (1 hunks)
  • packages/lib/di/tokens.ts (1 hunks)
  • packages/trpc/server/routers/viewer/slots/util.ts (4 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • apps/api/v2/src/lib/modules/available-slots.module.ts
  • packages/lib/di/containers/available-slots.ts
  • packages/lib/di/tokens.ts
  • packages/lib/di/modules/available-slots.ts
  • apps/api/v2/src/lib/services/available-slots.service.ts
  • packages/features/redis/RedisService.ts
  • packages/features/redis/di/redisModule.ts
  • packages/features/redis/IRedisService.d.ts
  • packages/trpc/server/routers/viewer/slots/util.ts
  • packages/features/redis/NoopRedisService.ts
  • apps/api/v2/src/modules/redis/redis.service.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • apps/api/v2/src/lib/modules/available-slots.module.ts
  • packages/lib/di/containers/available-slots.ts
  • packages/lib/di/tokens.ts
  • packages/lib/di/modules/available-slots.ts
  • apps/api/v2/src/lib/services/available-slots.service.ts
  • packages/features/redis/RedisService.ts
  • packages/features/redis/di/redisModule.ts
  • packages/features/redis/IRedisService.d.ts
  • packages/trpc/server/routers/viewer/slots/util.ts
  • packages/features/redis/NoopRedisService.ts
  • apps/api/v2/src/modules/redis/redis.service.ts
**/*.{service,repository}.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Avoid dot-suffixes like .service.ts or .repository.ts for new files; reserve .test.ts, .spec.ts, .types.ts for their specific purposes

Files:

  • apps/api/v2/src/lib/services/available-slots.service.ts
  • apps/api/v2/src/modules/redis/redis.service.ts
**/*Service.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Service files must include Service suffix, use PascalCase matching exported class, and avoid generic names (e.g., MembershipService.ts)

Files:

  • packages/features/redis/RedisService.ts
  • packages/features/redis/NoopRedisService.ts
🧠 Learnings (4)
📚 Learning: in the failedbookingsbyfield component (packages/features/insights/components/failedbookingsbyfield....
Learnt from: eunjae-lee
PR: calcom/cal.com#22106
File: packages/features/insights/components/FailedBookingsByField.tsx:65-71
Timestamp: 2025-07-15T12:59:34.389Z
Learning: In the FailedBookingsByField component (packages/features/insights/components/FailedBookingsByField.tsx), although routingFormId is typed as optional in useInsightsParameters, the system automatically enforces a routing form filter, so routingFormId is always present in practice. This means the data always contains only one entry, making the single-entry destructuring approach safe.

Applied to files:

  • packages/lib/di/modules/available-slots.ts
📚 Learning: applies to **/*repository.ts : repository files must include `repository` suffix, prefix with techno...
Learnt from: CR
PR: calcom/cal.com#0
File: .cursor/rules/review.mdc:0-0
Timestamp: 2025-07-28T11:50:23.946Z
Learning: Applies to **/*Repository.ts : Repository files must include `Repository` suffix, prefix with technology if applicable (e.g., `PrismaAppRepository.ts`), and use PascalCase matching the exported class

Applied to files:

  • apps/api/v2/src/lib/services/available-slots.service.ts
📚 Learning: the office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is spec...
Learnt from: vijayraghav-io
PR: calcom/cal.com#21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.

Applied to files:

  • packages/trpc/server/routers/viewer/slots/util.ts
📚 Learning: in the insightsbookingservice (packages/lib/server/service/insightsbooking.ts), the constructor stor...
Learnt from: eunjae-lee
PR: calcom/cal.com#22702
File: packages/lib/server/service/insightsBooking.ts:120-124
Timestamp: 2025-07-24T08:39:06.185Z
Learning: In the InsightsBookingService (packages/lib/server/service/insightsBooking.ts), the constructor stores null for invalid options or filters but this is handled safely through null checks in buildFilterConditions() and buildAuthorizationConditions() methods. The service uses defensive programming to return safe fallback conditions (null or NOTHING_CONDITION) rather than throwing errors on invalid inputs.

Applied to files:

  • packages/trpc/server/routers/viewer/slots/util.ts
🧬 Code Graph Analysis (5)
apps/api/v2/src/lib/modules/available-slots.module.ts (1)
packages/features/redis/RedisService.ts (1)
  • RedisService (5-46)
packages/lib/di/containers/available-slots.ts (2)
packages/lib/di/tokens.ts (1)
  • DI_TOKENS (1-30)
packages/features/redis/di/redisModule.ts (1)
  • redisModule (18-18)
packages/lib/di/modules/available-slots.ts (1)
packages/lib/di/tokens.ts (1)
  • DI_TOKENS (1-30)
apps/api/v2/src/lib/services/available-slots.service.ts (1)
packages/features/redis/RedisService.ts (1)
  • RedisService (5-46)
packages/features/redis/NoopRedisService.ts (1)
packages/features/redis/IRedisService.d.ts (1)
  • IRedisService (1-13)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Tests / Unit
  • GitHub Check: Linters / lint
  • GitHub Check: Type check / check-types
🔇 Additional comments (23)
apps/web/package.json (1)

82-82: No breaking changes or security advisories detected for @upstash/redis v1.21.0 → v1.35.2

  • Checked GitHub release notes from v1.21.0 through v1.35.2 for “BREAKING” changes: none found.
  • Queried NPM security advisories for @upstash/redis: no vulnerabilities reported.

This dependency bump can be merged as-is.

packages/lib/di/tokens.ts (1)

5-5: LGTM!

The new REDIS_CLIENT token follows the established pattern and naming convention. The addition is consistent with the existing dependency injection structure.

apps/api/v2/src/lib/modules/available-slots.module.ts (2)

12-12: LGTM!

Proper import of RedisService following the established module import pattern.


26-26: LGTM!

Correctly adds RedisService to the providers array, making it available for dependency injection within the module.

packages/lib/di/containers/available-slots.ts (2)

3-3: LGTM!

Proper import of redisModule following the established import pattern for DI modules.


20-20: LGTM!

Correctly loads the Redis module into the container using the appropriate DI token. The placement follows the logical sequence with other module loadings.

packages/lib/di/modules/available-slots.ts (1)

18-18: LGTM!

Properly adds the Redis client dependency binding following the established pattern. The satisfies constraint ensures type safety with the service interface.

apps/api/v2/src/lib/services/available-slots.service.ts (2)

9-9: LGTM! Redis service import is correctly added.

The import follows the established pattern and correctly references the RedisService from the NestJS modules directory.


25-27: LGTM! Redis service dependency injection is properly implemented.

The constructor correctly accepts the RedisService parameter and passes it to the base class as redisClient, enabling Redis caching functionality for available slots.

Also applies to: 37-37

packages/features/redis/IRedisService.d.ts (1)

4-4: LGTM! TTL support added to the set method interface.

The optional opts parameter with ttl property enables time-to-live functionality while maintaining backward compatibility. This aligns with the PR objective of implementing short-lived Redis cache.

packages/features/redis/RedisService.ts (2)

9-12: LGTM! Request timeout configuration improves reliability.

Adding a 2-second timeout prevents hanging Redis requests and improves service reliability. The timeout value is appropriate for Redis operations.


22-32: LGTM! TTL implementation correctly uses Redis PX option.

The set method properly implements TTL support using the px option for millisecond precision. The conditional logic ensures TTL is only applied when provided, maintaining backward compatibility.

packages/features/redis/NoopRedisService.ts (1)

7-32: LGTM! Noop implementation provides safe fallback behavior.

The NoopRedisService correctly implements the IRedisService interface with appropriate default return values. The unused parameter prefixes and clear documentation make the intent obvious. This provides a safe fallback when Redis is unavailable without breaking dependent code.

packages/trpc/server/routers/viewer/slots/util.ts (3)

11-11: LGTM - Clean import addition

The import of IRedisService type is correctly placed and follows the existing import pattern.


95-105: Interface reordering and Redis client addition looks good

The addition of redisClient: IRedisService to the interface is appropriate for dependency injection. The reordering of checkBookingLimitsService above redisClient maintains consistency.


925-928: Clean integration of caching with reporting

The wrapping of _getAvailableSlots with both withSlotsCache and withReporting follows a good composition pattern. The order ensures caching happens before reporting, which is appropriate.

apps/api/v2/src/modules/redis/redis.service.ts (7)

10-10: Good addition of connection status tracking

Adding isReady to track connection status is a good practice for preventing operations on disconnected clients.


18-35: Comprehensive connection event handling

The event handlers provide good visibility into Redis connection state and properly update the isReady flag. The logging levels are appropriate for each event type.


46-67: Robust get method with good error handling

The implementation properly checks connection status, handles errors gracefully, and attempts JSON parsing with fallback to raw data. The type safety with generics is well implemented.


69-79: Clean del method implementation

The delete method follows the same pattern as get with proper error handling and connection status checking.


81-99: Well-implemented set method with TTL support

The set method properly handles both object and primitive types, supports optional TTL using Redis PX (milliseconds), and includes comprehensive error handling.


101-111: Clean expire method implementation

The expire method follows the established pattern with proper error handling and type safety.


113-139: List operations implemented correctly

Both lrange and lpush methods handle JSON serialization/deserialization appropriately and follow the same error handling pattern as other methods. The automatic JSON parsing in lrange assumes all list items are JSON, which is reasonable for this use case.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 31, 2025

E2E results are ready!

@btwitsPratyush
Copy link

What does this PR do?

lol

Copy link

@btwitsPratyush btwitsPratyush left a comment

Choose a reason for hiding this comment

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

changes look good overall. good to merge once tested.

Copy link

@btwitsPratyush btwitsPratyush left a comment

Choose a reason for hiding this comment

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

its good to go i guess

EventType,
GetAvailabilityUser,
UserAvailabilityService,
IUserAvailabilityService,
Copy link
Contributor

Choose a reason for hiding this comment

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

needs to be UserAvailabilityService

@ThyMinimalDev ThyMinimalDev enabled auto-merge (squash) August 5, 2025 17:29
@ThyMinimalDev ThyMinimalDev merged commit b71d8ba into main Aug 5, 2025
37 checks passed
@ThyMinimalDev ThyMinimalDev deleted the chore/shortlived-slots-cache branch August 5, 2025 17:32
"@calcom/platform-constants": "*",
"@calcom/platform-enums": "*",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.283",
"@calcom/platform-libraries": "npm:@calcom/platform-libraries@0.0.284",

Choose a reason for hiding this comment

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

how can it after anyhow?

@sentry
Copy link

sentry bot commented Aug 6, 2025

Suspect Issues

This pull request was deployed and Sentry observed the following issues:

Did you find this useful? React with a 👍 or 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api area: API, enterprise API, access token, OAuth core area: core, team members only foundation ready-for-e2e

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants