Hello everyone, Iām the CEO of NewToki, a webtoon platform where my team and I manage everything from coding to deployment. Iām also personally involved in writing some parts of the code, so I get hands-on with all the technical challenges. Recently, while optimizing the site for faster load times, I ran into a critical issue that I wanted to share here to see if anyone has encountered something similar.
We noticed that our episode pages were loading extremely slowly for certain users, even though our server response times were normal. After digging, I realized the problem was related to a recursive data fetch in our Next.js API route. Essentially, each episode page was fetching its metadata along with the metadata of related episodes, and each related episode was again fetching its related episodes, causing an infinite loop of API calls. This is a simplified example of what the code looked like:
`// pages/api/episode/[id].js
export default async function handler(req, res) {
const { id } = req.query;
const episode = await fetchEpisodeFromDB(id);
// Problem: fetching related episodes recursively without depth limit
episode.related = await fetchRelatedEpisodes(episode.relatedIds);
res.status(200).json({ episode });
}
async function fetchRelatedEpisodes(ids) {
return Promise.all(ids.map(async (relatedId) => {
const relatedEpisode = await fetchEpisodeFromDB(relatedId);
// Recursive call causing performance issue
relatedEpisode.related = await fetchRelatedEpisodes(relatedEpisode.relatedIds);
return relatedEpisode;
}));
}
`
The issue was hard to spot because it only occurred for episodes with many related entries. Once identified, we implemented a depth limit and memoization to prevent repeated fetches, which drastically improved performance.
From this experience, I learned how important it is to test API logic with complex data scenarios, especially in content-heavy platforms like ours. Even a seemingly small recursive fetch can completely slow down your site if not handled carefully.
Iād love to hear if anyone here has faced similar challenges with recursive API calls or Next.js data fetching patterns. Sharing experiences like this really helps the community grow.
Thanks!
Top comments (0)