Caching results
If your gallery SQL query is run every time a user performs a search or loads a gallery, it's going to cripple your database server fairly fast given the scale of said query. Caching results helps to massively reduce load on your database server, and for it to be effective, you need cacheĀ hits to be fairly high, which in practice means you need to avoid caching overly specific data.
The biggest pitfall here is returning data that's specific to the requesting user. For example, if your SQL query checks a list of users the requesting user has blocked, you can't cache that query for anyone except the requesting user, as it will only be correct for their block list.