0

I'm developing a Sinatra app which uses unicorn. Each worker is one thread, it loads the whole application, they just share the db. (please correct my if I'm wrong ;) )

The first thread gets the Integer, does something with it and then increments it, the second thread should not get the Integer of the first thread (thread safety), it should only get the incremented Integer.

I did that with blocking, but want to find a better approach because during my research I often read that this is a very bad way of solving my problem as it's not very scaleable.

If you want to see my whole application feel free to check it out on github ;)

le_me
  • 3,089
  • 3
  • 26
  • 28

1 Answers1

2

Seems that you're trying to generate alphanumeric ids for shortened urls. If this is the case, then it's much simpler than you think

Let there be a regular auto-incrementing id integer field. When a new request comes in, you create a record in the database, get its id (which won't be repeated again and other workers won't get it), convert it to an alphanumeric form and save (to another column).

Ruby even includes conversion methods for some cases.

aid = 1746563

s = aid.to_s(36) # => "11fnn"
i = s.to_i(36) # => 1746563

You can just use your methods instead of these.

Update

Since you mentioned that you use Posgresql, there is a perfect tool for this: Sequences!

You can create a sequence and then get auto-incrementing numbers from it, without worrying that another client will get the same value.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • I'm not sure if I get it ;) You mean I should write the long url into the db, get the id (which is automatically generated and unique) and use it to generate my hash? – le_me Oct 11 '12 at 14:44
  • Something like that, yeah (if I understand correctly what you are trying to do). – Sergio Tulentsev Oct 11 '12 at 14:45
  • hmm sounds good, I'll try it and then post what happened, thx so long :D – le_me Oct 11 '12 at 14:46
  • @your edit: I use data-mapper and the "Serial" data type for the id field. It works like a charm :D – le_me Oct 11 '12 at 21:07