CYBERTEC Logo

Optimizing PostgreSQL functions with preloaded libraries

01.2024 / Category: / Tags: |

In PostgreSQL, functions and procedures can be written in many different programming languages including but not limited to PL/pgSQL, PL/Perl, PL/Python and a lot more. This flexibility gives the end user the choice to write code in languages of their choice. However, this flexibility has some implications which are often forgotten. Loading libraries early is one of them.

Executing functions and procedures in PostgreSQL

To understand how PostgreSQL works, we first got to take a look at a simple function call. The next listing shows some simple PostGIS code:

In a standard PostgreSQL database connection, PostGIS is not available yet. In fact, it has to be loaded when PostGIS is used for the first time inside a connection. What we see is that the second call is WAY faster than the first one because during the first call the library is loaded and initialized. After a database restart the first can be a major performance problem. Consider: After a restart caches are cold, libraries are not yet loaded and the connections have to be established - this can cause a fairly nasty cocktail of issues which all happen at the same time.

Loading libraries early

One way to address the problem is to make use of a fairly old feature in PostgreSQL: The session_preload_library can ensure that the library is already there when the connection is used for the first time. Of course we will see some serious performance improvements:

The first call is way faster than before. The second call is still a lot slower than the first invocation because we still have to do some init work. However, we have shaved off a fair amount of overhead for the first call which can be incredibly beneficial in case of reboots, cluster failures and so on.

Conclusion

All server side languages are loaded as libraries and the same is true for extensions and many others things. session_preload_libraries can therefore be really helpful to speed up the first call inside a database connection.

Read more about optimization in PostgreSQL.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
CYBERTEC Logo white
CYBERTEC PostgreSQL International GmbH
Römerstraße 19
2752 Wöllersdorf
Austria

+43 (0) 2622 93022-0
office@cybertec.at

Get the newest PostgreSQL Info & Tools


    This site is protected by reCAPTCHA and the Google Privacy Policy & Terms of Service apply.

    ©
    2024
    CYBERTEC PostgreSQL International GmbH
    phone-handsetmagnifiercrosscross-circle
    0
    Would love your thoughts, please comment.x
    ()
    x
    linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram