I am working on AWS lambda (Stateless service where you can run your code) Link - What is AWS lambda
In my case, ,lambda is running 1 service, for which every request has to perform write operation. Every request binds with one Id.
If, requests are binds with same id. Then, that should have to process sequentially.
So, to do this. we have to take lock on "id". That way, we can avoid write operation clashes.
To do this(My research)-
- Create MySQL table with 1 column of Id, and it is primary key. Means, you cannot persist 1 id more than 1 time.
Pseudocode-
acquirelock
perform write operation
release lock
Here, acquire lock means -
If, id is already present, then wait, else insert id into Mysql table
release means-
Delete id from MySQL
Code-
public void run() {
String host = "AWS-RDS_HOST";
String userName = "USERNAME";
String password = "PASSWORD";
String dbName = "DBNAME";
Connection connection = createConnection(host, userName, password, dbName);
Statement statement = null;
try {
statement = connection.createStatement();
} catch(SQLException e) {
throw new RuntimeException("Failed at taking statement");
}
// Aquire lock.
while(true) {
try {
statement.executeUpdate("insert into locktable values('"+id+"');");
} catch(SQLException e) {
System.out.println("Failed in taking lock. Waiting for others to release the lock.");
continue;
}
System.out.println("Yes...I took lock");
break;
}
// Execute write operation
System.out.println("Doing write operation");
System.out.println("Wrtie operation completed");
// Release lock.
while(true) {
try {
statement.executeUpdate("DELETE from locktable where id='"+id+"'");
} catch(SQLException e) {
System.out.println("Failed to remove lock - " + id);
continue;
}
System.out.println("Lock removed. Id - " + id);
break;
}
}`
Questions-
- Is this idea correct to maintain sequential behaviour for same id ?
- Is there any better solution/idea for this problem ?
- If you have some blogs for such problem, please share me.