back arrow

Taking note about Rails instability asynchronous code

24 - 06 - 2023

I don’t want this article to be a simple venting for the language I’m learning to use but the reason for my frustration with this task perhaps coming from my lack of knowledge about all the gotchas of the language. Therefore this is a note or even a recording of the issue or experience that I have when using Ruby on Rails.

My story start with this task of attaching an avatar image from AWS to each User entity in my database. This project was initiated by my boss and he chose active storage for images management. I followed the documentation here to get my job done. My code would look like this:

    user_ids = (1..100).to_a{ |id| User.find_by(id: id).image.attach(
        filename: "#{id}.png"
    ) }

All of my avatar images were uploaded to AWS beforehand and the format of each image can be imagined as this https://aws-avatar-link/#{id}.png. I logged in to my rails console at production to run this code. This choice may not be the best practice but this would demonstrate my point. My expectation for this code is that for each iteration of the user_ids array, one file from aws would be read and another file would be uploaded to aws while new record is inserted into active storage.

My expectation is not completely wrong but there is one issue though. Among 100 files that were attached to each user, there were a few dozens failed quietly.

How did I realize it?

Well I came to the admin app to check the avatar image and some user in my list did not have their avatar. I have to run this code for those user one by one to fix this.

This incident makes me think that during the process of reading the file, searching for the user, uploading it and insert new records to active_storage_blobs and active_storage_attachments table, some processes or tasks have either failed or skipped silently. This is actually not what bother me but when writing the above code (with help of ChatGPT I admit), there are absolutely no signs of asynchronicity so I naively think that the code would run flawlessly.

Coming from javascript background I am always aware that callback, promise or async/await would be the places for side effect and instability to appear but I can’t find it in the above code. This makes me quite uncomfortable!

Maybe it is just because I am unexperienced. Hopefully with time things would be easier to reason about!