Senior
Where should you put COMMIT and ROLLBACK in a worker?
sobes.tech AI
Answer from AI
In a worker that processes tasks using transactions, a COMMIT should be issued after the successful completion of all operations related to the task to record the changes in the database. If an error occurs during processing, a ROLLBACK should be performed to undo all changes and maintain data consistency.
Example in Go using a database:
func processTask(tx *sql.Tx, task Task) error {
// Processing the task
err := doWork(tx, task)
if err != nil {
tx.Rollback() // Rollback on error
return err
}
return tx.Commit() // Commit on success
}
Thus, COMMIT is placed at the end of successful processing, and ROLLBACK in case of errors to avoid partially applied changes.