Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42828

Can we achieve strong consistency by using purely get_or_insert and get_by_id, without parent entity and transaction

I had built a back-end system, to support 7 days free trial feature of a mobile app. It consists of 2 APIs

In my use case, strong consistency is important.

My main concern is, will the following code able to achieve strong consistency?

As


class User(ndb.Model):
    email = ndb.StringProperty(required = True)
    timestamp = ndb.DateTimeProperty(required = True)


class RegisterHandler(webapp2.RequestHandler):
    def get(self):
        result = {
            'email' : email,
            'user_timestamp' : 0,
        }

        email = self.request.get('email')
        user_timestamp = int(time.time())
        user = User.get_or_insert(email, email=email, timestamp=datetime.datetime.fromtimestamp(user_timestamp))

        result['user_timestamp'] = int(time.mktime(user.timestamp.timetuple()))
        self.response.headers['Content-Type'] = 'application/json'
        json_result = json.encode(result)
        self.response.out.write(json_result)


class QueryHandler(webapp2.RequestHandler):
    def get(self):
        result = {
            'email' : email,
            'user_timestamp' : 0,
        }

        email = self.request.get('email')
        user = User.get_by_id(email)

        if user is not None:
            result['user_timestamp'] = int(time.mktime(user.timestamp.timetuple()))

        self.response.headers['Content-Type'] = 'application/json'
        json_result = json.encode(result)
        self.response.out.write(json_result)

Upvotes: 0

Views: 85

Answers (1)

Greg
Greg

Reputation: 10360

Yes, gets by key (i.e. by id) are always strongly consistent. Eventual consistency is only a concern with queries.

get_or_insert though, is running a transaction.

Upvotes: 1

Related Questions