Skip to content

[WIP] - Implementing connection pooling #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

lucifercr07
Copy link

@lucifercr07 lucifercr07 commented Apr 2, 2025

Connection pooling implementation

  • The pool should maintain a fixed number of connections (e.g. 10) each database instance(host:port).
  • When all connections in the pool are in use, we create a temporary connection and return to the application. That connection is put back in pool if required else closed.

TODO

  • Add tests
  • Add WithMaxConnections as option so that it can be defined once when connection is init first time via SDK. Currently fixed to 10.
  • Watch connection restricted to 1 connection per application for now
  • Skipped minimum connection pool per DB instance for now
  • Async refresh connection pool i.e. validate connections are valid and not stale. If stale invalidate.

Summary by CodeRabbit

  • New Features

    • Introduced an enhanced connection pooling mechanism, improving network performance and stability with more robust error handling and automatic retries.
  • Chores

    • Updated repository management by excluding IDE-specific configuration files for a cleaner codebase.

Copy link

coderabbitai bot commented Apr 2, 2025

Walkthrough

This update introduces a connection pooling mechanism in the main application file and refines the client connection management. The changes replace the previous single connection approach with a more robust, pooled model that manages network connections using a dedicated pool structure, mutexes, and channels. In addition, basic error handling improvements and retry logic are integrated. A new entry is also added to the .gitignore file to exclude IDE-specific configuration directories.

Changes

File Change Summary
.gitignore Added entry to ignore the .idea/ directory, excluding IDE settings from version control.
main.go Introduced connection pooling with a new constant (poolSize), sync.Map for pools, and a mutex. Modified Client to include host and port. Added a new pool struct and associated functions (getPoolKey, getOrCreatePool, leaseConnectionFromPool, returnToConnectionPool), and updated the fire, Fire, and reconnection logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant PoolManager as Pool
    participant Conn as Connection

    Client->>PoolManager: Request connection (getOrCreatePool)
    PoolManager-->>Client: Return pooled connection (leaseConnectionFromPool)
    Client->>Conn: Execute command (fire)
    Conn-->>Client: Return response
    Client->>PoolManager: Return connection to pool (returnToConnectionPool)
Loading

Poem

I'm just a rabbit in the land of code,
Hopping through connections on a new, improved road 🐰.
Pools now keep my traffic neat,
Ensuring every command is sweet.
My whiskers twitch with debugging cheer,
Celebrating changes that bring performance near!
Hop along – the flow is crystal clear!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Copy link

@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 (9)
main.go (9)

17-19: Consider making poolSize configurable.

Currently, the maximum connection limit is hardcoded to 10. You mentioned a future plan for a WithMaxConnections option; implementing that now or adding a placeholder config would improve flexibility.


21-24: Evaluate the use of sync.Map vs. a standard map with a mutex.

sync.Map can be beneficial for certain concurrent use cases, but in some scenarios, a well-structured map protected by a single mutex might be simpler and perform better. Consider verifying if the read-mostly patterns of sync.Map apply here.


27-29: Inconsistent naming of exported vs. unexported fields.

Id is exported, whereas host and port are not. If they are intended to be read outside this package, consider capitalizing them. Otherwise, consider making Id unexported for consistency.


34-36: Ensure concurrency access to pool fields is handled consistently.

pool.mu protects p.available, but you may need additional documentation or checks for other fields like host and port to avoid race conditions.


78-109: Improve error messaging in NewClient.

When the handshake fails, you return a generic error message. Consider adding context about the host/port to simplify debugging.


170-184: Ensure consistent connection closure handling.

Returning a connection to the pool or closing it is correct, but consider factoring logging for these events to a structured logger instead of fmt.Println for production readiness.


186-205: Synchronized fire might degrade throughput.

A single fireCmdMutex gating all command writes can become a bottleneck. Consider using per-connection synchronization or a more granular approach if throughput becomes a concern.


233-235: Avoid repeatedly calling io.EOF.Error().

Repeatedly allocating the string from io.EOF.Error() can be replaced with a constant if performance is critical. The current approach is fine, but it’s a minor optimization.


294-309: Logging approach in checkAndReconnect.

Using fmt.Println for error reporting and reconnection status is workable for development. For production, consider switching to a structured logger or a dedicated logging library.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5c680 and bea3792.

📒 Files selected for processing (2)
  • .gitignore (1 hunks)
  • main.go (6 hunks)
🔇 Additional comments (6)
.gitignore (1)

1-1: Add IDE directory to .gitignore.

This addition is appropriate to keep JetBrains IDE settings out of version control.

main.go (5)

43-45: Key generation logic appears sound.

Combining host and port via fmt.Sprintf("%s:%d", host, port) provides a clear unique identifier.


47-61: Validate pool creation workflow.

The LoadOrStore approach is safe for concurrency. Just ensure that external calls (e.g., potential expansions to warm connections) remain mutually coherent when multiple goroutines call getOrCreatePool concurrently.


111-168: Examine concurrency under load.

Multiple goroutines calling leaseConnectionFromPool can trigger concurrent logic (e.g., line 133 capacity checks). The locking strategy seems correct, but concurrency load tests would ensure no race conditions or channel contention.

Would you like to generate a shell script to grep for concurrency tests and highlight any potential coverage gaps?


206-231: Single retry logic in Fire.

Retriable connection errors are only retried once. This is likely sufficient, but confirm if users need more robust retry or backoff strategies for high-availability scenarios.


326-330: Watch connection closure.

You correctly set c.watchConn = nil after closing it, preventing double closure issues. The overall resource cleanup is good.

@lucifercr07 lucifercr07 changed the title Implementing connection pooling [WIP] - Implementing connection pooling Apr 3, 2025
Copy link

@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 (8)
main.go (8)

17-20: Make the pool size configurable.

Currently, poolSize is hardcoded to 10. It would be beneficial to introduce a WithMaxConnections(int) option or similar approach to make this limit user-configurable.


34-40: Consider additional fields or structures for pool management.

The pool struct effectively manages concurrent usage. For advanced scenarios like minimum pools or async refreshes, consider extra state or channels for staleness checks, as noted in the PR objectives.


85-99: Releasing the connection immediately after creation might reduce reuse benefits.

In NewClient, you lease a connection but immediately defer returning it. Consider persisting a dedicated connection if you want each client to maintain a persistent channel to the pool.


101-144: Connection leasing logic is sound, but consider a blocking wait or backoff option.

Right now, if no connection is available, you immediately attempt to create a new one (if the pool isn't at capacity). Optionally, a short blocking interval or exponential backoff could help manage spikes in demand.


146-215: Handshake code is repeated; consider a shared handshake function.

You handle handshakes in multiple places. A single helper (e.g., performHandshake(conn, clientID, mode)) could reduce duplication and improve maintainability.


237-290: Retry logic in Fire is a good start, could be expanded.

The single retry is helpful, but a loop or backoff might better handle sporadic network issues. If repeated attempts fail, you could provide clearer error messaging.


327-333: Consider centralizing handshake logic for watch connections.

You repeat the handshake approach for watch flows. A unified handshake helper could reduce duplication.


347-387: Reconnect logic is functional, but adding backoff could improve resilience.

If repeated errors occur, using an exponential backoff strategy helps prevent tight reconnect loops.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bea3792 and 093b781.

📒 Files selected for processing (1)
  • main.go (6 hunks)
🔇 Additional comments (9)
main.go (9)

22-24: Use of sync.Map looks good.

Storing pools keyed by host and port in a concurrent map is appropriate for thread-safe lookups and updates.


27-32: Initialization of new Client fields is clear.

Exposing Id publicly and adding host / port fields match the new connection pooling design.


42-45: pooledConn structure is concise.

Storing the last client ID helps ensure proper re-handshakes when reusing connections.


49-51: Key generation for host/port is straightforward.

This approach reliably identifies a unique pool per host and port.


53-68: Creating or retrieving the pool is well-handled.

The usage of LoadOrStore ensures thread-safe pool retrieval or creation. Keep in mind any cleanup strategy for stale or unused pools if needed.


217-235: Effective strategy for returning or closing connections.

Closing connections when the pool is full avoids resource leaks. However, if usage spikes temporarily, disposing of connections might be suboptimal. Consider waiting in a queue or tracking connection usage patterns.


292-294: Connection error checks are straightforward.

Validating EOF or EPIPE covers typical broken-pipe scenarios.


318-320: Allocating a dedicated watch connection bypasses the pool.

This may be intentional, but verify if you want watchers to also leverage the pool for consistency.


390-393: Closing the watch connection is clean.

Explicitly closing watchConn prevents resource leaks. This approach is consistent with the rest of the design.

@mintobit
Copy link
Contributor

@lucifercr07 sounds interesting. You'll have to pull latest changes though, since we changed implementation of creating a connection

@lucifercr07
Copy link
Author

@lucifercr07 sounds interesting. You'll have to pull latest changes though, since we changed implementation of creating a connection

@mintobit will rebase the PR with new changes and update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants