Implementing Bottleneck to control the rate of API requests within a software tool

In TypeScript, I am developing an API wrapper with asynchronous code to abide by the rate limit of 1 request/second set by the particular API. My goal is to create a single instantiated API wrapper that enables access to different endpoints using objects. For example, within the API there are endpoints named post and pool, which I aim to reach like this:

post_object.post.submit_request(argument1, ...)
or
post_object.pool.submit_request(argument1, ...)
.

To maintain information across objects, I implemented an object called state_info containing headers like user-agent, login data if provided, and a rate limiter from the Bottleneck library.

During testing, I encountered an issue where my program does not seem to be effectively limiting the request rate. Regardless of adjusting the limit in Bottleneck's arguments, requests consistently occur in about .600 seconds each time.

I suspect the problem could be related to passing around the rate limiter object or accessing it from multiple places, but I'm uncertain about the exact cause.

Here is the snippet for the Model object representing API access:

Code snippet for Model object goes here...

And below is how I instantiate and call this class:

Code snippet for instantiation and method calls goes here...

Despite setting the minimum time between requests (mintime) to 1000 milliseconds and allowing only one concurrent request per second, the actual operation finishes much faster than anticipated, averaging half the expected duration. This discrepancy persists regardless of what value I provide for mintime.

Answer №1

After much contemplation, I have finally unraveled the solution to my own inquiry.

Surprisingly, nestled in the "gotchas" segment of the bottleneck API reference, they make mention:

If you're passing an object's method as a job, you'll probably need to bind() the object:

Take heed of this code snippet:

// rather than this:
limiter.schedule(object.doSomething);
// opt for this:
limiter.schedule(object.doSomething.bind(object));
// alternatively, encase it within an arrow function like this:
limiter.schedule(() => object.doSomething());

This was precisely the hurdle I encountered. I neglected to bind the scope when transferring axios(axiosContext), hence nothing made its way to the bottleneck ratelimiter. By wrapping it accordingly:

this.state_info.rateLimiter.schedule(() => axios(axiosContext));
I successfully bound the context where necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

Having trouble getting Plaid Link to open when using a combination of Javascript and Python

Whenever I try to call the plaid link handler, it spins for a while and then disappears. I am facing an issue where the link dialog box does not show completely, preventing me from accessing the access token. My setup involves using Flask for the Python se ...

How can I extract a specific data value from a JSON file in Ionic 2?

Here is the JSON data: [ { "id": 1, "label": "saw", "total": "100" }, { "id": 2, "label": "saw1", "total": "300" }, { "id": 3, "label": "saw2", "total": "400" } ] Below is my Typescript code snippet: this. ...

Unable to determine the data type of the property within the table object

Is it feasible to retrieve the type of object property when that object is nested within a table structure? Take a look at this playground. function table<ROW extends object, K extends Extract<keyof ROW, string>>({ columns, data, }: { col ...

Retrieving user input in React by utilizing the onChange event handler

I have been tasked with creating a Quiz App and I am currently working on building it. The app consists of several components such as "question", "question-list", and "add-question". Within the "add-question" component, there is a form that allows users ...

Error message: React router issue (Prop type failure: Prop `children` supplied to `Switch` is invalid, expecting a ReactNode.)

Trying to modify a component in order to create a login page, I attempted to modify App.js but encountered an error. warning.js?6327:36 Warning: Failed prop type: Invalid prop children supplied to Switch, expected a ReactNode. This is the code I have ...

Enable users to handle the version of a dependency in an npm package

As I develop a module that relies on THREE.js, I am exploring the most effective method to include THREE as a dependency and ensure accessibility for both the module and its users. My goal is to provide users with access to the THREE library within their p ...

Error message: "Lazy-loaded modules encounter a TypeError stating that '' is not a function when accessed through NGINX."

Hey, I've got some distribution files for you to check out: AOT-enabled dist with Lazy Modules No AOT Lazy Modules dist AOT without Lazy Modules dist Here's what's been going on: When served locally with webpack-dev-server or live-serve ...

Encountering issues when attempting to deploy an Angular 8 application locally on IIS, receiving an error stating 'The server is returning a non-JavaScript MIME type of "text/html"'

Trying to deploy my Angular 8 application hosted within my ASP.NET Core application in the wwwroot folder has been a bit challenging. Previously, I had successfully accomplished this by following these steps: Adjusted the web.config file of the ASP.NET C ...

Generic type mapping of TypeScript interface properties

I am struggling to get this to function correctly interface ObjectPool<Ids, T> { pool: { [K in Ids]: T<K>; }; }; interface Player<Id> { id: Id; } let playerPool: ObjectPool<0 | 1 | 2, Player>; in a way that playerPool[0 ...

Error Encountered: Invalid Parameter Type when Retrieving Item from AWS Dynamo

I've been facing issues when trying to establish a connection between my ReactJS application and AWS DynamoDB. Despite confirming the correctness of the API key, secret key, and region, I keep encountering an InvalidParameterType error. I have even at ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

Struggling with getting render props to work in Next.js version 13

Looking to develop a custom component for Contentful's next 13 live preview feature in the app directory, I thought of creating a client component that can accept a data prop and ensure type safety by allowing a generic type to be passed down. Here is ...

Creating 3D Shapes with three.js

I am currently in the process of importing an STL object into my three.js scene. Unfortunately, this particular object seems to be using a large amount of GPU resources for rendering and animation, causing the overall performance of the scene to suffer. B ...

Angular 8 experiencing unexpected collision issues

Currently, I am utilizing Angular 8 with "typescript": "~3.5.3". My objective is to handle the undefined collision in my code. const { testLocation } = this.ngr.getState(); this.step2 = testLocation && testLocation.step2 ? testLocat ...

Where am I going wrong in my attempts to use a callback function?

I am currently attempting to implement a callback function for this particular JavaScript function. function Filtering_GetSite(siteElement) { $.ajax({ type: "POST", url: "samle.asmx/f1", data: "", contentType: "application/json; charset= ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

The object type in Typescript prohibits direct access to its properties

Currently, I am facing an issue while trying to define a variable with the Object type and initialize it with a property. When attempting to access that property, an error message 'Property ____ does not exist on type Object' is displayed. I have ...

The "else" statement is never being executed

Trying to create a form where users enter their first name, last name, and city. If any input is empty or contains numbers, a message should appear requesting to fill out all boxes without numbers. Otherwise, display a personalized quote using the input in ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...