How to send client data of a random song from large playlist?

I created an API that returns data about a song on my server, including the stream URL. When a client calls the API, it'll get the data, and start streaming the song in their player.

But now that I have multiple clients making the call to the API, what is the best way to return data about a random song in the playlist that they haven't heard recently? There are a couple thousand of song and still expanding.

So my question is the whether the following is a good approach:

Here is what I am planning on doing. Set up sessions for each client, and on the initial request, I take all the songs, generate a random list, save it in a cache along with their session ID, then on every subsequent request, I check their session ID, and grab and return the next song data?

As for making sure of not playing a recently played song, I'll have a history of the previous 50 songs listened to in a database, and do a song ID comparison, and fetch the next song if matched?

Would this be a working approach?

EDITED: Got more info of the server.

Store X amount of songs in user's listening history (buffer, size X). Implement a single function for requesting a random song. When client requires a new random song:

  1. pick a random song from your database
  2. push the song ID to the listening history buffer.
  3. return the data to client

There's actually no need to maintain a random generated song list if you are planning to store user data on the server anyways.

Otherwise, you're pretty much on point. Use sessions to identify a user.

Assuming you are using a database like mysql, or anything that associates and ID with a song, you can generate a random number and use that to select a random song from the database. Any ID based data store would work for this and would scale extremely well.

If you know your highest song ID is X, then generate a random number between 1 and X, call it Y. The perform a query like this:

SELECT * FROM songs WHERE song_id>=Y LIMIT 1

That will allow for gaps in your ID and will be really fast. You could keep a log of the songs played in another table and filter those out. If the query returns no results, then invert the random number like Y = X-Y, and then run the query again.