Reputation: 619
I was going through this Instagram engineering article where in they had mentioned about denormalizing counters, I quote
To reduce the resources needed for each of these operations, we denormalized the counter for likes on the post. Whenever a new like comes in, the count is increased in the database. Therefore, each read of the count will just be a simple “select” which is a lot more efficient.
There is also an added benefit of denormalizing counters in the same database where the liker to the post is stored. Both updates can be included in one transaction, making the updates atomic and consistent all the time. Whereas before the change, the counter in cache could be inconsistent with what was stored in the database due to timeout, retries etc.
I tried to update the counter table and a normal table which had the user who liked the post in a batch using,
BEGIN BATCH
UPDATE postlike_counter_counter
set likecount = likecount+1
where postid = c77b9e44-379b-11e7-93dc-dd4982fae088;
INSERT INTO postlikes (postid, likedtime, likedby) values(c77b9e44-379b-11e7-93dc-dd4982fae088, unixTimestampOf(now()),
{"firstname": 'fname', "lastname": 'lname', "profileimgurl":'img/pic'});
APPLY BATCH;
I see the error, Counter mutations are only allowed in COUNTER batches If i make it as a counter batch, i get, Only counter mutations are allowed in COUNTER batches
Is there any way I can make this work? If not, what exactly did the article mean when they wrote the above quoted lines?
Upvotes: 0
Views: 2086
Reputation: 3463
Ashraful Islam has answered the question why Cassandra does not allow to mix counter query and non counter query in a single batch. But the context that you have quoted is not happening in the cassandra world. Instagram engineering article (De-normalizing Counters) is trying to explaining in the PgQ world (Where it is possible actually, also they are not counter data type but maintaining as sort of counters)
Upvotes: 3
Reputation: 12830
Counter Update and Normal Update can't be used at the same batch.
Counter batches cannot include non-counter columns in the DML statements, just as a non-counter batch cannot include counter columns. Counter batch statements cannot provide custom timestamps.
You have to use separate batch.
First you can apply the counter batch, if success then apply the non-counter batch. If non-counter batch failed toggle the sign of the counter statements (set a = a + 1 to a = a - 1
or vise versa) and apply the batch.
In Java Here is how you can check a batch is success by wasApplied()
method
ResultSet resultSet = session.execute(batch);
if(resultSet.wasApplied()) {
// Batch success
}
Source : https://docs.datastax.com/en/cql/3.3/cql/cql_reference/cqlBatch.html
Upvotes: 0