What are the mechanics of verifying that an output transaction is not spent? I am trying to understand the mechanics of how a bitcoin transaction works. When the output gets consumed by a later transaction, who and how prevents this output from being consumed a second time? Do we go over all the transactions after to make sure it hasn't been used?

I am not sure what are the right tags for this kind of questions
When the output gets consumed by a later transaction, who and how prevents this output from being consumed a second time? Do we go over all the transactions after to make sure it hasn't been used?


Full nodes keep track of all unspent outputs in the blockchain, known as UTXOs (unspent transaction outputs). This is the UTXO set. When a transaction in the blockchain spends a UTXO, it is removed from that set, and new UTXOs are added for the new outputs from that transaction. This happens every time a new block is received. If a transaction tries to spend a UTXO which isn't in the set, the node sees it as invalid. To that node, there is no difference between spending from a transaction which has already been spent, or one which never existed. Either way, there is no valid UTXO to spend from in the UTXO set, so its an invalid transaction.