Refactor API to be threadsafe