Skip to content

Commit

Permalink
Improve requests to polling endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
aron committed Dec 8, 2023
1 parent 9ee1272 commit 3c00ccb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
1 change: 1 addition & 0 deletions middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const ratelimit = new Ratelimit({
// 20 requests from the same IP within a 10 second sliding window
limiter: Ratelimit.slidingWindow(20, '10s'),
prefix: `v2/zoo/ratelimit/${process.env.VERCEL_ENV ?? 'local'}`,
timeout: 500,
});

// Rate limit the /api/predictions/[id] endpoint
Expand Down
33 changes: 29 additions & 4 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ export default function Home({ baseUrl, submissionPredictions }) {
const response = await fetch(`/api/submissions/${seed}`, {
method: "GET",
});
submissionPredictions = await response.json();
if (response.ok) {
submissionPredictions = await response.json();
}
setPredictions(submissionPredictions);

// get the model names from the predictions, and update which ones are checked
Expand Down Expand Up @@ -151,17 +153,36 @@ export default function Home({ baseUrl, submissionPredictions }) {
throw new Error(prediction.detail);
}

// Add incremental backoff for polling requests.
const backoff = [250, 500, 500, 750, 1000, 1500, 3000, 5000, 10000, 15000, 30000];

while (
prediction.status !== "succeeded" &&
prediction.status !== "failed"
) {
await sleep(500);
const jitter = random(0, 100); // Don't make all requests at the same time.
const delay = backoff.shift();
if (!delay) {
// We've exceeded our timeout.
// TODO: Better user facing messaging here.
break;
}

await sleep(delay + jitter);
const response = await fetch("/api/predictions/" + prediction.id);
prediction = await response.json();
console.log(prediction);

// Handle Rate Limiting
if (response.status === 429) {
const reset = response.headers.get('X-Ratelimit-Reset') ?? Date.now() + 10_000;
const wait = reset - Date.now();
await sleep(wait)
continue;
}

if (response.status !== 200) {
throw new Error(prediction.detail);
}
prediction = await response.json();
}

prediction.model = model.name;
Expand Down Expand Up @@ -551,3 +572,7 @@ export async function getServerSideProps({ req }) {

return { props: { baseUrl, submissionPredictions } };
}

function random(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}

0 comments on commit 3c00ccb

Please sign in to comment.