Skip to content

Instantly share code, notes, and snippets.

@nomisRev
Created May 31, 2021 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nomisRev/f7c34956a5e78f3cc1f937eae3a89c6b to your computer and use it in GitHub Desktop.
Save nomisRev/f7c34956a5e78f3cc1f937eae3a89c6b to your computer and use it in GitHub Desktop.
Postgres health check that checks buffer hit performance
data class HealthCheck(val heapRead: Long, val heapHit: Long, val ratio: Float)
suspend fun DataSource.databaseHealth(): HealthCheck? =
connection.use { conn ->
conn.createStatement()
.executeQuery(healthCheckQuery).use { rs ->
if (rs.next()) HealthCheck(
rs.getLong("heap_read"),
rs.getLong("heap_hit"),
rs.getFloat("ratio")
)
else null
}
}
/*
* heap_blks_read: Number of disk blocks read from this table in Long
* heap_blks_hit: Number of buffer hits in this table
* pg_statio_user_tables: Same as pg_stat_all_tables, except that only user tables are shown.
*
* Reference: https://www.craigkerstiens.com/2012/10/01/understanding-postgres-performance/
*/
private const val healthCheckQuery: String =
"""
SELECT
sum(heap_blks_read) as heap_read,
sum(heap_blks_hit) as heap_hit,
sum(heap_blks_hit) / (sum(heap_blks_hit) + sum(heap_blks_read)) as ratio
FROM
pg_statio_user_tables;
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment