Dynamodb PutItem Written Twice

I am new to AWS and I feel like I am missing something important.

I am using this code from a lambda function in nodeJS to create an entry in a DynamoDB table :

function recordUser(item) {
    return ddb.putItem({
        TableName: 'Users',
        Item: item,
        Expected: {
            username: { Exists: false }

username is the primary key of my table.

I though the condition would restrain duplicates to appear but I still see some duplicated entries with same username, what am I missing ?



You are giving "Expected" a wrong interpretation... You seemed to hope that it checks whether there is any existing item in the database with the given value for the "username" attribute. But this is not what Expected does... It does something very different: It reads one specific item - the item with the same key as the one you specified in "Item", and then check whether for this specific item, a value (any value!) exists for its "username" attribute.

To suggest how to fix your use case, we would need to know more about your data. The easiest solution is, of course, to have a table whose sole key is "username", which will allow just one item per username. But I don't know if this is good enough for your usecase.