sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

Cache Client Key for PostgreSQL SASL

Open ThomWright opened this issue 3 months ago • 3 comments

I have found these related issues/pull requests

Relates to #4005

Description

SCRAM-SHA-256 is slow and expensive, especially when the number of iterations is high (the default is 4096).

Prefered solution

According to the SCRAM-SHA-256 RFC:

This computational cost can be avoided by caching the ClientKey (assuming the Salt and hash iteration-count is stable).

Could we consider caching this to prevent the expensive hashing every time we open a connection?

Even if we've potentially mitigated the event loop blocking in #4006, it's still a high price to pay in terms of extra latency.

I haven't looked in detail, but I suspect it would need a fair amount of refactoring, since we'd need to keep this cache somewhere to be reused between opening connections, and pass it down to the SASL implementation.

Is this a breaking change? Why or why not?

Hopefully not. Ideally we'll keep the caching transparent.

ThomWright avatar Sep 22 '25 12:09 ThomWright

We could store it in the PgConnectOptions along with the salt and iteration count. We just need to be careful to invalidate it if any of these things change:

  • hostname
  • port
  • database
  • username
  • password
  • salt
  • iteration count

abonander avatar Sep 23 '25 23:09 abonander

I was thinking similarly. Storing it in PgConnectOptions felt a bit weird but I couldn't see anywhere else.

I'll try to find some time to put a PR together.

ThomWright avatar Sep 26 '25 15:09 ThomWright

@abonander I added a PR, let me know what you think!

ThomWright avatar Oct 06 '25 09:10 ThomWright