Skip to content

Query caching #3165

Open
Open

Description

@daniellwdb

It would be nice if queries would get out of the box support for caching, it's a pain to make a wrapper since you'd have to make sure the function you create accepts and returns the right types. The syntax could be something like:

const users = await client.user.find({
  select: { x: true },
  where: { id },
  cache: true // defaults to y ms
})

// Custom time
const users = await client.user.find({
  select: { x: true },
  where: { id },
  cache: 60000 // cache for 1 minute / Maybe an options object for custom cache storage keys?
})

The cache could default to memory and a custom solution could be added in schema.prisma

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

datasource cache {
  provider = "redis"
  url      = env("CACHE_URL")
}

Any thoughts? I just read about the middleware API which maybe could be used under the hood to support this feature, manually caching there would cause duplicate code

Activity

  1. added
    kind/feature
    on Jul 29, 2020
  2. divyenduz commented on Jul 29, 2020

    @divyenduz

    Related discussion #3164 (reply in thread)

  3. AnandChowdhary commented on Nov 8, 2020

    @AnandChowdhary

    I'd also love to see an easy way to invalidate the cache, if this is implemented. For example:

    const users = await client.user.find({
      select: { x: true },
      where: { id },
      // Set a cache time of 1 minute and a key of "users-cache"
      cache: { time: 60000, key: "users-cache" }
    })

    Then, if you update a user, for example:

    await client.user.update({ where: { id }, data: { /* new user data */ } });
    // Invalidate the user cache
    await client.cache.invalidate("users-cache");

    This can probably even happen under the hood without explicit keys, because Prisma knows when user.update or user.delete are called, it can automatically invalidate any cache for user.find, etc. 🧠

  4. daniellwdb commented on Nov 8, 2020

    @daniellwdb
    Author

    @AnandChowdhary Seems like a nice addition, I hope this will gain more attention in the future, creating a custom solution using the new middlewares is a option but it adds a lot of repetitive code and abstraction

  5. changed the title [-]Request for query caching[/-] [+]Query caching[/+] on May 8, 2021
  6. JoelLefkowitz commented on Aug 3, 2021

    @JoelLefkowitz

    In order to cache effectively you need a centralised caching mechanism across all PrismaClient instances. I wrote a library to implement a cache as a static property rather than as middleware. This strips away a lot of the repetitive code as mentioned by @daniellwdb.

    https://github.com/JoelLefkowitz/cached-prisma

  7. franco-roura commented on Oct 1, 2021

    @franco-roura

    Would it be a terrible idea to cache the objects with JSON.stringify(obj) as a value and their table&id combination as a key?
    I'm thinking about something like

    Key Value
    user:5 "{ id: 5, name: \"Mr. Potato\" }"
    post:123 "{ id: 123, title: \"My first post\" }"

    Then we could invalidate that cached object by deleting the Redis key. What do you guys think?

  8. v0lume commented on Oct 28, 2021

    @v0lume

    any updates on this?

  9. casey-chow commented on Nov 3, 2021

    @casey-chow

    Would it be a terrible idea to cache the objects with JSON.stringify(obj) as a value and their table&id combination as a key? I'm thinking about something like
    Key Value
    user:5 "{ id: 5, name: \"Mr. Potato\" }"
    post:123 "{ id: 123, title: \"My first post\" }"

    Then we could invalidate that cached object by deleting the Redis key. What do you guys think?

    The main issue I've had with this is Date serialization--basically the serializer/deserializer needs some way to distinguish that type automatically.

  10. JoelLefkowitz commented on Dec 8, 2021

    @JoelLefkowitz

    Would it be a terrible idea to cache the objects with JSON.stringify(obj) as a value and their table&id combination as a key? I'm thinking about something like

    Key Value
    user:5 "{ id: 5, name: \"Mr. Potato\" }"
    post:123 "{ id: 123, title: \"My first post\" }"
    Then we could invalidate that cached object by deleting the Redis key. What do you guys think?

    This is the way I've implemented it except I've inverted the control of the cache read/update methods. This way the caching mechanism is configurable. This makes it compatible with Memcached and possible to test without a Redis instance.

    https://github.com/JoelLefkowitz/cached-prisma/blob/4ceec8b454456ebde688737be589bbbef42e7f58/src/prisma/prisma.ts#L68

    @casey-chow Do you think converting dates to ISO strings before serializing and deserializing would solve the problem? This would include traversing nested objects for date fields. I don't think there are any other types that Prisma handles which aren't capable of being serialized to JSON.

  11. casey-chow commented on Mar 8, 2022

    @casey-chow

    @casey-chow Do you think converting dates to ISO strings before serializing and deserializing would solve the problem? This would include traversing nested objects for date fields. I don't think there are any other types that Prisma handles which aren't capable of being serialized to JSON.

    So we have the following Prisma scalar types, and I've italicized all the datatypes not supported by JSON:

    Of these, the only one I actually use is DateTime but if the goal is to generalize I'm guessing everything but Unsupported would be needed. To this end I just settled on using msgpack because it has a built-in date serializer; the only popular serialization format that I've found that supports all these types is Amazon Ion.

  12. 5 remaining items

  13. songkeys commented on Nov 15, 2022

    @songkeys

    @TasinIshmam Great to hear this!

    Another team at Prisma is working on solving this problem in different ways (beyond the Prisma ORM) — especially for users of serverless environments.

    May I know why it is especially for serverless though?

  14. TasinIshmam commented on Nov 17, 2022

    @TasinIshmam

    Hey @songkeys

    With the design partner program, we're exploring solutions to problems that are acute in serverless environments. However, the query caching problem is not exclusive to serverless environments. We will also consider partners for the program even if they are not using serverless.

    Hope that clarifies things a bit.

  15. TiagoCavalcante commented on May 13, 2023

    @TiagoCavalcante

    Any news on this?

  16. JoelLefkowitz commented on May 13, 2023

    @JoelLefkowitz

    Any news on this?

    I can't seem to find anything on caching in the roadmap. Maybe it's included in this one: https://prismaio.notion.site/Optimize-Prisma-Client-Query-Performance-68caf089581e4d07ac154dd34ad73639

    I've had a couple people fork my repo but I dont think there has been any concrete plans from the Prisma team on what they plan to do.

  17. bsplosion commented on Oct 30, 2023

    @bsplosion

    Any news on this?

    I can't seem to find anything on caching in the roadmap. Maybe it's included in this one: https://prismaio.notion.site/Optimize-Prisma-Client-Query-Performance-68caf089581e4d07ac154dd34ad73639

    I've had a couple people fork my repo but I dont think there has been any concrete plans from the Prisma team on what they plan to do.

    I'm pretty confident that the comments from their team were alluding to the Prisma Accelerate system on their Prisma Data Platform.

    Unfortunately, while this sort-of solves the issue for a very specific class of users, the rest of us are going to have to still roll our own caching. Actual cache integrations are still not on their roadmap, and Prisma Accelerate seems to have taken priority since they actually produce revenue with it.

    Edit: also, Accelerate is unable to handle raw queries at this time which severely inhibits its utility for at least our use case. Many of the biggest, most-cacheable queries are actually done raw since they have advanced reporting and aggregations with results which are usually highly cacheable.

  18. janpio commented on Oct 31, 2023

    @janpio
    Contributor

    What kinds of "cache integrations" would you be looking for @bsplosion?
    I am not aware of any having been requested in the past.

    And no, the existence of a commercial product like Accelerate with its caching functionality does not mean we will not implement something in ORM directly if it is possible. A cloud-based caching service, which Accelerate is, unfortunately is not possible in an Open Source library as it includes an infrastructure component, though.

  19. bsplosion commented on Oct 31, 2023

    @bsplosion

    @janpio Sorry, I didn't mean to imply there's no chance that you and the team won't ever do something in the ORM directly, but it certainly does seem like Accelerate took priority from a resource perspective.

    Without speaking for everyone here, I'd say something like the Cached Prisma solution would be incredibly helpful:
    https://github.com/JoelLefkowitz/cached-prisma

    @JoelLefkowitz posted that here back in August 2021 and I think many of our requirements have remained unchanged. Ultimately, we'd want to define a cache engine and strategy at a similar level, with the option to use standard engines like Memcached or Redis (Joel's solution already integrated Memcached).

    There are of course a ton of considerations when caching, but frankly I don't think people would mind if those were largely presented as configuration options for the user to handle. The originally-proposed feature on this ticket with a cache invalidation strategy similar to Cached Prisma would probably work well for most as a start on the functionality.

    Separately, I've rolled my own caching stack in the past for other projects and just intercepted prepared statements, checking the cache with hashes of the query and parameters. However, that doesn't seem to be an option here since you can't easily "prepare" the statement about to be run in Prisma without using Prisma.sql for everything. Is there some way we could possibly use middleware for this? I can't seem to find a way to demarcate certain types of queries to provide the controls you'd really need from a caching perspective but perhaps I'm missing something.

  20. janpio commented on Oct 31, 2023

    @janpio
    Contributor

    Middlewares or Client Extensions indeed would be the right approaches to build something universal yourself. If you have use cases that are not covered by these (and I think you mean raw queries in your use case above), please open a new issue and we can figure out how to make that work - or if we need to build something.

    In general the desires and needs expressed in this issue are super diverse. There are many many approaches to caching that make this a pretty vast problem to tackle. You said yourself that "standard engines" already would include Memcached and Redis, and if you ask someone else there would be other storage mechanisms desired as well. When we start talking about the needed functionality and API we probably get even more options.

    One of them, a pretty opinionated one, was tackled by colleagues in the commercial side of Prisma with Prisma Accelerate as a hosted infrastructure component.

  21. self-assigned this
    on Jun 13, 2024
  22. janpio commented on Jun 13, 2024

    @janpio
    Contributor

    What kind of API or configuration would you expect or wish for? The examples above show an API to cache individual queries with a duration as a named cache, and a way to invalidate individual named caches.

  23. KhaoDoesDev commented on Jun 13, 2024

    @KhaoDoesDev

    This could have the same caching system from Prisma Accelerate.

  24. removed their assignment
    on Nov 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions