The two errors are essentially the same thing, but one is designed to appear in Apex/API contexts, the other is meant for UI contexts (e.g. a user is editing a record in the UI). The cause is typically because of data skew, such as mentioned in Reducing Lock Contention by Avoiding Account Data Skew. There's not necessarily a "code" solution for this, since it simply means that there's too much database contention.
Having one user own a majority/all records of any type is more will increase contention. Try to make sure that users own the correct records as necessary. The more evenly spread out your records are, the better performance you'll get.
Do not place all of your child records on a single parent record. For example, do not place every Contact in your org on a single Account. The general rule of thumb is to not go over 10,000 children per parent, but you should keep accounts as small as possible.
Minimize Transaction Time
Optimize your code to use the least amount of time possible. Use debug logs to find out which sections you need to optimize.
There is no "silver bullet" solution to this. You'll need to look at your code, see what it's doing, check all objects it touches (including master records for detail records), run reports for ownership skew and master/account skew, move records around as appropriate, try to optimize your triggers and any other code that uses these records (e.g. Visualforce, Lightning). Overall, it might be a simple fix, or incredibly complicated, but it's not something we can answer directly to your situation, since it would require significant analysis.