Skip to content

Commit

Permalink
Set limits on the number and lifetime of connections. (#725)
Browse files Browse the repository at this point in the history
  • Loading branch information
timburks authored Sep 6, 2022
1 parent 8e82f10 commit 86315f3
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions server/registry/internal/storage/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package storage
import (
"context"
"fmt"
"time"

_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/postgres"
"github.com/apigee/registry/server/registry/internal/storage/models"
Expand Down Expand Up @@ -63,6 +64,11 @@ func NewClient(ctx context.Context, driver, dsn string) (*Client, error) {
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
if err := applyConnectionLimits(db); err != nil {
c := &Client{db: db}
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
return &Client{db: db}, nil
case "postgres", "cloudsqlpostgres":
db, err := gorm.Open(postgres.New(postgres.Config{
Expand All @@ -76,12 +82,30 @@ func NewClient(ctx context.Context, driver, dsn string) (*Client, error) {
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
if err := applyConnectionLimits(db); err != nil {
c := &Client{db: db}
c.close()
return nil, grpcErrorForDBError(ctx, err)
}
return &Client{db: db}, nil
default:
return nil, fmt.Errorf("unsupported database %s", driver)
}
}

// Applies limits to concurrent connections.
// Could be made configurable.
func applyConnectionLimits(db *gorm.DB) error {
sqlDB, err := db.DB()
if err != nil {
return err
}
sqlDB.SetMaxOpenConns(10)
sqlDB.SetMaxIdleConns(10)
sqlDB.SetConnMaxLifetime(60 * time.Second)
return nil
}

// Close closes a database session.
func (c *Client) Close() {
c.close()
Expand Down

0 comments on commit 86315f3

Please sign in to comment.