Parallelising the pull
The Last.fm API is rateālimited and the script currently sleeps between calls, so parallelism helps if we restructure the workflow to reduce roundātrip latency, not to increase request volume.
Currently the api_call() is written to be called serially, one week at a time, with a flat --delay between calls to stay under Last.fmās 5 requests/second/IP limit. Thatās easy to reason about but leaves speed on the table. A full ~1,120-week pull spends most of its time waiting rather than fetching.
The current script:
- Fetches week list
- For each week:
- call weekly artist chart
- sleep
- write results
This means the total runtime is:
weeks Ć (APIĀ latency + delay)
For a user with ~800 weeks of history, thatās easily 10ā20 minutes.
Where async helps
Async improves speed when:
- you have many independent API calls
- each call has nonātrivial latency (Last.fm often takes 200ā500ms)
- you can pipeline requests without exceeding rate limits
- this script fits this pattern.
Where async doesnāt help
If you simply fire off 800 requests at once, Last.fm will:
- return 429 rate limit errors
- possibly ban your API key temporarily
So the async version must still throttle requests. Enter asynchio semaphores. Iām not going to go into any depth for this as itās something Iām new to and clearly thereās plenty to read, that said, itās really interesting!
Back to this, this script pulls once, writes a file, and the file gets checked in. Thereās no server component and nothing here is about scaling it up to run anywhere but a laptop.
Further reading
I came across this interesting blog post about asynchio semaphores and the handling of concurrent processes. Like I said, this is a topic for another time. I want some time to look into it and play.