Skip to content

Commit d8e9c4e

Browse files
committed
perf: Add semaphore to limit threads using the pool
1 parent 35de13e commit d8e9c4e

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/PostgREST/AppState.hs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ import Protolude
7979
data AppState = AppState
8080
-- | Database connection pool
8181
{ statePool :: SQL.Pool
82+
-- | Semaphore to limit threads using the pool
83+
, statePoolSemaphore :: QSem
8284
-- | Database server version
8385
, statePgVersion :: IORef PgVersion
8486
-- | Schema cache
@@ -133,10 +135,11 @@ init conf@AppConfig{configLogLevel, configDbPoolSize} = do
133135
pure state' { stateSocketREST = sock, stateSocketAdmin = adminSock}
134136

135137
initWithPool :: AppSockets -> SQL.Pool -> AppConfig -> Logger.LoggerState -> Metrics.MetricsState -> ObservationHandler -> IO AppState
136-
initWithPool (sock, adminSock) pool conf loggerState metricsState observer = do
138+
initWithPool (sock, adminSock) pool conf@AppConfig{configDbPoolSize} loggerState metricsState observer = do
137139

138140
appState <- AppState pool
139-
<$> newIORef minimumPgVersion -- assume we're in a supported version when starting, this will be corrected on a later step
141+
<$> newQSem configDbPoolSize
142+
<*> newIORef minimumPgVersion -- assume we're in a supported version when starting, this will be corrected on a later step
140143
<*> newIORef Nothing
141144
<*> newIORef SCPending
142145
<*> newIORef False
@@ -216,7 +219,7 @@ usePool :: AppState -> SQL.Session a -> IO (Either SQL.UsageError a)
216219
usePool AppState{stateObserver=observer, stateMainThreadId=mainThreadId, ..} sess = do
217220
observer PoolRequest
218221

219-
res <- SQL.use statePool sess
222+
res <- bracket_ (waitQSem statePoolSemaphore) (signalQSem statePoolSemaphore) (SQL.use statePool sess)
220223

221224
observer PoolRequestFullfilled
222225

0 commit comments

Comments
 (0)