def sync_last_active_at(): """ Update User model with the active_at timestamp from Redis. We first fetch all the user_ids to update, and then fetch the timestamp to minimize the time between fetching the value and updating the DB. This is because there might be a more recent update we skip otherwise. """ user_ids = redis_connection.hkeys(LAST_ACTIVE_KEY) for user_id in user_ids: timestamp = redis_connection.hget(LAST_ACTIVE_KEY, user_id) active_at = dt_from_timestamp(timestamp) user = User.query.filter(User.id == user_id).first() if user: user.active_at = active_at redis_connection.hdel(LAST_ACTIVE_KEY, user_id) db.session.commit()