perf: use LRU cache for getServerSession (#8339)

* chore: add lru package

* feat: use LRU cache

* fix: type

* Updates package json

---------

Co-authored-by: zomars <zomars@me.com>
pull/8360/head
Nafees Nazik 2023-04-18 07:25:01 +05:30 committed by GitHub
parent 597b14cf4c
commit f467bb7957
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 8 deletions

View File

@ -1,3 +1,4 @@
import { LRUCache } from "lru-cache";
import type { GetServerSidePropsContext, NextApiRequest, NextApiResponse } from "next";
import type { AuthOptions, Session } from "next-auth";
import { getToken } from "next-auth/jwt";
@ -9,13 +10,8 @@ import prisma from "@calcom/prisma";
/**
* Stores the session in memory using the stringified token as the key.
*
* This is fine for production as each lambda will be recycled before this
* becomes large enough to cause issues.
*
* If we want to get extra spicy we could store this in edge config or similar
* so we can TTL things and benefit from faster retrievals than prisma.
*/
const UNSTABLE_SESSION_CACHE = new Map<string, Session>();
const CACHE = new LRUCache<string, Session>({ max: 1000 });
/**
* This is a slimmed down version of the `getServerSession` function from
@ -44,7 +40,7 @@ export async function getServerSession(options: {
return null;
}
const cachedSession = UNSTABLE_SESSION_CACHE.get(JSON.stringify(token));
const cachedSession = CACHE.get(JSON.stringify(token));
if (cachedSession) {
return cachedSession;
@ -79,7 +75,7 @@ export async function getServerSession(options: {
},
};
UNSTABLE_SESSION_CACHE.set(JSON.stringify(token), session);
CACHE.set(JSON.stringify(token), session);
return session;
}

View File

@ -14,6 +14,7 @@
"bcryptjs": "^2.4.3",
"handlebars": "^4.7.7",
"jose": "^4.13.1",
"lru-cache": "^9.0.3",
"next-auth": "^4.20.1",
"nodemailer": "^6.7.8",
"otplib": "^12.0.1"

View File

@ -4332,6 +4332,7 @@ __metadata:
bcryptjs: ^2.4.3
handlebars: ^4.7.7
jose: ^4.13.1
lru-cache: ^9.0.3
next-auth: ^4.20.1
nodemailer: ^6.7.8
otplib: ^12.0.1
@ -27369,6 +27370,13 @@ __metadata:
languageName: node
linkType: hard
"lru-cache@npm:^9.0.3":
version: 9.0.3
resolution: "lru-cache@npm:9.0.3"
checksum: 218415714d44c113bc3a8d12ceca6dedf310915aa861f9e0df13df1fe6db9833e1b5f1f656e9a117ac82677ad3e499be23bff2f670f2a7c5c186d64a92596b68
languageName: node
linkType: hard
"lru-cache@npm:~4.0.0":
version: 4.0.2
resolution: "lru-cache@npm:4.0.2"