public inbox for [email protected]  
help / color / mirror / Atom feed
From: Yura Sokolov <[email protected]>
To: Zixuan Fu <[email protected]>
To: [email protected]
Subject: Re: Optimize scram_SaltedPassword performance
Date: Mon, 3 Feb 2025 10:45:49 +0300
Message-ID: <[email protected]> (raw)
In-Reply-To: <Z6BsNAadbID+k2L4@bass1>
References: <Z6BsNAadbID+k2L4@bass1>

03.02.2025 10:11, Zixuan Fu пишет:
> Hi Hackers,  
> 
> While profiling a program with `perf`, I noticed that `scram_SaltedPassword`
> consumed more CPU time than expected. After some investigation, I found
> that the function performs many HMAC iterations (4096 rounds for
> SCRAM-SHA-256), and each iteration reinitializes the HMAC context, causing
> excessive overhead.
> 
> OpenSSL has an optimization for this case: when the key remains the
> same, the HMAC context can be reused with a lightweight state reset by
> passing NULL as the key. To take advantage of this, I introduced
> `pg_hmac_reuse()`, which replaces the key with NULL when OpenSSL is used.

Good catch.

Since pg_hmac_reuse is not `static`, I'd add some checks that key is
exactly same. At least there should be

   Assert(key == prev_key && len == prev_len && hash_bytes(key, len) ==
prev_hash);

Where `prev_key`, `prev_len` and `prev_hash` are static variables, filled
in `pg_hmac_init`.

I don't know, should it be `Assert`, or check that leads to `elog(ERROR)`.

`hash_bytes` is fast enough to not cause measurable slow down in production.

On the other hand, use cases are trivial enough to occasional misuses to be
caught using just `Assert`.

> With this change, the performance improves by approximately **4x** (reducing
> execution time from 4ms to 1ms). The built-in PostgreSQL HMAC implementation
> does not support context reuse, and modifying it would require substantial
> changes. Therefore, `pg_hmac_reuse()` simply calls `pg_hmac_init()` in that
> case, maintaining the existing logic.

-------

regards,
Yura






view thread (4+ messages)  latest in thread

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected]
  Subject: Re: Optimize scram_SaltedPassword performance
  In-Reply-To: <[email protected]>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox